PackageManagerService.java revision 104e14531ca2212117540d8b6abc06ab67564ebc
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.Manifest.permission.INSTALL_PACKAGES;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.os.Process.PACKAGE_INFO_GID;
28import static android.os.Process.SYSTEM_UID;
29import static android.system.OsConstants.S_IRGRP;
30import static android.system.OsConstants.S_IROTH;
31import static android.system.OsConstants.S_IRWXU;
32import static android.system.OsConstants.S_IXGRP;
33import static android.system.OsConstants.S_IXOTH;
34import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
35import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
36import static com.android.internal.util.ArrayUtils.appendInt;
37import static com.android.internal.util.ArrayUtils.removeInt;
38
39import com.android.internal.R;
40import com.android.internal.app.IMediaContainerService;
41import com.android.internal.app.ResolverActivity;
42import com.android.internal.content.NativeLibraryHelper;
43import com.android.internal.content.NativeLibraryHelper.ApkHandle;
44import com.android.internal.content.PackageHelper;
45import com.android.internal.util.FastPrintWriter;
46import com.android.internal.util.FastXmlSerializer;
47import com.android.internal.util.XmlUtils;
48import com.android.server.EventLogTags;
49import com.android.server.IntentResolver;
50import com.android.server.LocalServices;
51import com.android.server.ServiceThread;
52import com.android.server.Watchdog;
53import com.android.server.pm.Settings.DatabaseVersion;
54import com.android.server.storage.DeviceStorageMonitorInternal;
55import com.android.server.storage.DeviceStorageMonitorInternal;
56
57import org.xmlpull.v1.XmlPullParser;
58import org.xmlpull.v1.XmlPullParserException;
59import org.xmlpull.v1.XmlSerializer;
60
61import android.app.ActivityManager;
62import android.app.ActivityManagerNative;
63import android.app.IActivityManager;
64import android.app.PackageInstallObserver;
65import android.app.admin.IDevicePolicyManager;
66import android.app.backup.IBackupManager;
67import android.content.BroadcastReceiver;
68import android.content.ComponentName;
69import android.content.Context;
70import android.content.IIntentReceiver;
71import android.content.Intent;
72import android.content.IntentFilter;
73import android.content.IntentSender;
74import android.content.IntentSender.SendIntentException;
75import android.content.ServiceConnection;
76import android.content.pm.ActivityInfo;
77import android.content.pm.ApplicationInfo;
78import android.content.pm.ContainerEncryptionParams;
79import android.content.pm.FeatureInfo;
80import android.content.pm.IPackageDataObserver;
81import android.content.pm.IPackageDeleteObserver;
82import android.content.pm.IPackageInstallObserver;
83import android.content.pm.IPackageInstallObserver2;
84import android.content.pm.IPackageInstaller;
85import android.content.pm.IPackageManager;
86import android.content.pm.IPackageMoveObserver;
87import android.content.pm.IPackageStatsObserver;
88import android.content.pm.InstrumentationInfo;
89import android.content.pm.ManifestDigest;
90import android.content.pm.PackageCleanItem;
91import android.content.pm.PackageInfo;
92import android.content.pm.PackageInfoLite;
93import android.content.pm.PackageInstallerParams;
94import android.content.pm.PackageManager;
95import android.content.pm.PackageParser.ActivityIntentInfo;
96import android.content.pm.PackageParser;
97import android.content.pm.PackageStats;
98import android.content.pm.PackageUserState;
99import android.content.pm.ParceledListSlice;
100import android.content.pm.PermissionGroupInfo;
101import android.content.pm.PermissionInfo;
102import android.content.pm.ProviderInfo;
103import android.content.pm.ResolveInfo;
104import android.content.pm.ServiceInfo;
105import android.content.pm.Signature;
106import android.content.pm.VerificationParams;
107import android.content.pm.VerifierDeviceIdentity;
108import android.content.pm.VerifierInfo;
109import android.content.res.Resources;
110import android.hardware.display.DisplayManager;
111import android.net.Uri;
112import android.os.Binder;
113import android.os.Build;
114import android.os.Bundle;
115import android.os.Environment;
116import android.os.Environment.UserEnvironment;
117import android.os.FileObserver;
118import android.os.FileUtils;
119import android.os.Handler;
120import android.os.IBinder;
121import android.os.Looper;
122import android.os.Message;
123import android.os.Parcel;
124import android.os.ParcelFileDescriptor;
125import android.os.Process;
126import android.os.RemoteException;
127import android.os.SELinux;
128import android.os.ServiceManager;
129import android.os.SystemClock;
130import android.os.SystemProperties;
131import android.os.UserHandle;
132import android.os.UserManager;
133import android.security.KeyStore;
134import android.security.SystemKeyStore;
135import android.system.ErrnoException;
136import android.system.Os;
137import android.system.StructStat;
138import android.text.TextUtils;
139import android.util.AtomicFile;
140import android.util.DisplayMetrics;
141import android.util.EventLog;
142import android.util.Log;
143import android.util.LogPrinter;
144import android.util.PrintStreamPrinter;
145import android.util.Slog;
146import android.util.SparseArray;
147import android.util.Xml;
148import android.view.Display;
149
150import java.io.BufferedInputStream;
151import java.io.BufferedOutputStream;
152import java.io.File;
153import java.io.FileDescriptor;
154import java.io.FileInputStream;
155import java.io.FileNotFoundException;
156import java.io.FileOutputStream;
157import java.io.FileReader;
158import java.io.FilenameFilter;
159import java.io.IOException;
160import java.io.InputStream;
161import java.io.PrintWriter;
162import java.nio.charset.StandardCharsets;
163import java.security.NoSuchAlgorithmException;
164import java.security.PublicKey;
165import java.security.cert.CertificateEncodingException;
166import java.security.cert.CertificateException;
167import java.text.SimpleDateFormat;
168import java.util.ArrayList;
169import java.util.Arrays;
170import java.util.Collection;
171import java.util.Collections;
172import java.util.Comparator;
173import java.util.Date;
174import java.util.HashMap;
175import java.util.HashSet;
176import java.util.Iterator;
177import java.util.List;
178import java.util.Map;
179import java.util.Set;
180import java.util.concurrent.atomic.AtomicBoolean;
181import java.util.concurrent.atomic.AtomicLong;
182
183import dalvik.system.DexFile;
184import dalvik.system.StaleDexCacheError;
185import dalvik.system.VMRuntime;
186
187import libcore.io.IoUtils;
188
189/**
190 * Keep track of all those .apks everywhere.
191 *
192 * This is very central to the platform's security; please run the unit
193 * tests whenever making modifications here:
194 *
195mmm frameworks/base/tests/AndroidTests
196adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
197adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
198 *
199 * {@hide}
200 */
201public class PackageManagerService extends IPackageManager.Stub {
202    static final String TAG = "PackageManager";
203    static final boolean DEBUG_SETTINGS = false;
204    static final boolean DEBUG_PREFERRED = false;
205    static final boolean DEBUG_UPGRADE = false;
206    private static final boolean DEBUG_INSTALL = false;
207    private static final boolean DEBUG_REMOVE = false;
208    private static final boolean DEBUG_BROADCASTS = false;
209    private static final boolean DEBUG_SHOW_INFO = false;
210    private static final boolean DEBUG_PACKAGE_INFO = false;
211    private static final boolean DEBUG_INTENT_MATCHING = false;
212    private static final boolean DEBUG_PACKAGE_SCANNING = false;
213    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
214    private static final boolean DEBUG_VERIFY = false;
215    private static final boolean DEBUG_DEXOPT = false;
216
217    private static final int RADIO_UID = Process.PHONE_UID;
218    private static final int LOG_UID = Process.LOG_UID;
219    private static final int NFC_UID = Process.NFC_UID;
220    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
221    private static final int SHELL_UID = Process.SHELL_UID;
222
223    // Cap the size of permission trees that 3rd party apps can define
224    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
225
226    private static final int REMOVE_EVENTS =
227        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
228    private static final int ADD_EVENTS =
229        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
230
231    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
232    // Suffix used during package installation when copying/moving
233    // package apks to install directory.
234    private static final String INSTALL_PACKAGE_SUFFIX = "-";
235
236    static final int SCAN_MONITOR = 1<<0;
237    static final int SCAN_NO_DEX = 1<<1;
238    static final int SCAN_FORCE_DEX = 1<<2;
239    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
240    static final int SCAN_NEW_INSTALL = 1<<4;
241    static final int SCAN_NO_PATHS = 1<<5;
242    static final int SCAN_UPDATE_TIME = 1<<6;
243    static final int SCAN_DEFER_DEX = 1<<7;
244    static final int SCAN_BOOTING = 1<<8;
245    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
246    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
247
248    static final int REMOVE_CHATTY = 1<<16;
249
250    /**
251     * Timeout (in milliseconds) after which the watchdog should declare that
252     * our handler thread is wedged.  The usual default for such things is one
253     * minute but we sometimes do very lengthy I/O operations on this thread,
254     * such as installing multi-gigabyte applications, so ours needs to be longer.
255     */
256    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
257
258    /**
259     * Whether verification is enabled by default.
260     */
261    private static final boolean DEFAULT_VERIFY_ENABLE = true;
262
263    /**
264     * The default maximum time to wait for the verification agent to return in
265     * milliseconds.
266     */
267    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
268
269    /**
270     * The default response for package verification timeout.
271     *
272     * This can be either PackageManager.VERIFICATION_ALLOW or
273     * PackageManager.VERIFICATION_REJECT.
274     */
275    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
276
277    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
278
279    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
280            DEFAULT_CONTAINER_PACKAGE,
281            "com.android.defcontainer.DefaultContainerService");
282
283    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
284
285    private static final String LIB_DIR_NAME = "lib";
286    private static final String LIB64_DIR_NAME = "lib64";
287
288    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
289
290    static final String mTempContainerPrefix = "smdl2tmp";
291
292    private static String sPreferredInstructionSet;
293
294    final ServiceThread mHandlerThread;
295
296    private static final String IDMAP_PREFIX = "/data/resource-cache/";
297    private static final String IDMAP_SUFFIX = "@idmap";
298
299    final PackageHandler mHandler;
300
301    final int mSdkVersion = Build.VERSION.SDK_INT;
302
303    final Context mContext;
304    final boolean mFactoryTest;
305    final boolean mOnlyCore;
306    final DisplayMetrics mMetrics;
307    final int mDefParseFlags;
308    final String[] mSeparateProcesses;
309
310    // This is where all application persistent data goes.
311    final File mAppDataDir;
312
313    // This is where all application persistent data goes for secondary users.
314    final File mUserAppDataDir;
315
316    /** The location for ASEC container files on internal storage. */
317    final String mAsecInternalPath;
318
319    // This is the object monitoring the framework dir.
320    final FileObserver mFrameworkInstallObserver;
321
322    // This is the object monitoring the system app dir.
323    final FileObserver mSystemInstallObserver;
324
325    // This is the object monitoring the privileged system app dir.
326    final FileObserver mPrivilegedInstallObserver;
327
328    // This is the object monitoring the vendor app dir.
329    final FileObserver mVendorInstallObserver;
330
331    // This is the object monitoring the vendor overlay package dir.
332    final FileObserver mVendorOverlayInstallObserver;
333
334    // This is the object monitoring the OEM app dir.
335    final FileObserver mOemInstallObserver;
336
337    // This is the object monitoring mAppInstallDir.
338    final FileObserver mAppInstallObserver;
339
340    // This is the object monitoring mDrmAppPrivateInstallDir.
341    final FileObserver mDrmAppInstallObserver;
342
343    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
344    // LOCK HELD.  Can be called with mInstallLock held.
345    final Installer mInstaller;
346
347    final File mAppInstallDir;
348
349    /**
350     * Directory to which applications installed internally have native
351     * libraries copied.
352     */
353    private File mAppLibInstallDir;
354
355    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
356    // apps.
357    final File mDrmAppPrivateInstallDir;
358
359    final File mAppStagingDir;
360
361    // ----------------------------------------------------------------
362
363    // Lock for state used when installing and doing other long running
364    // operations.  Methods that must be called with this lock held have
365    // the suffix "LI".
366    final Object mInstallLock = new Object();
367
368    // These are the directories in the 3rd party applications installed dir
369    // that we have currently loaded packages from.  Keys are the application's
370    // installed zip file (absolute codePath), and values are Package.
371    final HashMap<String, PackageParser.Package> mAppDirs =
372            new HashMap<String, PackageParser.Package>();
373
374    // Information for the parser to write more useful error messages.
375    int mLastScanError;
376
377    // ----------------------------------------------------------------
378
379    // Keys are String (package name), values are Package.  This also serves
380    // as the lock for the global state.  Methods that must be called with
381    // this lock held have the prefix "LP".
382    final HashMap<String, PackageParser.Package> mPackages =
383            new HashMap<String, PackageParser.Package>();
384
385    // Tracks available target package names -> overlay package paths.
386    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
387        new HashMap<String, HashMap<String, PackageParser.Package>>();
388
389    final Settings mSettings;
390    boolean mRestoredSettings;
391
392    // Group-ids that are given to all packages as read from etc/permissions/*.xml.
393    int[] mGlobalGids;
394
395    // These are the built-in uid -> permission mappings that were read from the
396    // etc/permissions.xml file.
397    final SparseArray<HashSet<String>> mSystemPermissions =
398            new SparseArray<HashSet<String>>();
399
400    static final class SharedLibraryEntry {
401        final String path;
402        final String apk;
403
404        SharedLibraryEntry(String _path, String _apk) {
405            path = _path;
406            apk = _apk;
407        }
408    }
409
410    // These are the built-in shared libraries that were read from the
411    // etc/permissions.xml file.
412    final HashMap<String, SharedLibraryEntry> mSharedLibraries
413            = new HashMap<String, SharedLibraryEntry>();
414
415    // Temporary for building the final shared libraries for an .apk.
416    String[] mTmpSharedLibraries = null;
417
418    // These are the features this devices supports that were read from the
419    // etc/permissions.xml file.
420    final HashMap<String, FeatureInfo> mAvailableFeatures =
421            new HashMap<String, FeatureInfo>();
422
423    // If mac_permissions.xml was found for seinfo labeling.
424    boolean mFoundPolicyFile;
425
426    // If a recursive restorecon of /data/data/<pkg> is needed.
427    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
428
429    // All available activities, for your resolving pleasure.
430    final ActivityIntentResolver mActivities =
431            new ActivityIntentResolver();
432
433    // All available receivers, for your resolving pleasure.
434    final ActivityIntentResolver mReceivers =
435            new ActivityIntentResolver();
436
437    // All available services, for your resolving pleasure.
438    final ServiceIntentResolver mServices = new ServiceIntentResolver();
439
440    // All available providers, for your resolving pleasure.
441    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
442
443    // Mapping from provider base names (first directory in content URI codePath)
444    // to the provider information.
445    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
446            new HashMap<String, PackageParser.Provider>();
447
448    // Mapping from instrumentation class names to info about them.
449    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
450            new HashMap<ComponentName, PackageParser.Instrumentation>();
451
452    // Mapping from permission names to info about them.
453    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
454            new HashMap<String, PackageParser.PermissionGroup>();
455
456    // Packages whose data we have transfered into another package, thus
457    // should no longer exist.
458    final HashSet<String> mTransferedPackages = new HashSet<String>();
459
460    // Broadcast actions that are only available to the system.
461    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
462
463    /** List of packages waiting for verification. */
464    final SparseArray<PackageVerificationState> mPendingVerification
465            = new SparseArray<PackageVerificationState>();
466
467    final PackageInstallerService mInstallerService;
468
469    HashSet<PackageParser.Package> mDeferredDexOpt = null;
470
471    /** Token for keys in mPendingVerification. */
472    private int mPendingVerificationToken = 0;
473
474    boolean mSystemReady;
475    boolean mSafeMode;
476    boolean mHasSystemUidErrors;
477
478    ApplicationInfo mAndroidApplication;
479    final ActivityInfo mResolveActivity = new ActivityInfo();
480    final ResolveInfo mResolveInfo = new ResolveInfo();
481    ComponentName mResolveComponentName;
482    PackageParser.Package mPlatformPackage;
483    ComponentName mCustomResolverComponentName;
484
485    boolean mResolverReplaced = false;
486
487    // Set of pending broadcasts for aggregating enable/disable of components.
488    static class PendingPackageBroadcasts {
489        // for each user id, a map of <package name -> components within that package>
490        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
491
492        public PendingPackageBroadcasts() {
493            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
494        }
495
496        public ArrayList<String> get(int userId, String packageName) {
497            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
498            return packages.get(packageName);
499        }
500
501        public void put(int userId, String packageName, ArrayList<String> components) {
502            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
503            packages.put(packageName, components);
504        }
505
506        public void remove(int userId, String packageName) {
507            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
508            if (packages != null) {
509                packages.remove(packageName);
510            }
511        }
512
513        public void remove(int userId) {
514            mUidMap.remove(userId);
515        }
516
517        public int userIdCount() {
518            return mUidMap.size();
519        }
520
521        public int userIdAt(int n) {
522            return mUidMap.keyAt(n);
523        }
524
525        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
526            return mUidMap.get(userId);
527        }
528
529        public int size() {
530            // total number of pending broadcast entries across all userIds
531            int num = 0;
532            for (int i = 0; i< mUidMap.size(); i++) {
533                num += mUidMap.valueAt(i).size();
534            }
535            return num;
536        }
537
538        public void clear() {
539            mUidMap.clear();
540        }
541
542        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
543            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
544            if (map == null) {
545                map = new HashMap<String, ArrayList<String>>();
546                mUidMap.put(userId, map);
547            }
548            return map;
549        }
550    }
551    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
552
553    // Service Connection to remote media container service to copy
554    // package uri's from external media onto secure containers
555    // or internal storage.
556    private IMediaContainerService mContainerService = null;
557
558    static final int SEND_PENDING_BROADCAST = 1;
559    static final int MCS_BOUND = 3;
560    static final int END_COPY = 4;
561    static final int INIT_COPY = 5;
562    static final int MCS_UNBIND = 6;
563    static final int START_CLEANING_PACKAGE = 7;
564    static final int FIND_INSTALL_LOC = 8;
565    static final int POST_INSTALL = 9;
566    static final int MCS_RECONNECT = 10;
567    static final int MCS_GIVE_UP = 11;
568    static final int UPDATED_MEDIA_STATUS = 12;
569    static final int WRITE_SETTINGS = 13;
570    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
571    static final int PACKAGE_VERIFIED = 15;
572    static final int CHECK_PENDING_VERIFICATION = 16;
573
574    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
575
576    // Delay time in millisecs
577    static final int BROADCAST_DELAY = 10 * 1000;
578
579    static UserManagerService sUserManager;
580
581    // Stores a list of users whose package restrictions file needs to be updated
582    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
583
584    final private DefaultContainerConnection mDefContainerConn =
585            new DefaultContainerConnection();
586    class DefaultContainerConnection implements ServiceConnection {
587        public void onServiceConnected(ComponentName name, IBinder service) {
588            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
589            IMediaContainerService imcs =
590                IMediaContainerService.Stub.asInterface(service);
591            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
592        }
593
594        public void onServiceDisconnected(ComponentName name) {
595            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
596        }
597    };
598
599    // Recordkeeping of restore-after-install operations that are currently in flight
600    // between the Package Manager and the Backup Manager
601    class PostInstallData {
602        public InstallArgs args;
603        public PackageInstalledInfo res;
604
605        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
606            args = _a;
607            res = _r;
608        }
609    };
610    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
611    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
612
613    private final String mRequiredVerifierPackage;
614
615    private final PackageUsage mPackageUsage = new PackageUsage();
616
617    private class PackageUsage {
618        private static final int WRITE_INTERVAL
619            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
620
621        private final Object mFileLock = new Object();
622        private final AtomicLong mLastWritten = new AtomicLong(0);
623        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
624
625        private boolean mIsFirstBoot = false;
626
627        boolean isFirstBoot() {
628            return mIsFirstBoot;
629        }
630
631        void write(boolean force) {
632            if (force) {
633                writeInternal();
634                return;
635            }
636            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
637                && !DEBUG_DEXOPT) {
638                return;
639            }
640            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
641                new Thread("PackageUsage_DiskWriter") {
642                    @Override
643                    public void run() {
644                        try {
645                            writeInternal();
646                        } finally {
647                            mBackgroundWriteRunning.set(false);
648                        }
649                    }
650                }.start();
651            }
652        }
653
654        private void writeInternal() {
655            synchronized (mPackages) {
656                synchronized (mFileLock) {
657                    AtomicFile file = getFile();
658                    FileOutputStream f = null;
659                    try {
660                        f = file.startWrite();
661                        BufferedOutputStream out = new BufferedOutputStream(f);
662                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
663                        StringBuilder sb = new StringBuilder();
664                        for (PackageParser.Package pkg : mPackages.values()) {
665                            if (pkg.mLastPackageUsageTimeInMills == 0) {
666                                continue;
667                            }
668                            sb.setLength(0);
669                            sb.append(pkg.packageName);
670                            sb.append(' ');
671                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
672                            sb.append('\n');
673                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
674                        }
675                        out.flush();
676                        file.finishWrite(f);
677                    } catch (IOException e) {
678                        if (f != null) {
679                            file.failWrite(f);
680                        }
681                        Log.e(TAG, "Failed to write package usage times", e);
682                    }
683                }
684            }
685            mLastWritten.set(SystemClock.elapsedRealtime());
686        }
687
688        void readLP() {
689            synchronized (mFileLock) {
690                AtomicFile file = getFile();
691                BufferedInputStream in = null;
692                try {
693                    in = new BufferedInputStream(file.openRead());
694                    StringBuffer sb = new StringBuffer();
695                    while (true) {
696                        String packageName = readToken(in, sb, ' ');
697                        if (packageName == null) {
698                            break;
699                        }
700                        String timeInMillisString = readToken(in, sb, '\n');
701                        if (timeInMillisString == null) {
702                            throw new IOException("Failed to find last usage time for package "
703                                                  + packageName);
704                        }
705                        PackageParser.Package pkg = mPackages.get(packageName);
706                        if (pkg == null) {
707                            continue;
708                        }
709                        long timeInMillis;
710                        try {
711                            timeInMillis = Long.parseLong(timeInMillisString.toString());
712                        } catch (NumberFormatException e) {
713                            throw new IOException("Failed to parse " + timeInMillisString
714                                                  + " as a long.", e);
715                        }
716                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
717                    }
718                } catch (FileNotFoundException expected) {
719                    mIsFirstBoot = true;
720                } catch (IOException e) {
721                    Log.w(TAG, "Failed to read package usage times", e);
722                } finally {
723                    IoUtils.closeQuietly(in);
724                }
725            }
726            mLastWritten.set(SystemClock.elapsedRealtime());
727        }
728
729        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
730                throws IOException {
731            sb.setLength(0);
732            while (true) {
733                int ch = in.read();
734                if (ch == -1) {
735                    if (sb.length() == 0) {
736                        return null;
737                    }
738                    throw new IOException("Unexpected EOF");
739                }
740                if (ch == endOfToken) {
741                    return sb.toString();
742                }
743                sb.append((char)ch);
744            }
745        }
746
747        private AtomicFile getFile() {
748            File dataDir = Environment.getDataDirectory();
749            File systemDir = new File(dataDir, "system");
750            File fname = new File(systemDir, "package-usage.list");
751            return new AtomicFile(fname);
752        }
753    }
754
755    class PackageHandler extends Handler {
756        private boolean mBound = false;
757        final ArrayList<HandlerParams> mPendingInstalls =
758            new ArrayList<HandlerParams>();
759
760        private boolean connectToService() {
761            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
762                    " DefaultContainerService");
763            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
764            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
765            if (mContext.bindServiceAsUser(service, mDefContainerConn,
766                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
767                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
768                mBound = true;
769                return true;
770            }
771            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
772            return false;
773        }
774
775        private void disconnectService() {
776            mContainerService = null;
777            mBound = false;
778            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
779            mContext.unbindService(mDefContainerConn);
780            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
781        }
782
783        PackageHandler(Looper looper) {
784            super(looper);
785        }
786
787        public void handleMessage(Message msg) {
788            try {
789                doHandleMessage(msg);
790            } finally {
791                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
792            }
793        }
794
795        void doHandleMessage(Message msg) {
796            switch (msg.what) {
797                case INIT_COPY: {
798                    HandlerParams params = (HandlerParams) msg.obj;
799                    int idx = mPendingInstalls.size();
800                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
801                    // If a bind was already initiated we dont really
802                    // need to do anything. The pending install
803                    // will be processed later on.
804                    if (!mBound) {
805                        // If this is the only one pending we might
806                        // have to bind to the service again.
807                        if (!connectToService()) {
808                            Slog.e(TAG, "Failed to bind to media container service");
809                            params.serviceError();
810                            return;
811                        } else {
812                            // Once we bind to the service, the first
813                            // pending request will be processed.
814                            mPendingInstalls.add(idx, params);
815                        }
816                    } else {
817                        mPendingInstalls.add(idx, params);
818                        // Already bound to the service. Just make
819                        // sure we trigger off processing the first request.
820                        if (idx == 0) {
821                            mHandler.sendEmptyMessage(MCS_BOUND);
822                        }
823                    }
824                    break;
825                }
826                case MCS_BOUND: {
827                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
828                    if (msg.obj != null) {
829                        mContainerService = (IMediaContainerService) msg.obj;
830                    }
831                    if (mContainerService == null) {
832                        // Something seriously wrong. Bail out
833                        Slog.e(TAG, "Cannot bind to media container service");
834                        for (HandlerParams params : mPendingInstalls) {
835                            // Indicate service bind error
836                            params.serviceError();
837                        }
838                        mPendingInstalls.clear();
839                    } else if (mPendingInstalls.size() > 0) {
840                        HandlerParams params = mPendingInstalls.get(0);
841                        if (params != null) {
842                            if (params.startCopy()) {
843                                // We are done...  look for more work or to
844                                // go idle.
845                                if (DEBUG_SD_INSTALL) Log.i(TAG,
846                                        "Checking for more work or unbind...");
847                                // Delete pending install
848                                if (mPendingInstalls.size() > 0) {
849                                    mPendingInstalls.remove(0);
850                                }
851                                if (mPendingInstalls.size() == 0) {
852                                    if (mBound) {
853                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
854                                                "Posting delayed MCS_UNBIND");
855                                        removeMessages(MCS_UNBIND);
856                                        Message ubmsg = obtainMessage(MCS_UNBIND);
857                                        // Unbind after a little delay, to avoid
858                                        // continual thrashing.
859                                        sendMessageDelayed(ubmsg, 10000);
860                                    }
861                                } else {
862                                    // There are more pending requests in queue.
863                                    // Just post MCS_BOUND message to trigger processing
864                                    // of next pending install.
865                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
866                                            "Posting MCS_BOUND for next work");
867                                    mHandler.sendEmptyMessage(MCS_BOUND);
868                                }
869                            }
870                        }
871                    } else {
872                        // Should never happen ideally.
873                        Slog.w(TAG, "Empty queue");
874                    }
875                    break;
876                }
877                case MCS_RECONNECT: {
878                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
879                    if (mPendingInstalls.size() > 0) {
880                        if (mBound) {
881                            disconnectService();
882                        }
883                        if (!connectToService()) {
884                            Slog.e(TAG, "Failed to bind to media container service");
885                            for (HandlerParams params : mPendingInstalls) {
886                                // Indicate service bind error
887                                params.serviceError();
888                            }
889                            mPendingInstalls.clear();
890                        }
891                    }
892                    break;
893                }
894                case MCS_UNBIND: {
895                    // If there is no actual work left, then time to unbind.
896                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
897
898                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
899                        if (mBound) {
900                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
901
902                            disconnectService();
903                        }
904                    } else if (mPendingInstalls.size() > 0) {
905                        // There are more pending requests in queue.
906                        // Just post MCS_BOUND message to trigger processing
907                        // of next pending install.
908                        mHandler.sendEmptyMessage(MCS_BOUND);
909                    }
910
911                    break;
912                }
913                case MCS_GIVE_UP: {
914                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
915                    mPendingInstalls.remove(0);
916                    break;
917                }
918                case SEND_PENDING_BROADCAST: {
919                    String packages[];
920                    ArrayList<String> components[];
921                    int size = 0;
922                    int uids[];
923                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
924                    synchronized (mPackages) {
925                        if (mPendingBroadcasts == null) {
926                            return;
927                        }
928                        size = mPendingBroadcasts.size();
929                        if (size <= 0) {
930                            // Nothing to be done. Just return
931                            return;
932                        }
933                        packages = new String[size];
934                        components = new ArrayList[size];
935                        uids = new int[size];
936                        int i = 0;  // filling out the above arrays
937
938                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
939                            int packageUserId = mPendingBroadcasts.userIdAt(n);
940                            Iterator<Map.Entry<String, ArrayList<String>>> it
941                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
942                                            .entrySet().iterator();
943                            while (it.hasNext() && i < size) {
944                                Map.Entry<String, ArrayList<String>> ent = it.next();
945                                packages[i] = ent.getKey();
946                                components[i] = ent.getValue();
947                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
948                                uids[i] = (ps != null)
949                                        ? UserHandle.getUid(packageUserId, ps.appId)
950                                        : -1;
951                                i++;
952                            }
953                        }
954                        size = i;
955                        mPendingBroadcasts.clear();
956                    }
957                    // Send broadcasts
958                    for (int i = 0; i < size; i++) {
959                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
960                    }
961                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
962                    break;
963                }
964                case START_CLEANING_PACKAGE: {
965                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
966                    final String packageName = (String)msg.obj;
967                    final int userId = msg.arg1;
968                    final boolean andCode = msg.arg2 != 0;
969                    synchronized (mPackages) {
970                        if (userId == UserHandle.USER_ALL) {
971                            int[] users = sUserManager.getUserIds();
972                            for (int user : users) {
973                                mSettings.addPackageToCleanLPw(
974                                        new PackageCleanItem(user, packageName, andCode));
975                            }
976                        } else {
977                            mSettings.addPackageToCleanLPw(
978                                    new PackageCleanItem(userId, packageName, andCode));
979                        }
980                    }
981                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
982                    startCleaningPackages();
983                } break;
984                case POST_INSTALL: {
985                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
986                    PostInstallData data = mRunningInstalls.get(msg.arg1);
987                    mRunningInstalls.delete(msg.arg1);
988                    boolean deleteOld = false;
989
990                    if (data != null) {
991                        InstallArgs args = data.args;
992                        PackageInstalledInfo res = data.res;
993
994                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
995                            res.removedInfo.sendBroadcast(false, true, false);
996                            Bundle extras = new Bundle(1);
997                            extras.putInt(Intent.EXTRA_UID, res.uid);
998                            // Determine the set of users who are adding this
999                            // package for the first time vs. those who are seeing
1000                            // an update.
1001                            int[] firstUsers;
1002                            int[] updateUsers = new int[0];
1003                            if (res.origUsers == null || res.origUsers.length == 0) {
1004                                firstUsers = res.newUsers;
1005                            } else {
1006                                firstUsers = new int[0];
1007                                for (int i=0; i<res.newUsers.length; i++) {
1008                                    int user = res.newUsers[i];
1009                                    boolean isNew = true;
1010                                    for (int j=0; j<res.origUsers.length; j++) {
1011                                        if (res.origUsers[j] == user) {
1012                                            isNew = false;
1013                                            break;
1014                                        }
1015                                    }
1016                                    if (isNew) {
1017                                        int[] newFirst = new int[firstUsers.length+1];
1018                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1019                                                firstUsers.length);
1020                                        newFirst[firstUsers.length] = user;
1021                                        firstUsers = newFirst;
1022                                    } else {
1023                                        int[] newUpdate = new int[updateUsers.length+1];
1024                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1025                                                updateUsers.length);
1026                                        newUpdate[updateUsers.length] = user;
1027                                        updateUsers = newUpdate;
1028                                    }
1029                                }
1030                            }
1031                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1032                                    res.pkg.applicationInfo.packageName,
1033                                    extras, null, null, firstUsers);
1034                            final boolean update = res.removedInfo.removedPackage != null;
1035                            if (update) {
1036                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1037                            }
1038                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1039                                    res.pkg.applicationInfo.packageName,
1040                                    extras, null, null, updateUsers);
1041                            if (update) {
1042                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1043                                        res.pkg.applicationInfo.packageName,
1044                                        extras, null, null, updateUsers);
1045                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1046                                        null, null,
1047                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1048
1049                                // treat asec-hosted packages like removable media on upgrade
1050                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1051                                    if (DEBUG_INSTALL) {
1052                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1053                                                + " is ASEC-hosted -> AVAILABLE");
1054                                    }
1055                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1056                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1057                                    pkgList.add(res.pkg.applicationInfo.packageName);
1058                                    sendResourcesChangedBroadcast(true, true,
1059                                            pkgList,uidArray, null);
1060                                }
1061                            }
1062                            if (res.removedInfo.args != null) {
1063                                // Remove the replaced package's older resources safely now
1064                                deleteOld = true;
1065                            }
1066
1067                            // Log current value of "unknown sources" setting
1068                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1069                                getUnknownSourcesSettings());
1070                        }
1071                        // Force a gc to clear up things
1072                        Runtime.getRuntime().gc();
1073                        // We delete after a gc for applications  on sdcard.
1074                        if (deleteOld) {
1075                            synchronized (mInstallLock) {
1076                                res.removedInfo.args.doPostDeleteLI(true);
1077                            }
1078                        }
1079                        if (args.observer != null) {
1080                            try {
1081                                args.observer.packageInstalled(res.name, res.returnCode);
1082                            } catch (RemoteException e) {
1083                                Slog.i(TAG, "Observer no longer exists.");
1084                            }
1085                        }
1086                        if (args.observer2 != null) {
1087                            try {
1088                                Bundle extras = extrasForInstallResult(res);
1089                                args.observer2.packageInstalled(res.name, extras, res.returnCode);
1090                            } catch (RemoteException e) {
1091                                Slog.i(TAG, "Observer no longer exists.");
1092                            }
1093                        }
1094                    } else {
1095                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1096                    }
1097                } break;
1098                case UPDATED_MEDIA_STATUS: {
1099                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1100                    boolean reportStatus = msg.arg1 == 1;
1101                    boolean doGc = msg.arg2 == 1;
1102                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1103                    if (doGc) {
1104                        // Force a gc to clear up stale containers.
1105                        Runtime.getRuntime().gc();
1106                    }
1107                    if (msg.obj != null) {
1108                        @SuppressWarnings("unchecked")
1109                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1110                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1111                        // Unload containers
1112                        unloadAllContainers(args);
1113                    }
1114                    if (reportStatus) {
1115                        try {
1116                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1117                            PackageHelper.getMountService().finishMediaUpdate();
1118                        } catch (RemoteException e) {
1119                            Log.e(TAG, "MountService not running?");
1120                        }
1121                    }
1122                } break;
1123                case WRITE_SETTINGS: {
1124                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1125                    synchronized (mPackages) {
1126                        removeMessages(WRITE_SETTINGS);
1127                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1128                        mSettings.writeLPr();
1129                        mDirtyUsers.clear();
1130                    }
1131                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1132                } break;
1133                case WRITE_PACKAGE_RESTRICTIONS: {
1134                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1135                    synchronized (mPackages) {
1136                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1137                        for (int userId : mDirtyUsers) {
1138                            mSettings.writePackageRestrictionsLPr(userId);
1139                        }
1140                        mDirtyUsers.clear();
1141                    }
1142                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1143                } break;
1144                case CHECK_PENDING_VERIFICATION: {
1145                    final int verificationId = msg.arg1;
1146                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1147
1148                    if ((state != null) && !state.timeoutExtended()) {
1149                        final InstallArgs args = state.getInstallArgs();
1150                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
1151                        mPendingVerification.remove(verificationId);
1152
1153                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1154
1155                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1156                            Slog.i(TAG, "Continuing with installation of "
1157                                    + args.packageURI.toString());
1158                            state.setVerifierResponse(Binder.getCallingUid(),
1159                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1160                            broadcastPackageVerified(verificationId, args.packageURI,
1161                                    PackageManager.VERIFICATION_ALLOW,
1162                                    state.getInstallArgs().getUser());
1163                            try {
1164                                ret = args.copyApk(mContainerService, true);
1165                            } catch (RemoteException e) {
1166                                Slog.e(TAG, "Could not contact the ContainerService");
1167                            }
1168                        } else {
1169                            broadcastPackageVerified(verificationId, args.packageURI,
1170                                    PackageManager.VERIFICATION_REJECT,
1171                                    state.getInstallArgs().getUser());
1172                        }
1173
1174                        processPendingInstall(args, ret);
1175                        mHandler.sendEmptyMessage(MCS_UNBIND);
1176                    }
1177                    break;
1178                }
1179                case PACKAGE_VERIFIED: {
1180                    final int verificationId = msg.arg1;
1181
1182                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1183                    if (state == null) {
1184                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1185                        break;
1186                    }
1187
1188                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1189
1190                    state.setVerifierResponse(response.callerUid, response.code);
1191
1192                    if (state.isVerificationComplete()) {
1193                        mPendingVerification.remove(verificationId);
1194
1195                        final InstallArgs args = state.getInstallArgs();
1196
1197                        int ret;
1198                        if (state.isInstallAllowed()) {
1199                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1200                            broadcastPackageVerified(verificationId, args.packageURI,
1201                                    response.code, state.getInstallArgs().getUser());
1202                            try {
1203                                ret = args.copyApk(mContainerService, true);
1204                            } catch (RemoteException e) {
1205                                Slog.e(TAG, "Could not contact the ContainerService");
1206                            }
1207                        } else {
1208                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1209                        }
1210
1211                        processPendingInstall(args, ret);
1212
1213                        mHandler.sendEmptyMessage(MCS_UNBIND);
1214                    }
1215
1216                    break;
1217                }
1218            }
1219        }
1220    }
1221
1222    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1223        Bundle extras = null;
1224        switch (res.returnCode) {
1225            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1226                extras = new Bundle();
1227                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1228                        res.origPermission);
1229                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1230                        res.origPackage);
1231                break;
1232            }
1233        }
1234        return extras;
1235    }
1236
1237    void scheduleWriteSettingsLocked() {
1238        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1239            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1240        }
1241    }
1242
1243    void scheduleWritePackageRestrictionsLocked(int userId) {
1244        if (!sUserManager.exists(userId)) return;
1245        mDirtyUsers.add(userId);
1246        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1247            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1248        }
1249    }
1250
1251    public static final IPackageManager main(Context context, Installer installer,
1252            boolean factoryTest, boolean onlyCore) {
1253        PackageManagerService m = new PackageManagerService(context, installer,
1254                factoryTest, onlyCore);
1255        ServiceManager.addService("package", m);
1256        return m;
1257    }
1258
1259    static String[] splitString(String str, char sep) {
1260        int count = 1;
1261        int i = 0;
1262        while ((i=str.indexOf(sep, i)) >= 0) {
1263            count++;
1264            i++;
1265        }
1266
1267        String[] res = new String[count];
1268        i=0;
1269        count = 0;
1270        int lastI=0;
1271        while ((i=str.indexOf(sep, i)) >= 0) {
1272            res[count] = str.substring(lastI, i);
1273            count++;
1274            i++;
1275            lastI = i;
1276        }
1277        res[count] = str.substring(lastI, str.length());
1278        return res;
1279    }
1280
1281    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1282        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1283                Context.DISPLAY_SERVICE);
1284        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1285    }
1286
1287    public PackageManagerService(Context context, Installer installer,
1288            boolean factoryTest, boolean onlyCore) {
1289        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1290                SystemClock.uptimeMillis());
1291
1292        if (mSdkVersion <= 0) {
1293            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1294        }
1295
1296        mContext = context;
1297        mFactoryTest = factoryTest;
1298        mOnlyCore = onlyCore;
1299        mMetrics = new DisplayMetrics();
1300        mSettings = new Settings(context);
1301        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1302                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1303        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1304                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1305        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1306                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1307        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1308                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1309        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1310                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1311        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1312                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1313
1314        String separateProcesses = SystemProperties.get("debug.separate_processes");
1315        if (separateProcesses != null && separateProcesses.length() > 0) {
1316            if ("*".equals(separateProcesses)) {
1317                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1318                mSeparateProcesses = null;
1319                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1320            } else {
1321                mDefParseFlags = 0;
1322                mSeparateProcesses = separateProcesses.split(",");
1323                Slog.w(TAG, "Running with debug.separate_processes: "
1324                        + separateProcesses);
1325            }
1326        } else {
1327            mDefParseFlags = 0;
1328            mSeparateProcesses = null;
1329        }
1330
1331        mInstaller = installer;
1332
1333        getDefaultDisplayMetrics(context, mMetrics);
1334
1335        synchronized (mInstallLock) {
1336        // writer
1337        synchronized (mPackages) {
1338            mHandlerThread = new ServiceThread(TAG,
1339                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1340            mHandlerThread.start();
1341            mHandler = new PackageHandler(mHandlerThread.getLooper());
1342            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1343
1344            File dataDir = Environment.getDataDirectory();
1345            mAppDataDir = new File(dataDir, "data");
1346            mAppInstallDir = new File(dataDir, "app");
1347            mAppLibInstallDir = new File(dataDir, "app-lib");
1348            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1349            mUserAppDataDir = new File(dataDir, "user");
1350            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1351            mAppStagingDir = new File(dataDir, "app-staging");
1352
1353            sUserManager = new UserManagerService(context, this,
1354                    mInstallLock, mPackages);
1355
1356            // Read permissions and features from system
1357            readPermissions(Environment.buildPath(
1358                    Environment.getRootDirectory(), "etc", "permissions"), false);
1359            // Only read features from OEM
1360            readPermissions(Environment.buildPath(
1361                    Environment.getOemDirectory(), "etc", "permissions"), true);
1362
1363            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1364
1365            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1366                    mSdkVersion, mOnlyCore);
1367
1368            String customResolverActivity = Resources.getSystem().getString(
1369                    R.string.config_customResolverActivity);
1370            if (TextUtils.isEmpty(customResolverActivity)) {
1371                customResolverActivity = null;
1372            } else {
1373                mCustomResolverComponentName = ComponentName.unflattenFromString(
1374                        customResolverActivity);
1375            }
1376
1377            long startTime = SystemClock.uptimeMillis();
1378
1379            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1380                    startTime);
1381
1382            // Set flag to monitor and not change apk file paths when
1383            // scanning install directories.
1384            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1385
1386            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1387
1388            /**
1389             * Add everything in the in the boot class path to the
1390             * list of process files because dexopt will have been run
1391             * if necessary during zygote startup.
1392             */
1393            String bootClassPath = System.getProperty("java.boot.class.path");
1394            if (bootClassPath != null) {
1395                String[] paths = splitString(bootClassPath, ':');
1396                for (int i=0; i<paths.length; i++) {
1397                    alreadyDexOpted.add(paths[i]);
1398                }
1399            } else {
1400                Slog.w(TAG, "No BOOTCLASSPATH found!");
1401            }
1402
1403            boolean didDexOptLibraryOrTool = false;
1404
1405            final List<String> instructionSets = getAllInstructionSets();
1406
1407            /**
1408             * Ensure all external libraries have had dexopt run on them.
1409             */
1410            if (mSharedLibraries.size() > 0) {
1411                // NOTE: For now, we're compiling these system "shared libraries"
1412                // (and framework jars) into all available architectures. It's possible
1413                // to compile them only when we come across an app that uses them (there's
1414                // already logic for that in scanPackageLI) but that adds some complexity.
1415                for (String instructionSet : instructionSets) {
1416                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1417                        final String lib = libEntry.path;
1418                        if (lib == null) {
1419                            continue;
1420                        }
1421
1422                        try {
1423                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1424                                alreadyDexOpted.add(lib);
1425
1426                                // The list of "shared libraries" we have at this point is
1427                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1428                                didDexOptLibraryOrTool = true;
1429                            }
1430                        } catch (FileNotFoundException e) {
1431                            Slog.w(TAG, "Library not found: " + lib);
1432                        } catch (IOException e) {
1433                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1434                                    + e.getMessage());
1435                        }
1436                    }
1437                }
1438            }
1439
1440            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1441
1442            // Gross hack for now: we know this file doesn't contain any
1443            // code, so don't dexopt it to avoid the resulting log spew.
1444            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1445
1446            // Gross hack for now: we know this file is only part of
1447            // the boot class path for art, so don't dexopt it to
1448            // avoid the resulting log spew.
1449            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1450
1451            /**
1452             * And there are a number of commands implemented in Java, which
1453             * we currently need to do the dexopt on so that they can be
1454             * run from a non-root shell.
1455             */
1456            String[] frameworkFiles = frameworkDir.list();
1457            if (frameworkFiles != null) {
1458                // TODO: We could compile these only for the most preferred ABI. We should
1459                // first double check that the dex files for these commands are not referenced
1460                // by other system apps.
1461                for (String instructionSet : instructionSets) {
1462                    for (int i=0; i<frameworkFiles.length; i++) {
1463                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1464                        String path = libPath.getPath();
1465                        // Skip the file if we already did it.
1466                        if (alreadyDexOpted.contains(path)) {
1467                            continue;
1468                        }
1469                        // Skip the file if it is not a type we want to dexopt.
1470                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1471                            continue;
1472                        }
1473                        try {
1474                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1475                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1476                                didDexOptLibraryOrTool = true;
1477                            }
1478                        } catch (FileNotFoundException e) {
1479                            Slog.w(TAG, "Jar not found: " + path);
1480                        } catch (IOException e) {
1481                            Slog.w(TAG, "Exception reading jar: " + path, e);
1482                        }
1483                    }
1484                }
1485            }
1486
1487            if (didDexOptLibraryOrTool) {
1488                pruneDexFiles(new File(dataDir, "dalvik-cache"));
1489            }
1490
1491            // Collect vendor overlay packages.
1492            // (Do this before scanning any apps.)
1493            // For security and version matching reason, only consider
1494            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1495            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1496            mVendorOverlayInstallObserver = new AppDirObserver(
1497                vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1498            mVendorOverlayInstallObserver.startWatching();
1499            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1500                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1501
1502            // Find base frameworks (resource packages without code).
1503            mFrameworkInstallObserver = new AppDirObserver(
1504                frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1505            mFrameworkInstallObserver.startWatching();
1506            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1507                    | PackageParser.PARSE_IS_SYSTEM_DIR
1508                    | PackageParser.PARSE_IS_PRIVILEGED,
1509                    scanMode | SCAN_NO_DEX, 0);
1510
1511            // Collected privileged system packages.
1512            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1513            mPrivilegedInstallObserver = new AppDirObserver(
1514                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1515            mPrivilegedInstallObserver.startWatching();
1516                scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1517                        | PackageParser.PARSE_IS_SYSTEM_DIR
1518                        | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1519
1520            // Collect ordinary system packages.
1521            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1522            mSystemInstallObserver = new AppDirObserver(
1523                systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1524            mSystemInstallObserver.startWatching();
1525            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1526                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1527
1528            // Collect all vendor packages.
1529            File vendorAppDir = new File("/vendor/app");
1530            try {
1531                vendorAppDir = vendorAppDir.getCanonicalFile();
1532            } catch (IOException e) {
1533                // failed to look up canonical path, continue with original one
1534            }
1535            mVendorInstallObserver = new AppDirObserver(
1536                vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1537            mVendorInstallObserver.startWatching();
1538            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1539                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1540
1541            // Collect all OEM packages.
1542            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1543            mOemInstallObserver = new AppDirObserver(
1544                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1545            mOemInstallObserver.startWatching();
1546            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1547                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1548
1549            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1550            mInstaller.moveFiles();
1551
1552            // Prune any system packages that no longer exist.
1553            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1554            if (!mOnlyCore) {
1555                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1556                while (psit.hasNext()) {
1557                    PackageSetting ps = psit.next();
1558
1559                    /*
1560                     * If this is not a system app, it can't be a
1561                     * disable system app.
1562                     */
1563                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1564                        continue;
1565                    }
1566
1567                    /*
1568                     * If the package is scanned, it's not erased.
1569                     */
1570                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1571                    if (scannedPkg != null) {
1572                        /*
1573                         * If the system app is both scanned and in the
1574                         * disabled packages list, then it must have been
1575                         * added via OTA. Remove it from the currently
1576                         * scanned package so the previously user-installed
1577                         * application can be scanned.
1578                         */
1579                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1580                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1581                                    + "; removing system app");
1582                            removePackageLI(ps, true);
1583                        }
1584
1585                        continue;
1586                    }
1587
1588                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1589                        psit.remove();
1590                        String msg = "System package " + ps.name
1591                                + " no longer exists; wiping its data";
1592                        reportSettingsProblem(Log.WARN, msg);
1593                        removeDataDirsLI(ps.name);
1594                    } else {
1595                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1596                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1597                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1598                        }
1599                    }
1600                }
1601            }
1602
1603            //look for any incomplete package installations
1604            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1605            //clean up list
1606            for(int i = 0; i < deletePkgsList.size(); i++) {
1607                //clean up here
1608                cleanupInstallFailedPackage(deletePkgsList.get(i));
1609            }
1610            //delete tmp files
1611            deleteTempPackageFiles();
1612
1613            // Remove any shared userIDs that have no associated packages
1614            mSettings.pruneSharedUsersLPw();
1615
1616            if (!mOnlyCore) {
1617                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1618                        SystemClock.uptimeMillis());
1619                mAppInstallObserver = new AppDirObserver(
1620                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1621                mAppInstallObserver.startWatching();
1622                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1623
1624                mDrmAppInstallObserver = new AppDirObserver(
1625                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1626                mDrmAppInstallObserver.startWatching();
1627                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1628                        scanMode, 0);
1629
1630                /**
1631                 * Remove disable package settings for any updated system
1632                 * apps that were removed via an OTA. If they're not a
1633                 * previously-updated app, remove them completely.
1634                 * Otherwise, just revoke their system-level permissions.
1635                 */
1636                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1637                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1638                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1639
1640                    String msg;
1641                    if (deletedPkg == null) {
1642                        msg = "Updated system package " + deletedAppName
1643                                + " no longer exists; wiping its data";
1644                        removeDataDirsLI(deletedAppName);
1645                    } else {
1646                        msg = "Updated system app + " + deletedAppName
1647                                + " no longer present; removing system privileges for "
1648                                + deletedAppName;
1649
1650                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1651
1652                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1653                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1654                    }
1655                    reportSettingsProblem(Log.WARN, msg);
1656                }
1657            } else {
1658                mAppInstallObserver = null;
1659                mDrmAppInstallObserver = null;
1660            }
1661
1662            // Now that we know all of the shared libraries, update all clients to have
1663            // the correct library paths.
1664            updateAllSharedLibrariesLPw();
1665
1666            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1667                // NOTE: We ignore potential failures here during a system scan (like
1668                // the rest of the commands above) because there's precious little we
1669                // can do about it. A settings error is reported, though.
1670                adjustCpuAbisForSharedUserLPw(setting.packages, null,
1671                        false /* force dexopt */, false /* defer dexopt */);
1672            }
1673
1674            // Now that we know all the packages we are keeping,
1675            // read and update their last usage times.
1676            mPackageUsage.readLP();
1677
1678            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1679                    SystemClock.uptimeMillis());
1680            Slog.i(TAG, "Time to scan packages: "
1681                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1682                    + " seconds");
1683
1684            // If the platform SDK has changed since the last time we booted,
1685            // we need to re-grant app permission to catch any new ones that
1686            // appear.  This is really a hack, and means that apps can in some
1687            // cases get permissions that the user didn't initially explicitly
1688            // allow...  it would be nice to have some better way to handle
1689            // this situation.
1690            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1691                    != mSdkVersion;
1692            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1693                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1694                    + "; regranting permissions for internal storage");
1695            mSettings.mInternalSdkPlatform = mSdkVersion;
1696
1697            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1698                    | (regrantPermissions
1699                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1700                            : 0));
1701
1702            // If this is the first boot, and it is a normal boot, then
1703            // we need to initialize the default preferred apps.
1704            if (!mRestoredSettings && !onlyCore) {
1705                mSettings.readDefaultPreferredAppsLPw(this, 0);
1706            }
1707
1708            // All the changes are done during package scanning.
1709            mSettings.updateInternalDatabaseVersion();
1710
1711            // can downgrade to reader
1712            mSettings.writeLPr();
1713
1714            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1715                    SystemClock.uptimeMillis());
1716
1717
1718            mRequiredVerifierPackage = getRequiredVerifierLPr();
1719        } // synchronized (mPackages)
1720        } // synchronized (mInstallLock)
1721
1722        mInstallerService = new PackageInstallerService(context, this, mAppStagingDir);
1723
1724        // Now after opening every single application zip, make sure they
1725        // are all flushed.  Not really needed, but keeps things nice and
1726        // tidy.
1727        Runtime.getRuntime().gc();
1728    }
1729
1730    private static void pruneDexFiles(File cacheDir) {
1731        // If we had to do a dexopt of one of the previous
1732        // things, then something on the system has changed.
1733        // Consider this significant, and wipe away all other
1734        // existing dexopt files to ensure we don't leave any
1735        // dangling around.
1736        //
1737        // Additionally, delete all dex files from the root directory
1738        // since there shouldn't be any there anyway.
1739        //
1740        // Note: This isn't as good an indicator as it used to be. It
1741        // used to include the boot classpath but at some point
1742        // DexFile.isDexOptNeeded started returning false for the boot
1743        // class path files in all cases. It is very possible in a
1744        // small maintenance release update that the library and tool
1745        // jars may be unchanged but APK could be removed resulting in
1746        // unused dalvik-cache files.
1747        File[] files = cacheDir.listFiles();
1748        if (files != null) {
1749            for (File file : files) {
1750                if (!file.isDirectory()) {
1751                    Slog.i(TAG, "Pruning dalvik file: " + file.getAbsolutePath());
1752                    file.delete();
1753                } else {
1754                    File[] subDirList = file.listFiles();
1755                    if (subDirList != null) {
1756                        for (File subDirFile : subDirList) {
1757                            final String fn = subDirFile.getName();
1758                            if (fn.startsWith("data@app@") || fn.startsWith("data@app-private@")) {
1759                                Slog.i(TAG, "Pruning dalvik file: " + fn);
1760                                subDirFile.delete();
1761                            }
1762                        }
1763                    }
1764                }
1765            }
1766        }
1767    }
1768
1769    @Override
1770    public boolean isFirstBoot() {
1771        return !mRestoredSettings || mPackageUsage.isFirstBoot();
1772    }
1773
1774    @Override
1775    public boolean isOnlyCoreApps() {
1776        return mOnlyCore;
1777    }
1778
1779    private String getRequiredVerifierLPr() {
1780        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1781        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1782                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1783
1784        String requiredVerifier = null;
1785
1786        final int N = receivers.size();
1787        for (int i = 0; i < N; i++) {
1788            final ResolveInfo info = receivers.get(i);
1789
1790            if (info.activityInfo == null) {
1791                continue;
1792            }
1793
1794            final String packageName = info.activityInfo.packageName;
1795
1796            final PackageSetting ps = mSettings.mPackages.get(packageName);
1797            if (ps == null) {
1798                continue;
1799            }
1800
1801            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1802            if (!gp.grantedPermissions
1803                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1804                continue;
1805            }
1806
1807            if (requiredVerifier != null) {
1808                throw new RuntimeException("There can be only one required verifier");
1809            }
1810
1811            requiredVerifier = packageName;
1812        }
1813
1814        return requiredVerifier;
1815    }
1816
1817    @Override
1818    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1819            throws RemoteException {
1820        try {
1821            return super.onTransact(code, data, reply, flags);
1822        } catch (RuntimeException e) {
1823            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1824                Slog.wtf(TAG, "Package Manager Crash", e);
1825            }
1826            throw e;
1827        }
1828    }
1829
1830    void cleanupInstallFailedPackage(PackageSetting ps) {
1831        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1832        removeDataDirsLI(ps.name);
1833        if (ps.codePath != null) {
1834            if (!ps.codePath.delete()) {
1835                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1836            }
1837        }
1838        if (ps.resourcePath != null) {
1839            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1840                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1841            }
1842        }
1843        mSettings.removePackageLPw(ps.name);
1844    }
1845
1846    void readPermissions(File libraryDir, boolean onlyFeatures) {
1847        // Read permissions from .../etc/permission directory.
1848        if (!libraryDir.exists() || !libraryDir.isDirectory()) {
1849            Slog.w(TAG, "No directory " + libraryDir + ", skipping");
1850            return;
1851        }
1852        if (!libraryDir.canRead()) {
1853            Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
1854            return;
1855        }
1856
1857        // Iterate over the files in the directory and scan .xml files
1858        for (File f : libraryDir.listFiles()) {
1859            // We'll read platform.xml last
1860            if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1861                continue;
1862            }
1863
1864            if (!f.getPath().endsWith(".xml")) {
1865                Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
1866                continue;
1867            }
1868            if (!f.canRead()) {
1869                Slog.w(TAG, "Permissions library file " + f + " cannot be read");
1870                continue;
1871            }
1872
1873            readPermissionsFromXml(f, onlyFeatures);
1874        }
1875
1876        // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1877        final File permFile = new File(Environment.getRootDirectory(),
1878                "etc/permissions/platform.xml");
1879        readPermissionsFromXml(permFile, onlyFeatures);
1880    }
1881
1882    private void readPermissionsFromXml(File permFile, boolean onlyFeatures) {
1883        FileReader permReader = null;
1884        try {
1885            permReader = new FileReader(permFile);
1886        } catch (FileNotFoundException e) {
1887            Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
1888            return;
1889        }
1890
1891        try {
1892            XmlPullParser parser = Xml.newPullParser();
1893            parser.setInput(permReader);
1894
1895            XmlUtils.beginDocument(parser, "permissions");
1896
1897            while (true) {
1898                XmlUtils.nextElement(parser);
1899                if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1900                    break;
1901                }
1902
1903                String name = parser.getName();
1904                if ("group".equals(name) && !onlyFeatures) {
1905                    String gidStr = parser.getAttributeValue(null, "gid");
1906                    if (gidStr != null) {
1907                        int gid = Process.getGidForName(gidStr);
1908                        mGlobalGids = appendInt(mGlobalGids, gid);
1909                    } else {
1910                        Slog.w(TAG, "<group> without gid at "
1911                                + parser.getPositionDescription());
1912                    }
1913
1914                    XmlUtils.skipCurrentTag(parser);
1915                    continue;
1916                } else if ("permission".equals(name) && !onlyFeatures) {
1917                    String perm = parser.getAttributeValue(null, "name");
1918                    if (perm == null) {
1919                        Slog.w(TAG, "<permission> without name at "
1920                                + parser.getPositionDescription());
1921                        XmlUtils.skipCurrentTag(parser);
1922                        continue;
1923                    }
1924                    perm = perm.intern();
1925                    readPermission(parser, perm);
1926
1927                } else if ("assign-permission".equals(name) && !onlyFeatures) {
1928                    String perm = parser.getAttributeValue(null, "name");
1929                    if (perm == null) {
1930                        Slog.w(TAG, "<assign-permission> without name at "
1931                                + parser.getPositionDescription());
1932                        XmlUtils.skipCurrentTag(parser);
1933                        continue;
1934                    }
1935                    String uidStr = parser.getAttributeValue(null, "uid");
1936                    if (uidStr == null) {
1937                        Slog.w(TAG, "<assign-permission> without uid at "
1938                                + parser.getPositionDescription());
1939                        XmlUtils.skipCurrentTag(parser);
1940                        continue;
1941                    }
1942                    int uid = Process.getUidForName(uidStr);
1943                    if (uid < 0) {
1944                        Slog.w(TAG, "<assign-permission> with unknown uid \""
1945                                + uidStr + "\" at "
1946                                + parser.getPositionDescription());
1947                        XmlUtils.skipCurrentTag(parser);
1948                        continue;
1949                    }
1950                    perm = perm.intern();
1951                    HashSet<String> perms = mSystemPermissions.get(uid);
1952                    if (perms == null) {
1953                        perms = new HashSet<String>();
1954                        mSystemPermissions.put(uid, perms);
1955                    }
1956                    perms.add(perm);
1957                    XmlUtils.skipCurrentTag(parser);
1958
1959                } else if ("library".equals(name) && !onlyFeatures) {
1960                    String lname = parser.getAttributeValue(null, "name");
1961                    String lfile = parser.getAttributeValue(null, "file");
1962                    if (lname == null) {
1963                        Slog.w(TAG, "<library> without name at "
1964                                + parser.getPositionDescription());
1965                    } else if (lfile == null) {
1966                        Slog.w(TAG, "<library> without file at "
1967                                + parser.getPositionDescription());
1968                    } else {
1969                        //Log.i(TAG, "Got library " + lname + " in " + lfile);
1970                        mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null));
1971                    }
1972                    XmlUtils.skipCurrentTag(parser);
1973                    continue;
1974
1975                } else if ("feature".equals(name)) {
1976                    String fname = parser.getAttributeValue(null, "name");
1977                    if (fname == null) {
1978                        Slog.w(TAG, "<feature> without name at "
1979                                + parser.getPositionDescription());
1980                    } else {
1981                        //Log.i(TAG, "Got feature " + fname);
1982                        FeatureInfo fi = new FeatureInfo();
1983                        fi.name = fname;
1984                        mAvailableFeatures.put(fname, fi);
1985                    }
1986                    XmlUtils.skipCurrentTag(parser);
1987                    continue;
1988
1989                } else {
1990                    XmlUtils.skipCurrentTag(parser);
1991                    continue;
1992                }
1993
1994            }
1995            permReader.close();
1996        } catch (XmlPullParserException e) {
1997            Slog.w(TAG, "Got execption parsing permissions.", e);
1998        } catch (IOException e) {
1999            Slog.w(TAG, "Got execption parsing permissions.", e);
2000        }
2001    }
2002
2003    void readPermission(XmlPullParser parser, String name)
2004            throws IOException, XmlPullParserException {
2005
2006        name = name.intern();
2007
2008        BasePermission bp = mSettings.mPermissions.get(name);
2009        if (bp == null) {
2010            bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
2011            mSettings.mPermissions.put(name, bp);
2012        }
2013        int outerDepth = parser.getDepth();
2014        int type;
2015        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
2016               && (type != XmlPullParser.END_TAG
2017                       || parser.getDepth() > outerDepth)) {
2018            if (type == XmlPullParser.END_TAG
2019                    || type == XmlPullParser.TEXT) {
2020                continue;
2021            }
2022
2023            String tagName = parser.getName();
2024            if ("group".equals(tagName)) {
2025                String gidStr = parser.getAttributeValue(null, "gid");
2026                if (gidStr != null) {
2027                    int gid = Process.getGidForName(gidStr);
2028                    bp.gids = appendInt(bp.gids, gid);
2029                } else {
2030                    Slog.w(TAG, "<group> without gid at "
2031                            + parser.getPositionDescription());
2032                }
2033            }
2034            XmlUtils.skipCurrentTag(parser);
2035        }
2036    }
2037
2038    static int[] appendInts(int[] cur, int[] add) {
2039        if (add == null) return cur;
2040        if (cur == null) return add;
2041        final int N = add.length;
2042        for (int i=0; i<N; i++) {
2043            cur = appendInt(cur, add[i]);
2044        }
2045        return cur;
2046    }
2047
2048    static int[] removeInts(int[] cur, int[] rem) {
2049        if (rem == null) return cur;
2050        if (cur == null) return cur;
2051        final int N = rem.length;
2052        for (int i=0; i<N; i++) {
2053            cur = removeInt(cur, rem[i]);
2054        }
2055        return cur;
2056    }
2057
2058    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2059        if (!sUserManager.exists(userId)) return null;
2060        final PackageSetting ps = (PackageSetting) p.mExtras;
2061        if (ps == null) {
2062            return null;
2063        }
2064        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2065        final PackageUserState state = ps.readUserState(userId);
2066        return PackageParser.generatePackageInfo(p, gp.gids, flags,
2067                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
2068                state, userId);
2069    }
2070
2071    @Override
2072    public boolean isPackageAvailable(String packageName, int userId) {
2073        if (!sUserManager.exists(userId)) return false;
2074        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
2075        synchronized (mPackages) {
2076            PackageParser.Package p = mPackages.get(packageName);
2077            if (p != null) {
2078                final PackageSetting ps = (PackageSetting) p.mExtras;
2079                if (ps != null) {
2080                    final PackageUserState state = ps.readUserState(userId);
2081                    if (state != null) {
2082                        return PackageParser.isAvailable(state);
2083                    }
2084                }
2085            }
2086        }
2087        return false;
2088    }
2089
2090    @Override
2091    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2092        if (!sUserManager.exists(userId)) return null;
2093        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
2094        // reader
2095        synchronized (mPackages) {
2096            PackageParser.Package p = mPackages.get(packageName);
2097            if (DEBUG_PACKAGE_INFO)
2098                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2099            if (p != null) {
2100                return generatePackageInfo(p, flags, userId);
2101            }
2102            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2103                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2104            }
2105        }
2106        return null;
2107    }
2108
2109    @Override
2110    public String[] currentToCanonicalPackageNames(String[] names) {
2111        String[] out = new String[names.length];
2112        // reader
2113        synchronized (mPackages) {
2114            for (int i=names.length-1; i>=0; i--) {
2115                PackageSetting ps = mSettings.mPackages.get(names[i]);
2116                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2117            }
2118        }
2119        return out;
2120    }
2121
2122    @Override
2123    public String[] canonicalToCurrentPackageNames(String[] names) {
2124        String[] out = new String[names.length];
2125        // reader
2126        synchronized (mPackages) {
2127            for (int i=names.length-1; i>=0; i--) {
2128                String cur = mSettings.mRenamedPackages.get(names[i]);
2129                out[i] = cur != null ? cur : names[i];
2130            }
2131        }
2132        return out;
2133    }
2134
2135    @Override
2136    public int getPackageUid(String packageName, int userId) {
2137        if (!sUserManager.exists(userId)) return -1;
2138        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
2139        // reader
2140        synchronized (mPackages) {
2141            PackageParser.Package p = mPackages.get(packageName);
2142            if(p != null) {
2143                return UserHandle.getUid(userId, p.applicationInfo.uid);
2144            }
2145            PackageSetting ps = mSettings.mPackages.get(packageName);
2146            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2147                return -1;
2148            }
2149            p = ps.pkg;
2150            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2151        }
2152    }
2153
2154    @Override
2155    public int[] getPackageGids(String packageName) {
2156        // reader
2157        synchronized (mPackages) {
2158            PackageParser.Package p = mPackages.get(packageName);
2159            if (DEBUG_PACKAGE_INFO)
2160                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2161            if (p != null) {
2162                final PackageSetting ps = (PackageSetting)p.mExtras;
2163                return ps.getGids();
2164            }
2165        }
2166        // stupid thing to indicate an error.
2167        return new int[0];
2168    }
2169
2170    static final PermissionInfo generatePermissionInfo(
2171            BasePermission bp, int flags) {
2172        if (bp.perm != null) {
2173            return PackageParser.generatePermissionInfo(bp.perm, flags);
2174        }
2175        PermissionInfo pi = new PermissionInfo();
2176        pi.name = bp.name;
2177        pi.packageName = bp.sourcePackage;
2178        pi.nonLocalizedLabel = bp.name;
2179        pi.protectionLevel = bp.protectionLevel;
2180        return pi;
2181    }
2182
2183    @Override
2184    public PermissionInfo getPermissionInfo(String name, int flags) {
2185        // reader
2186        synchronized (mPackages) {
2187            final BasePermission p = mSettings.mPermissions.get(name);
2188            if (p != null) {
2189                return generatePermissionInfo(p, flags);
2190            }
2191            return null;
2192        }
2193    }
2194
2195    @Override
2196    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2197        // reader
2198        synchronized (mPackages) {
2199            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2200            for (BasePermission p : mSettings.mPermissions.values()) {
2201                if (group == null) {
2202                    if (p.perm == null || p.perm.info.group == null) {
2203                        out.add(generatePermissionInfo(p, flags));
2204                    }
2205                } else {
2206                    if (p.perm != null && group.equals(p.perm.info.group)) {
2207                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2208                    }
2209                }
2210            }
2211
2212            if (out.size() > 0) {
2213                return out;
2214            }
2215            return mPermissionGroups.containsKey(group) ? out : null;
2216        }
2217    }
2218
2219    @Override
2220    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2221        // reader
2222        synchronized (mPackages) {
2223            return PackageParser.generatePermissionGroupInfo(
2224                    mPermissionGroups.get(name), flags);
2225        }
2226    }
2227
2228    @Override
2229    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2230        // reader
2231        synchronized (mPackages) {
2232            final int N = mPermissionGroups.size();
2233            ArrayList<PermissionGroupInfo> out
2234                    = new ArrayList<PermissionGroupInfo>(N);
2235            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2236                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2237            }
2238            return out;
2239        }
2240    }
2241
2242    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2243            int userId) {
2244        if (!sUserManager.exists(userId)) return null;
2245        PackageSetting ps = mSettings.mPackages.get(packageName);
2246        if (ps != null) {
2247            if (ps.pkg == null) {
2248                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2249                        flags, userId);
2250                if (pInfo != null) {
2251                    return pInfo.applicationInfo;
2252                }
2253                return null;
2254            }
2255            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2256                    ps.readUserState(userId), userId);
2257        }
2258        return null;
2259    }
2260
2261    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2262            int userId) {
2263        if (!sUserManager.exists(userId)) return null;
2264        PackageSetting ps = mSettings.mPackages.get(packageName);
2265        if (ps != null) {
2266            PackageParser.Package pkg = ps.pkg;
2267            if (pkg == null) {
2268                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2269                    return null;
2270                }
2271                // TODO: teach about reading split name
2272                pkg = new PackageParser.Package(packageName, null);
2273                pkg.applicationInfo.packageName = packageName;
2274                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2275                pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
2276                pkg.applicationInfo.sourceDir = ps.codePathString;
2277                pkg.applicationInfo.dataDir =
2278                        getDataPathForPackage(packageName, 0).getPath();
2279                pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
2280                pkg.applicationInfo.cpuAbi = ps.cpuAbiString;
2281            }
2282            return generatePackageInfo(pkg, flags, userId);
2283        }
2284        return null;
2285    }
2286
2287    @Override
2288    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2289        if (!sUserManager.exists(userId)) return null;
2290        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2291        // writer
2292        synchronized (mPackages) {
2293            PackageParser.Package p = mPackages.get(packageName);
2294            if (DEBUG_PACKAGE_INFO) Log.v(
2295                    TAG, "getApplicationInfo " + packageName
2296                    + ": " + p);
2297            if (p != null) {
2298                PackageSetting ps = mSettings.mPackages.get(packageName);
2299                if (ps == null) return null;
2300                // Note: isEnabledLP() does not apply here - always return info
2301                return PackageParser.generateApplicationInfo(
2302                        p, flags, ps.readUserState(userId), userId);
2303            }
2304            if ("android".equals(packageName)||"system".equals(packageName)) {
2305                return mAndroidApplication;
2306            }
2307            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2308                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2309            }
2310        }
2311        return null;
2312    }
2313
2314
2315    @Override
2316    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2317        mContext.enforceCallingOrSelfPermission(
2318                android.Manifest.permission.CLEAR_APP_CACHE, null);
2319        // Queue up an async operation since clearing cache may take a little while.
2320        mHandler.post(new Runnable() {
2321            public void run() {
2322                mHandler.removeCallbacks(this);
2323                int retCode = -1;
2324                synchronized (mInstallLock) {
2325                    retCode = mInstaller.freeCache(freeStorageSize);
2326                    if (retCode < 0) {
2327                        Slog.w(TAG, "Couldn't clear application caches");
2328                    }
2329                }
2330                if (observer != null) {
2331                    try {
2332                        observer.onRemoveCompleted(null, (retCode >= 0));
2333                    } catch (RemoteException e) {
2334                        Slog.w(TAG, "RemoveException when invoking call back");
2335                    }
2336                }
2337            }
2338        });
2339    }
2340
2341    @Override
2342    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2343        mContext.enforceCallingOrSelfPermission(
2344                android.Manifest.permission.CLEAR_APP_CACHE, null);
2345        // Queue up an async operation since clearing cache may take a little while.
2346        mHandler.post(new Runnable() {
2347            public void run() {
2348                mHandler.removeCallbacks(this);
2349                int retCode = -1;
2350                synchronized (mInstallLock) {
2351                    retCode = mInstaller.freeCache(freeStorageSize);
2352                    if (retCode < 0) {
2353                        Slog.w(TAG, "Couldn't clear application caches");
2354                    }
2355                }
2356                if(pi != null) {
2357                    try {
2358                        // Callback via pending intent
2359                        int code = (retCode >= 0) ? 1 : 0;
2360                        pi.sendIntent(null, code, null,
2361                                null, null);
2362                    } catch (SendIntentException e1) {
2363                        Slog.i(TAG, "Failed to send pending intent");
2364                    }
2365                }
2366            }
2367        });
2368    }
2369
2370    void freeStorage(long freeStorageSize) throws IOException {
2371        synchronized (mInstallLock) {
2372            if (mInstaller.freeCache(freeStorageSize) < 0) {
2373                throw new IOException("Failed to free enough space");
2374            }
2375        }
2376    }
2377
2378    @Override
2379    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2380        if (!sUserManager.exists(userId)) return null;
2381        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2382        synchronized (mPackages) {
2383            PackageParser.Activity a = mActivities.mActivities.get(component);
2384
2385            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2386            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2387                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2388                if (ps == null) return null;
2389                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2390                        userId);
2391            }
2392            if (mResolveComponentName.equals(component)) {
2393                return mResolveActivity;
2394            }
2395        }
2396        return null;
2397    }
2398
2399    @Override
2400    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2401            String resolvedType) {
2402        synchronized (mPackages) {
2403            PackageParser.Activity a = mActivities.mActivities.get(component);
2404            if (a == null) {
2405                return false;
2406            }
2407            for (int i=0; i<a.intents.size(); i++) {
2408                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2409                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2410                    return true;
2411                }
2412            }
2413            return false;
2414        }
2415    }
2416
2417    @Override
2418    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2419        if (!sUserManager.exists(userId)) return null;
2420        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2421        synchronized (mPackages) {
2422            PackageParser.Activity a = mReceivers.mActivities.get(component);
2423            if (DEBUG_PACKAGE_INFO) Log.v(
2424                TAG, "getReceiverInfo " + component + ": " + a);
2425            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2426                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2427                if (ps == null) return null;
2428                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2429                        userId);
2430            }
2431        }
2432        return null;
2433    }
2434
2435    @Override
2436    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2437        if (!sUserManager.exists(userId)) return null;
2438        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2439        synchronized (mPackages) {
2440            PackageParser.Service s = mServices.mServices.get(component);
2441            if (DEBUG_PACKAGE_INFO) Log.v(
2442                TAG, "getServiceInfo " + component + ": " + s);
2443            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2444                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2445                if (ps == null) return null;
2446                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2447                        userId);
2448            }
2449        }
2450        return null;
2451    }
2452
2453    @Override
2454    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2455        if (!sUserManager.exists(userId)) return null;
2456        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2457        synchronized (mPackages) {
2458            PackageParser.Provider p = mProviders.mProviders.get(component);
2459            if (DEBUG_PACKAGE_INFO) Log.v(
2460                TAG, "getProviderInfo " + component + ": " + p);
2461            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2462                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2463                if (ps == null) return null;
2464                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2465                        userId);
2466            }
2467        }
2468        return null;
2469    }
2470
2471    @Override
2472    public String[] getSystemSharedLibraryNames() {
2473        Set<String> libSet;
2474        synchronized (mPackages) {
2475            libSet = mSharedLibraries.keySet();
2476            int size = libSet.size();
2477            if (size > 0) {
2478                String[] libs = new String[size];
2479                libSet.toArray(libs);
2480                return libs;
2481            }
2482        }
2483        return null;
2484    }
2485
2486    @Override
2487    public FeatureInfo[] getSystemAvailableFeatures() {
2488        Collection<FeatureInfo> featSet;
2489        synchronized (mPackages) {
2490            featSet = mAvailableFeatures.values();
2491            int size = featSet.size();
2492            if (size > 0) {
2493                FeatureInfo[] features = new FeatureInfo[size+1];
2494                featSet.toArray(features);
2495                FeatureInfo fi = new FeatureInfo();
2496                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2497                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2498                features[size] = fi;
2499                return features;
2500            }
2501        }
2502        return null;
2503    }
2504
2505    @Override
2506    public boolean hasSystemFeature(String name) {
2507        synchronized (mPackages) {
2508            return mAvailableFeatures.containsKey(name);
2509        }
2510    }
2511
2512    private void checkValidCaller(int uid, int userId) {
2513        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2514            return;
2515
2516        throw new SecurityException("Caller uid=" + uid
2517                + " is not privileged to communicate with user=" + userId);
2518    }
2519
2520    @Override
2521    public int checkPermission(String permName, String pkgName) {
2522        synchronized (mPackages) {
2523            PackageParser.Package p = mPackages.get(pkgName);
2524            if (p != null && p.mExtras != null) {
2525                PackageSetting ps = (PackageSetting)p.mExtras;
2526                if (ps.sharedUser != null) {
2527                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2528                        return PackageManager.PERMISSION_GRANTED;
2529                    }
2530                } else if (ps.grantedPermissions.contains(permName)) {
2531                    return PackageManager.PERMISSION_GRANTED;
2532                }
2533            }
2534        }
2535        return PackageManager.PERMISSION_DENIED;
2536    }
2537
2538    @Override
2539    public int checkUidPermission(String permName, int uid) {
2540        synchronized (mPackages) {
2541            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2542            if (obj != null) {
2543                GrantedPermissions gp = (GrantedPermissions)obj;
2544                if (gp.grantedPermissions.contains(permName)) {
2545                    return PackageManager.PERMISSION_GRANTED;
2546                }
2547            } else {
2548                HashSet<String> perms = mSystemPermissions.get(uid);
2549                if (perms != null && perms.contains(permName)) {
2550                    return PackageManager.PERMISSION_GRANTED;
2551                }
2552            }
2553        }
2554        return PackageManager.PERMISSION_DENIED;
2555    }
2556
2557    /**
2558     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2559     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2560     * @param message the message to log on security exception
2561     */
2562    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2563            String message) {
2564        if (userId < 0) {
2565            throw new IllegalArgumentException("Invalid userId " + userId);
2566        }
2567        if (userId == UserHandle.getUserId(callingUid)) return;
2568        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2569            if (requireFullPermission) {
2570                mContext.enforceCallingOrSelfPermission(
2571                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2572            } else {
2573                try {
2574                    mContext.enforceCallingOrSelfPermission(
2575                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2576                } catch (SecurityException se) {
2577                    mContext.enforceCallingOrSelfPermission(
2578                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2579                }
2580            }
2581        }
2582    }
2583
2584    private BasePermission findPermissionTreeLP(String permName) {
2585        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2586            if (permName.startsWith(bp.name) &&
2587                    permName.length() > bp.name.length() &&
2588                    permName.charAt(bp.name.length()) == '.') {
2589                return bp;
2590            }
2591        }
2592        return null;
2593    }
2594
2595    private BasePermission checkPermissionTreeLP(String permName) {
2596        if (permName != null) {
2597            BasePermission bp = findPermissionTreeLP(permName);
2598            if (bp != null) {
2599                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2600                    return bp;
2601                }
2602                throw new SecurityException("Calling uid "
2603                        + Binder.getCallingUid()
2604                        + " is not allowed to add to permission tree "
2605                        + bp.name + " owned by uid " + bp.uid);
2606            }
2607        }
2608        throw new SecurityException("No permission tree found for " + permName);
2609    }
2610
2611    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2612        if (s1 == null) {
2613            return s2 == null;
2614        }
2615        if (s2 == null) {
2616            return false;
2617        }
2618        if (s1.getClass() != s2.getClass()) {
2619            return false;
2620        }
2621        return s1.equals(s2);
2622    }
2623
2624    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2625        if (pi1.icon != pi2.icon) return false;
2626        if (pi1.logo != pi2.logo) return false;
2627        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2628        if (!compareStrings(pi1.name, pi2.name)) return false;
2629        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2630        // We'll take care of setting this one.
2631        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2632        // These are not currently stored in settings.
2633        //if (!compareStrings(pi1.group, pi2.group)) return false;
2634        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2635        //if (pi1.labelRes != pi2.labelRes) return false;
2636        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2637        return true;
2638    }
2639
2640    int permissionInfoFootprint(PermissionInfo info) {
2641        int size = info.name.length();
2642        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2643        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2644        return size;
2645    }
2646
2647    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2648        int size = 0;
2649        for (BasePermission perm : mSettings.mPermissions.values()) {
2650            if (perm.uid == tree.uid) {
2651                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2652            }
2653        }
2654        return size;
2655    }
2656
2657    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2658        // We calculate the max size of permissions defined by this uid and throw
2659        // if that plus the size of 'info' would exceed our stated maximum.
2660        if (tree.uid != Process.SYSTEM_UID) {
2661            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2662            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2663                throw new SecurityException("Permission tree size cap exceeded");
2664            }
2665        }
2666    }
2667
2668    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2669        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2670            throw new SecurityException("Label must be specified in permission");
2671        }
2672        BasePermission tree = checkPermissionTreeLP(info.name);
2673        BasePermission bp = mSettings.mPermissions.get(info.name);
2674        boolean added = bp == null;
2675        boolean changed = true;
2676        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2677        if (added) {
2678            enforcePermissionCapLocked(info, tree);
2679            bp = new BasePermission(info.name, tree.sourcePackage,
2680                    BasePermission.TYPE_DYNAMIC);
2681        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2682            throw new SecurityException(
2683                    "Not allowed to modify non-dynamic permission "
2684                    + info.name);
2685        } else {
2686            if (bp.protectionLevel == fixedLevel
2687                    && bp.perm.owner.equals(tree.perm.owner)
2688                    && bp.uid == tree.uid
2689                    && comparePermissionInfos(bp.perm.info, info)) {
2690                changed = false;
2691            }
2692        }
2693        bp.protectionLevel = fixedLevel;
2694        info = new PermissionInfo(info);
2695        info.protectionLevel = fixedLevel;
2696        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2697        bp.perm.info.packageName = tree.perm.info.packageName;
2698        bp.uid = tree.uid;
2699        if (added) {
2700            mSettings.mPermissions.put(info.name, bp);
2701        }
2702        if (changed) {
2703            if (!async) {
2704                mSettings.writeLPr();
2705            } else {
2706                scheduleWriteSettingsLocked();
2707            }
2708        }
2709        return added;
2710    }
2711
2712    @Override
2713    public boolean addPermission(PermissionInfo info) {
2714        synchronized (mPackages) {
2715            return addPermissionLocked(info, false);
2716        }
2717    }
2718
2719    @Override
2720    public boolean addPermissionAsync(PermissionInfo info) {
2721        synchronized (mPackages) {
2722            return addPermissionLocked(info, true);
2723        }
2724    }
2725
2726    @Override
2727    public void removePermission(String name) {
2728        synchronized (mPackages) {
2729            checkPermissionTreeLP(name);
2730            BasePermission bp = mSettings.mPermissions.get(name);
2731            if (bp != null) {
2732                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2733                    throw new SecurityException(
2734                            "Not allowed to modify non-dynamic permission "
2735                            + name);
2736                }
2737                mSettings.mPermissions.remove(name);
2738                mSettings.writeLPr();
2739            }
2740        }
2741    }
2742
2743    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2744        int index = pkg.requestedPermissions.indexOf(bp.name);
2745        if (index == -1) {
2746            throw new SecurityException("Package " + pkg.packageName
2747                    + " has not requested permission " + bp.name);
2748        }
2749        boolean isNormal =
2750                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2751                        == PermissionInfo.PROTECTION_NORMAL);
2752        boolean isDangerous =
2753                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2754                        == PermissionInfo.PROTECTION_DANGEROUS);
2755        boolean isDevelopment =
2756                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2757
2758        if (!isNormal && !isDangerous && !isDevelopment) {
2759            throw new SecurityException("Permission " + bp.name
2760                    + " is not a changeable permission type");
2761        }
2762
2763        if (isNormal || isDangerous) {
2764            if (pkg.requestedPermissionsRequired.get(index)) {
2765                throw new SecurityException("Can't change " + bp.name
2766                        + ". It is required by the application");
2767            }
2768        }
2769    }
2770
2771    @Override
2772    public void grantPermission(String packageName, String permissionName) {
2773        mContext.enforceCallingOrSelfPermission(
2774                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2775        synchronized (mPackages) {
2776            final PackageParser.Package pkg = mPackages.get(packageName);
2777            if (pkg == null) {
2778                throw new IllegalArgumentException("Unknown package: " + packageName);
2779            }
2780            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2781            if (bp == null) {
2782                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2783            }
2784
2785            checkGrantRevokePermissions(pkg, bp);
2786
2787            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2788            if (ps == null) {
2789                return;
2790            }
2791            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2792            if (gp.grantedPermissions.add(permissionName)) {
2793                if (ps.haveGids) {
2794                    gp.gids = appendInts(gp.gids, bp.gids);
2795                }
2796                mSettings.writeLPr();
2797            }
2798        }
2799    }
2800
2801    @Override
2802    public void revokePermission(String packageName, String permissionName) {
2803        int changedAppId = -1;
2804
2805        synchronized (mPackages) {
2806            final PackageParser.Package pkg = mPackages.get(packageName);
2807            if (pkg == null) {
2808                throw new IllegalArgumentException("Unknown package: " + packageName);
2809            }
2810            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2811                mContext.enforceCallingOrSelfPermission(
2812                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2813            }
2814            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2815            if (bp == null) {
2816                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2817            }
2818
2819            checkGrantRevokePermissions(pkg, bp);
2820
2821            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2822            if (ps == null) {
2823                return;
2824            }
2825            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2826            if (gp.grantedPermissions.remove(permissionName)) {
2827                gp.grantedPermissions.remove(permissionName);
2828                if (ps.haveGids) {
2829                    gp.gids = removeInts(gp.gids, bp.gids);
2830                }
2831                mSettings.writeLPr();
2832                changedAppId = ps.appId;
2833            }
2834        }
2835
2836        if (changedAppId >= 0) {
2837            // We changed the perm on someone, kill its processes.
2838            IActivityManager am = ActivityManagerNative.getDefault();
2839            if (am != null) {
2840                final int callingUserId = UserHandle.getCallingUserId();
2841                final long ident = Binder.clearCallingIdentity();
2842                try {
2843                    //XXX we should only revoke for the calling user's app permissions,
2844                    // but for now we impact all users.
2845                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2846                    //        "revoke " + permissionName);
2847                    int[] users = sUserManager.getUserIds();
2848                    for (int user : users) {
2849                        am.killUid(UserHandle.getUid(user, changedAppId),
2850                                "revoke " + permissionName);
2851                    }
2852                } catch (RemoteException e) {
2853                } finally {
2854                    Binder.restoreCallingIdentity(ident);
2855                }
2856            }
2857        }
2858    }
2859
2860    @Override
2861    public boolean isProtectedBroadcast(String actionName) {
2862        synchronized (mPackages) {
2863            return mProtectedBroadcasts.contains(actionName);
2864        }
2865    }
2866
2867    @Override
2868    public int checkSignatures(String pkg1, String pkg2) {
2869        synchronized (mPackages) {
2870            final PackageParser.Package p1 = mPackages.get(pkg1);
2871            final PackageParser.Package p2 = mPackages.get(pkg2);
2872            if (p1 == null || p1.mExtras == null
2873                    || p2 == null || p2.mExtras == null) {
2874                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2875            }
2876            return compareSignatures(p1.mSignatures, p2.mSignatures);
2877        }
2878    }
2879
2880    @Override
2881    public int checkUidSignatures(int uid1, int uid2) {
2882        // Map to base uids.
2883        uid1 = UserHandle.getAppId(uid1);
2884        uid2 = UserHandle.getAppId(uid2);
2885        // reader
2886        synchronized (mPackages) {
2887            Signature[] s1;
2888            Signature[] s2;
2889            Object obj = mSettings.getUserIdLPr(uid1);
2890            if (obj != null) {
2891                if (obj instanceof SharedUserSetting) {
2892                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2893                } else if (obj instanceof PackageSetting) {
2894                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2895                } else {
2896                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2897                }
2898            } else {
2899                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2900            }
2901            obj = mSettings.getUserIdLPr(uid2);
2902            if (obj != null) {
2903                if (obj instanceof SharedUserSetting) {
2904                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2905                } else if (obj instanceof PackageSetting) {
2906                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2907                } else {
2908                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2909                }
2910            } else {
2911                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2912            }
2913            return compareSignatures(s1, s2);
2914        }
2915    }
2916
2917    /**
2918     * Compares two sets of signatures. Returns:
2919     * <br />
2920     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2921     * <br />
2922     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2923     * <br />
2924     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2925     * <br />
2926     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2927     * <br />
2928     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2929     */
2930    static int compareSignatures(Signature[] s1, Signature[] s2) {
2931        if (s1 == null) {
2932            return s2 == null
2933                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2934                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2935        }
2936
2937        if (s2 == null) {
2938            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2939        }
2940
2941        if (s1.length != s2.length) {
2942            return PackageManager.SIGNATURE_NO_MATCH;
2943        }
2944
2945        // Since both signature sets are of size 1, we can compare without HashSets.
2946        if (s1.length == 1) {
2947            return s1[0].equals(s2[0]) ?
2948                    PackageManager.SIGNATURE_MATCH :
2949                    PackageManager.SIGNATURE_NO_MATCH;
2950        }
2951
2952        HashSet<Signature> set1 = new HashSet<Signature>();
2953        for (Signature sig : s1) {
2954            set1.add(sig);
2955        }
2956        HashSet<Signature> set2 = new HashSet<Signature>();
2957        for (Signature sig : s2) {
2958            set2.add(sig);
2959        }
2960        // Make sure s2 contains all signatures in s1.
2961        if (set1.equals(set2)) {
2962            return PackageManager.SIGNATURE_MATCH;
2963        }
2964        return PackageManager.SIGNATURE_NO_MATCH;
2965    }
2966
2967    /**
2968     * If the database version for this type of package (internal storage or
2969     * external storage) is less than the version where package signatures
2970     * were updated, return true.
2971     */
2972    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2973        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2974                DatabaseVersion.SIGNATURE_END_ENTITY))
2975                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2976                        DatabaseVersion.SIGNATURE_END_ENTITY));
2977    }
2978
2979    /**
2980     * Used for backward compatibility to make sure any packages with
2981     * certificate chains get upgraded to the new style. {@code existingSigs}
2982     * will be in the old format (since they were stored on disk from before the
2983     * system upgrade) and {@code scannedSigs} will be in the newer format.
2984     */
2985    private int compareSignaturesCompat(PackageSignatures existingSigs,
2986            PackageParser.Package scannedPkg) {
2987        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2988            return PackageManager.SIGNATURE_NO_MATCH;
2989        }
2990
2991        HashSet<Signature> existingSet = new HashSet<Signature>();
2992        for (Signature sig : existingSigs.mSignatures) {
2993            existingSet.add(sig);
2994        }
2995        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2996        for (Signature sig : scannedPkg.mSignatures) {
2997            try {
2998                Signature[] chainSignatures = sig.getChainSignatures();
2999                for (Signature chainSig : chainSignatures) {
3000                    scannedCompatSet.add(chainSig);
3001                }
3002            } catch (CertificateEncodingException e) {
3003                scannedCompatSet.add(sig);
3004            }
3005        }
3006        /*
3007         * Make sure the expanded scanned set contains all signatures in the
3008         * existing one.
3009         */
3010        if (scannedCompatSet.equals(existingSet)) {
3011            // Migrate the old signatures to the new scheme.
3012            existingSigs.assignSignatures(scannedPkg.mSignatures);
3013            // The new KeySets will be re-added later in the scanning process.
3014            mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName);
3015            return PackageManager.SIGNATURE_MATCH;
3016        }
3017        return PackageManager.SIGNATURE_NO_MATCH;
3018    }
3019
3020    @Override
3021    public String[] getPackagesForUid(int uid) {
3022        uid = UserHandle.getAppId(uid);
3023        // reader
3024        synchronized (mPackages) {
3025            Object obj = mSettings.getUserIdLPr(uid);
3026            if (obj instanceof SharedUserSetting) {
3027                final SharedUserSetting sus = (SharedUserSetting) obj;
3028                final int N = sus.packages.size();
3029                final String[] res = new String[N];
3030                final Iterator<PackageSetting> it = sus.packages.iterator();
3031                int i = 0;
3032                while (it.hasNext()) {
3033                    res[i++] = it.next().name;
3034                }
3035                return res;
3036            } else if (obj instanceof PackageSetting) {
3037                final PackageSetting ps = (PackageSetting) obj;
3038                return new String[] { ps.name };
3039            }
3040        }
3041        return null;
3042    }
3043
3044    @Override
3045    public String getNameForUid(int uid) {
3046        // reader
3047        synchronized (mPackages) {
3048            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3049            if (obj instanceof SharedUserSetting) {
3050                final SharedUserSetting sus = (SharedUserSetting) obj;
3051                return sus.name + ":" + sus.userId;
3052            } else if (obj instanceof PackageSetting) {
3053                final PackageSetting ps = (PackageSetting) obj;
3054                return ps.name;
3055            }
3056        }
3057        return null;
3058    }
3059
3060    @Override
3061    public int getUidForSharedUser(String sharedUserName) {
3062        if(sharedUserName == null) {
3063            return -1;
3064        }
3065        // reader
3066        synchronized (mPackages) {
3067            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
3068            if (suid == null) {
3069                return -1;
3070            }
3071            return suid.userId;
3072        }
3073    }
3074
3075    @Override
3076    public int getFlagsForUid(int uid) {
3077        synchronized (mPackages) {
3078            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3079            if (obj instanceof SharedUserSetting) {
3080                final SharedUserSetting sus = (SharedUserSetting) obj;
3081                return sus.pkgFlags;
3082            } else if (obj instanceof PackageSetting) {
3083                final PackageSetting ps = (PackageSetting) obj;
3084                return ps.pkgFlags;
3085            }
3086        }
3087        return 0;
3088    }
3089
3090    @Override
3091    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3092            int flags, int userId) {
3093        if (!sUserManager.exists(userId)) return null;
3094        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
3095        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3096        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3097    }
3098
3099    @Override
3100    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3101            IntentFilter filter, int match, ComponentName activity) {
3102        final int userId = UserHandle.getCallingUserId();
3103        if (DEBUG_PREFERRED) {
3104            Log.v(TAG, "setLastChosenActivity intent=" + intent
3105                + " resolvedType=" + resolvedType
3106                + " flags=" + flags
3107                + " filter=" + filter
3108                + " match=" + match
3109                + " activity=" + activity);
3110            filter.dump(new PrintStreamPrinter(System.out), "    ");
3111        }
3112        intent.setComponent(null);
3113        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3114        // Find any earlier preferred or last chosen entries and nuke them
3115        findPreferredActivity(intent, resolvedType,
3116                flags, query, 0, false, true, false, userId);
3117        // Add the new activity as the last chosen for this filter
3118        addPreferredActivityInternal(filter, match, null, activity, false, userId);
3119    }
3120
3121    @Override
3122    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3123        final int userId = UserHandle.getCallingUserId();
3124        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3125        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3126        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3127                false, false, false, userId);
3128    }
3129
3130    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3131            int flags, List<ResolveInfo> query, int userId) {
3132        if (query != null) {
3133            final int N = query.size();
3134            if (N == 1) {
3135                return query.get(0);
3136            } else if (N > 1) {
3137                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3138                // If there is more than one activity with the same priority,
3139                // then let the user decide between them.
3140                ResolveInfo r0 = query.get(0);
3141                ResolveInfo r1 = query.get(1);
3142                if (DEBUG_INTENT_MATCHING || debug) {
3143                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3144                            + r1.activityInfo.name + "=" + r1.priority);
3145                }
3146                // If the first activity has a higher priority, or a different
3147                // default, then it is always desireable to pick it.
3148                if (r0.priority != r1.priority
3149                        || r0.preferredOrder != r1.preferredOrder
3150                        || r0.isDefault != r1.isDefault) {
3151                    return query.get(0);
3152                }
3153                // If we have saved a preference for a preferred activity for
3154                // this Intent, use that.
3155                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3156                        flags, query, r0.priority, true, false, debug, userId);
3157                if (ri != null) {
3158                    return ri;
3159                }
3160                if (userId != 0) {
3161                    ri = new ResolveInfo(mResolveInfo);
3162                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3163                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3164                            ri.activityInfo.applicationInfo);
3165                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3166                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3167                    return ri;
3168                }
3169                return mResolveInfo;
3170            }
3171        }
3172        return null;
3173    }
3174
3175    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3176            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3177        final int N = query.size();
3178        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3179                .get(userId);
3180        // Get the list of persistent preferred activities that handle the intent
3181        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3182        List<PersistentPreferredActivity> pprefs = ppir != null
3183                ? ppir.queryIntent(intent, resolvedType,
3184                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3185                : null;
3186        if (pprefs != null && pprefs.size() > 0) {
3187            final int M = pprefs.size();
3188            for (int i=0; i<M; i++) {
3189                final PersistentPreferredActivity ppa = pprefs.get(i);
3190                if (DEBUG_PREFERRED || debug) {
3191                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3192                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3193                            + "\n  component=" + ppa.mComponent);
3194                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3195                }
3196                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3197                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3198                if (DEBUG_PREFERRED || debug) {
3199                    Slog.v(TAG, "Found persistent preferred activity:");
3200                    if (ai != null) {
3201                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3202                    } else {
3203                        Slog.v(TAG, "  null");
3204                    }
3205                }
3206                if (ai == null) {
3207                    // This previously registered persistent preferred activity
3208                    // component is no longer known. Ignore it and do NOT remove it.
3209                    continue;
3210                }
3211                for (int j=0; j<N; j++) {
3212                    final ResolveInfo ri = query.get(j);
3213                    if (!ri.activityInfo.applicationInfo.packageName
3214                            .equals(ai.applicationInfo.packageName)) {
3215                        continue;
3216                    }
3217                    if (!ri.activityInfo.name.equals(ai.name)) {
3218                        continue;
3219                    }
3220                    //  Found a persistent preference that can handle the intent.
3221                    if (DEBUG_PREFERRED || debug) {
3222                        Slog.v(TAG, "Returning persistent preferred activity: " +
3223                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3224                    }
3225                    return ri;
3226                }
3227            }
3228        }
3229        return null;
3230    }
3231
3232    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3233            List<ResolveInfo> query, int priority, boolean always,
3234            boolean removeMatches, boolean debug, int userId) {
3235        if (!sUserManager.exists(userId)) return null;
3236        // writer
3237        synchronized (mPackages) {
3238            if (intent.getSelector() != null) {
3239                intent = intent.getSelector();
3240            }
3241            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3242
3243            // Try to find a matching persistent preferred activity.
3244            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3245                    debug, userId);
3246
3247            // If a persistent preferred activity matched, use it.
3248            if (pri != null) {
3249                return pri;
3250            }
3251
3252            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3253            // Get the list of preferred activities that handle the intent
3254            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3255            List<PreferredActivity> prefs = pir != null
3256                    ? pir.queryIntent(intent, resolvedType,
3257                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3258                    : null;
3259            if (prefs != null && prefs.size() > 0) {
3260                // First figure out how good the original match set is.
3261                // We will only allow preferred activities that came
3262                // from the same match quality.
3263                int match = 0;
3264
3265                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3266
3267                final int N = query.size();
3268                for (int j=0; j<N; j++) {
3269                    final ResolveInfo ri = query.get(j);
3270                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3271                            + ": 0x" + Integer.toHexString(match));
3272                    if (ri.match > match) {
3273                        match = ri.match;
3274                    }
3275                }
3276
3277                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3278                        + Integer.toHexString(match));
3279
3280                match &= IntentFilter.MATCH_CATEGORY_MASK;
3281                final int M = prefs.size();
3282                for (int i=0; i<M; i++) {
3283                    final PreferredActivity pa = prefs.get(i);
3284                    if (DEBUG_PREFERRED || debug) {
3285                        Slog.v(TAG, "Checking PreferredActivity ds="
3286                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3287                                + "\n  component=" + pa.mPref.mComponent);
3288                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3289                    }
3290                    if (pa.mPref.mMatch != match) {
3291                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3292                                + Integer.toHexString(pa.mPref.mMatch));
3293                        continue;
3294                    }
3295                    // If it's not an "always" type preferred activity and that's what we're
3296                    // looking for, skip it.
3297                    if (always && !pa.mPref.mAlways) {
3298                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3299                        continue;
3300                    }
3301                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3302                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3303                    if (DEBUG_PREFERRED || debug) {
3304                        Slog.v(TAG, "Found preferred activity:");
3305                        if (ai != null) {
3306                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3307                        } else {
3308                            Slog.v(TAG, "  null");
3309                        }
3310                    }
3311                    if (ai == null) {
3312                        // This previously registered preferred activity
3313                        // component is no longer known.  Most likely an update
3314                        // to the app was installed and in the new version this
3315                        // component no longer exists.  Clean it up by removing
3316                        // it from the preferred activities list, and skip it.
3317                        Slog.w(TAG, "Removing dangling preferred activity: "
3318                                + pa.mPref.mComponent);
3319                        pir.removeFilter(pa);
3320                        continue;
3321                    }
3322                    for (int j=0; j<N; j++) {
3323                        final ResolveInfo ri = query.get(j);
3324                        if (!ri.activityInfo.applicationInfo.packageName
3325                                .equals(ai.applicationInfo.packageName)) {
3326                            continue;
3327                        }
3328                        if (!ri.activityInfo.name.equals(ai.name)) {
3329                            continue;
3330                        }
3331
3332                        if (removeMatches) {
3333                            pir.removeFilter(pa);
3334                            if (DEBUG_PREFERRED) {
3335                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3336                            }
3337                            break;
3338                        }
3339
3340                        // Okay we found a previously set preferred or last chosen app.
3341                        // If the result set is different from when this
3342                        // was created, we need to clear it and re-ask the
3343                        // user their preference, if we're looking for an "always" type entry.
3344                        if (always && !pa.mPref.sameSet(query, priority)) {
3345                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3346                                    + intent + " type " + resolvedType);
3347                            if (DEBUG_PREFERRED) {
3348                                Slog.v(TAG, "Removing preferred activity since set changed "
3349                                        + pa.mPref.mComponent);
3350                            }
3351                            pir.removeFilter(pa);
3352                            // Re-add the filter as a "last chosen" entry (!always)
3353                            PreferredActivity lastChosen = new PreferredActivity(
3354                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3355                            pir.addFilter(lastChosen);
3356                            mSettings.writePackageRestrictionsLPr(userId);
3357                            return null;
3358                        }
3359
3360                        // Yay! Either the set matched or we're looking for the last chosen
3361                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3362                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3363                        mSettings.writePackageRestrictionsLPr(userId);
3364                        return ri;
3365                    }
3366                }
3367            }
3368            mSettings.writePackageRestrictionsLPr(userId);
3369        }
3370        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3371        return null;
3372    }
3373
3374    /*
3375     * Returns if intent can be forwarded from the userId from to dest
3376     */
3377    @Override
3378    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3379            int targetUserId) {
3380        mContext.enforceCallingOrSelfPermission(
3381                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3382        List<CrossProfileIntentFilter> matches =
3383                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3384        if (matches != null) {
3385            int size = matches.size();
3386            for (int i = 0; i < size; i++) {
3387                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3388            }
3389        }
3390        return false;
3391    }
3392
3393    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3394            String resolvedType, int userId) {
3395        CrossProfileIntentResolver cpir = mSettings.mCrossProfileIntentResolvers.get(userId);
3396        if (cpir != null) {
3397            return cpir.queryIntent(intent, resolvedType, false, userId);
3398        }
3399        return null;
3400    }
3401
3402    @Override
3403    public List<ResolveInfo> queryIntentActivities(Intent intent,
3404            String resolvedType, int flags, int userId) {
3405        if (!sUserManager.exists(userId)) return Collections.emptyList();
3406        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3407        ComponentName comp = intent.getComponent();
3408        if (comp == null) {
3409            if (intent.getSelector() != null) {
3410                intent = intent.getSelector();
3411                comp = intent.getComponent();
3412            }
3413        }
3414
3415        if (comp != null) {
3416            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3417            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3418            if (ai != null) {
3419                final ResolveInfo ri = new ResolveInfo();
3420                ri.activityInfo = ai;
3421                list.add(ri);
3422            }
3423            return list;
3424        }
3425
3426        // reader
3427        synchronized (mPackages) {
3428            final String pkgName = intent.getPackage();
3429            if (pkgName == null) {
3430                List<ResolveInfo> result =
3431                        mActivities.queryIntent(intent, resolvedType, flags, userId);
3432                // Checking if we can forward the intent to another user
3433                List<CrossProfileIntentFilter> cpifs =
3434                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3435                if (cpifs != null) {
3436                    CrossProfileIntentFilter crossProfileIntentFilterWithResult = null;
3437                    HashSet<Integer> alreadyTriedUserIds = new HashSet<Integer>();
3438                    for (CrossProfileIntentFilter cpif : cpifs) {
3439                        int targetUserId = cpif.getTargetUserId();
3440                        // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3441                        // match the same an intent. For performance reasons, it is better not to
3442                        // run queryIntent twice for the same userId
3443                        if (!alreadyTriedUserIds.contains(targetUserId)) {
3444                            List<ResolveInfo> resultUser = mActivities.queryIntent(intent,
3445                                    resolvedType, flags, targetUserId);
3446                            if (resultUser != null) {
3447                                crossProfileIntentFilterWithResult = cpif;
3448                                // As soon as there is a match in another user, we add the
3449                                // intentForwarderActivity to the list of ResolveInfo.
3450                                break;
3451                            }
3452                            alreadyTriedUserIds.add(targetUserId);
3453                        }
3454                    }
3455                    if (crossProfileIntentFilterWithResult != null) {
3456                        ResolveInfo forwardingResolveInfo = createForwardingResolveInfo(
3457                                crossProfileIntentFilterWithResult, userId);
3458                        result.add(forwardingResolveInfo);
3459                    }
3460                }
3461                return result;
3462            }
3463            final PackageParser.Package pkg = mPackages.get(pkgName);
3464            if (pkg != null) {
3465                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3466                        pkg.activities, userId);
3467            }
3468            return new ArrayList<ResolveInfo>();
3469        }
3470    }
3471
3472    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter cpif,
3473            int sourceUserId) {
3474        String className;
3475        int targetUserId = cpif.getTargetUserId();
3476        if (targetUserId == UserHandle.USER_OWNER) {
3477            className = FORWARD_INTENT_TO_USER_OWNER;
3478        } else {
3479            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3480        }
3481        ComponentName forwardingActivityComponentName = new ComponentName(
3482                mAndroidApplication.packageName, className);
3483        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3484                sourceUserId);
3485        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3486        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3487        forwardingResolveInfo.priority = 0;
3488        forwardingResolveInfo.preferredOrder = 0;
3489        forwardingResolveInfo.match = 0;
3490        forwardingResolveInfo.isDefault = true;
3491        forwardingResolveInfo.filter = cpif;
3492        return forwardingResolveInfo;
3493    }
3494
3495    @Override
3496    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3497            Intent[] specifics, String[] specificTypes, Intent intent,
3498            String resolvedType, int flags, int userId) {
3499        if (!sUserManager.exists(userId)) return Collections.emptyList();
3500        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3501                "query intent activity options");
3502        final String resultsAction = intent.getAction();
3503
3504        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3505                | PackageManager.GET_RESOLVED_FILTER, userId);
3506
3507        if (DEBUG_INTENT_MATCHING) {
3508            Log.v(TAG, "Query " + intent + ": " + results);
3509        }
3510
3511        int specificsPos = 0;
3512        int N;
3513
3514        // todo: note that the algorithm used here is O(N^2).  This
3515        // isn't a problem in our current environment, but if we start running
3516        // into situations where we have more than 5 or 10 matches then this
3517        // should probably be changed to something smarter...
3518
3519        // First we go through and resolve each of the specific items
3520        // that were supplied, taking care of removing any corresponding
3521        // duplicate items in the generic resolve list.
3522        if (specifics != null) {
3523            for (int i=0; i<specifics.length; i++) {
3524                final Intent sintent = specifics[i];
3525                if (sintent == null) {
3526                    continue;
3527                }
3528
3529                if (DEBUG_INTENT_MATCHING) {
3530                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3531                }
3532
3533                String action = sintent.getAction();
3534                if (resultsAction != null && resultsAction.equals(action)) {
3535                    // If this action was explicitly requested, then don't
3536                    // remove things that have it.
3537                    action = null;
3538                }
3539
3540                ResolveInfo ri = null;
3541                ActivityInfo ai = null;
3542
3543                ComponentName comp = sintent.getComponent();
3544                if (comp == null) {
3545                    ri = resolveIntent(
3546                        sintent,
3547                        specificTypes != null ? specificTypes[i] : null,
3548                            flags, userId);
3549                    if (ri == null) {
3550                        continue;
3551                    }
3552                    if (ri == mResolveInfo) {
3553                        // ACK!  Must do something better with this.
3554                    }
3555                    ai = ri.activityInfo;
3556                    comp = new ComponentName(ai.applicationInfo.packageName,
3557                            ai.name);
3558                } else {
3559                    ai = getActivityInfo(comp, flags, userId);
3560                    if (ai == null) {
3561                        continue;
3562                    }
3563                }
3564
3565                // Look for any generic query activities that are duplicates
3566                // of this specific one, and remove them from the results.
3567                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3568                N = results.size();
3569                int j;
3570                for (j=specificsPos; j<N; j++) {
3571                    ResolveInfo sri = results.get(j);
3572                    if ((sri.activityInfo.name.equals(comp.getClassName())
3573                            && sri.activityInfo.applicationInfo.packageName.equals(
3574                                    comp.getPackageName()))
3575                        || (action != null && sri.filter.matchAction(action))) {
3576                        results.remove(j);
3577                        if (DEBUG_INTENT_MATCHING) Log.v(
3578                            TAG, "Removing duplicate item from " + j
3579                            + " due to specific " + specificsPos);
3580                        if (ri == null) {
3581                            ri = sri;
3582                        }
3583                        j--;
3584                        N--;
3585                    }
3586                }
3587
3588                // Add this specific item to its proper place.
3589                if (ri == null) {
3590                    ri = new ResolveInfo();
3591                    ri.activityInfo = ai;
3592                }
3593                results.add(specificsPos, ri);
3594                ri.specificIndex = i;
3595                specificsPos++;
3596            }
3597        }
3598
3599        // Now we go through the remaining generic results and remove any
3600        // duplicate actions that are found here.
3601        N = results.size();
3602        for (int i=specificsPos; i<N-1; i++) {
3603            final ResolveInfo rii = results.get(i);
3604            if (rii.filter == null) {
3605                continue;
3606            }
3607
3608            // Iterate over all of the actions of this result's intent
3609            // filter...  typically this should be just one.
3610            final Iterator<String> it = rii.filter.actionsIterator();
3611            if (it == null) {
3612                continue;
3613            }
3614            while (it.hasNext()) {
3615                final String action = it.next();
3616                if (resultsAction != null && resultsAction.equals(action)) {
3617                    // If this action was explicitly requested, then don't
3618                    // remove things that have it.
3619                    continue;
3620                }
3621                for (int j=i+1; j<N; j++) {
3622                    final ResolveInfo rij = results.get(j);
3623                    if (rij.filter != null && rij.filter.hasAction(action)) {
3624                        results.remove(j);
3625                        if (DEBUG_INTENT_MATCHING) Log.v(
3626                            TAG, "Removing duplicate item from " + j
3627                            + " due to action " + action + " at " + i);
3628                        j--;
3629                        N--;
3630                    }
3631                }
3632            }
3633
3634            // If the caller didn't request filter information, drop it now
3635            // so we don't have to marshall/unmarshall it.
3636            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3637                rii.filter = null;
3638            }
3639        }
3640
3641        // Filter out the caller activity if so requested.
3642        if (caller != null) {
3643            N = results.size();
3644            for (int i=0; i<N; i++) {
3645                ActivityInfo ainfo = results.get(i).activityInfo;
3646                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3647                        && caller.getClassName().equals(ainfo.name)) {
3648                    results.remove(i);
3649                    break;
3650                }
3651            }
3652        }
3653
3654        // If the caller didn't request filter information,
3655        // drop them now so we don't have to
3656        // marshall/unmarshall it.
3657        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3658            N = results.size();
3659            for (int i=0; i<N; i++) {
3660                results.get(i).filter = null;
3661            }
3662        }
3663
3664        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3665        return results;
3666    }
3667
3668    @Override
3669    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3670            int userId) {
3671        if (!sUserManager.exists(userId)) return Collections.emptyList();
3672        ComponentName comp = intent.getComponent();
3673        if (comp == null) {
3674            if (intent.getSelector() != null) {
3675                intent = intent.getSelector();
3676                comp = intent.getComponent();
3677            }
3678        }
3679        if (comp != null) {
3680            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3681            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3682            if (ai != null) {
3683                ResolveInfo ri = new ResolveInfo();
3684                ri.activityInfo = ai;
3685                list.add(ri);
3686            }
3687            return list;
3688        }
3689
3690        // reader
3691        synchronized (mPackages) {
3692            String pkgName = intent.getPackage();
3693            if (pkgName == null) {
3694                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3695            }
3696            final PackageParser.Package pkg = mPackages.get(pkgName);
3697            if (pkg != null) {
3698                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3699                        userId);
3700            }
3701            return null;
3702        }
3703    }
3704
3705    @Override
3706    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3707        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3708        if (!sUserManager.exists(userId)) return null;
3709        if (query != null) {
3710            if (query.size() >= 1) {
3711                // If there is more than one service with the same priority,
3712                // just arbitrarily pick the first one.
3713                return query.get(0);
3714            }
3715        }
3716        return null;
3717    }
3718
3719    @Override
3720    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3721            int userId) {
3722        if (!sUserManager.exists(userId)) return Collections.emptyList();
3723        ComponentName comp = intent.getComponent();
3724        if (comp == null) {
3725            if (intent.getSelector() != null) {
3726                intent = intent.getSelector();
3727                comp = intent.getComponent();
3728            }
3729        }
3730        if (comp != null) {
3731            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3732            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3733            if (si != null) {
3734                final ResolveInfo ri = new ResolveInfo();
3735                ri.serviceInfo = si;
3736                list.add(ri);
3737            }
3738            return list;
3739        }
3740
3741        // reader
3742        synchronized (mPackages) {
3743            String pkgName = intent.getPackage();
3744            if (pkgName == null) {
3745                return mServices.queryIntent(intent, resolvedType, flags, userId);
3746            }
3747            final PackageParser.Package pkg = mPackages.get(pkgName);
3748            if (pkg != null) {
3749                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3750                        userId);
3751            }
3752            return null;
3753        }
3754    }
3755
3756    @Override
3757    public List<ResolveInfo> queryIntentContentProviders(
3758            Intent intent, String resolvedType, int flags, int userId) {
3759        if (!sUserManager.exists(userId)) return Collections.emptyList();
3760        ComponentName comp = intent.getComponent();
3761        if (comp == null) {
3762            if (intent.getSelector() != null) {
3763                intent = intent.getSelector();
3764                comp = intent.getComponent();
3765            }
3766        }
3767        if (comp != null) {
3768            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3769            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3770            if (pi != null) {
3771                final ResolveInfo ri = new ResolveInfo();
3772                ri.providerInfo = pi;
3773                list.add(ri);
3774            }
3775            return list;
3776        }
3777
3778        // reader
3779        synchronized (mPackages) {
3780            String pkgName = intent.getPackage();
3781            if (pkgName == null) {
3782                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3783            }
3784            final PackageParser.Package pkg = mPackages.get(pkgName);
3785            if (pkg != null) {
3786                return mProviders.queryIntentForPackage(
3787                        intent, resolvedType, flags, pkg.providers, userId);
3788            }
3789            return null;
3790        }
3791    }
3792
3793    @Override
3794    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3795        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3796
3797        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3798
3799        // writer
3800        synchronized (mPackages) {
3801            ArrayList<PackageInfo> list;
3802            if (listUninstalled) {
3803                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3804                for (PackageSetting ps : mSettings.mPackages.values()) {
3805                    PackageInfo pi;
3806                    if (ps.pkg != null) {
3807                        pi = generatePackageInfo(ps.pkg, flags, userId);
3808                    } else {
3809                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3810                    }
3811                    if (pi != null) {
3812                        list.add(pi);
3813                    }
3814                }
3815            } else {
3816                list = new ArrayList<PackageInfo>(mPackages.size());
3817                for (PackageParser.Package p : mPackages.values()) {
3818                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3819                    if (pi != null) {
3820                        list.add(pi);
3821                    }
3822                }
3823            }
3824
3825            return new ParceledListSlice<PackageInfo>(list);
3826        }
3827    }
3828
3829    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3830            String[] permissions, boolean[] tmp, int flags, int userId) {
3831        int numMatch = 0;
3832        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3833        for (int i=0; i<permissions.length; i++) {
3834            if (gp.grantedPermissions.contains(permissions[i])) {
3835                tmp[i] = true;
3836                numMatch++;
3837            } else {
3838                tmp[i] = false;
3839            }
3840        }
3841        if (numMatch == 0) {
3842            return;
3843        }
3844        PackageInfo pi;
3845        if (ps.pkg != null) {
3846            pi = generatePackageInfo(ps.pkg, flags, userId);
3847        } else {
3848            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3849        }
3850        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3851            if (numMatch == permissions.length) {
3852                pi.requestedPermissions = permissions;
3853            } else {
3854                pi.requestedPermissions = new String[numMatch];
3855                numMatch = 0;
3856                for (int i=0; i<permissions.length; i++) {
3857                    if (tmp[i]) {
3858                        pi.requestedPermissions[numMatch] = permissions[i];
3859                        numMatch++;
3860                    }
3861                }
3862            }
3863        }
3864        list.add(pi);
3865    }
3866
3867    @Override
3868    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3869            String[] permissions, int flags, int userId) {
3870        if (!sUserManager.exists(userId)) return null;
3871        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3872
3873        // writer
3874        synchronized (mPackages) {
3875            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3876            boolean[] tmpBools = new boolean[permissions.length];
3877            if (listUninstalled) {
3878                for (PackageSetting ps : mSettings.mPackages.values()) {
3879                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3880                }
3881            } else {
3882                for (PackageParser.Package pkg : mPackages.values()) {
3883                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3884                    if (ps != null) {
3885                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3886                                userId);
3887                    }
3888                }
3889            }
3890
3891            return new ParceledListSlice<PackageInfo>(list);
3892        }
3893    }
3894
3895    @Override
3896    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3897        if (!sUserManager.exists(userId)) return null;
3898        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3899
3900        // writer
3901        synchronized (mPackages) {
3902            ArrayList<ApplicationInfo> list;
3903            if (listUninstalled) {
3904                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3905                for (PackageSetting ps : mSettings.mPackages.values()) {
3906                    ApplicationInfo ai;
3907                    if (ps.pkg != null) {
3908                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3909                                ps.readUserState(userId), userId);
3910                    } else {
3911                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3912                    }
3913                    if (ai != null) {
3914                        list.add(ai);
3915                    }
3916                }
3917            } else {
3918                list = new ArrayList<ApplicationInfo>(mPackages.size());
3919                for (PackageParser.Package p : mPackages.values()) {
3920                    if (p.mExtras != null) {
3921                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3922                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3923                        if (ai != null) {
3924                            list.add(ai);
3925                        }
3926                    }
3927                }
3928            }
3929
3930            return new ParceledListSlice<ApplicationInfo>(list);
3931        }
3932    }
3933
3934    public List<ApplicationInfo> getPersistentApplications(int flags) {
3935        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3936
3937        // reader
3938        synchronized (mPackages) {
3939            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3940            final int userId = UserHandle.getCallingUserId();
3941            while (i.hasNext()) {
3942                final PackageParser.Package p = i.next();
3943                if (p.applicationInfo != null
3944                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3945                        && (!mSafeMode || isSystemApp(p))) {
3946                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3947                    if (ps != null) {
3948                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3949                                ps.readUserState(userId), userId);
3950                        if (ai != null) {
3951                            finalList.add(ai);
3952                        }
3953                    }
3954                }
3955            }
3956        }
3957
3958        return finalList;
3959    }
3960
3961    @Override
3962    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3963        if (!sUserManager.exists(userId)) return null;
3964        // reader
3965        synchronized (mPackages) {
3966            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3967            PackageSetting ps = provider != null
3968                    ? mSettings.mPackages.get(provider.owner.packageName)
3969                    : null;
3970            return ps != null
3971                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3972                    && (!mSafeMode || (provider.info.applicationInfo.flags
3973                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3974                    ? PackageParser.generateProviderInfo(provider, flags,
3975                            ps.readUserState(userId), userId)
3976                    : null;
3977        }
3978    }
3979
3980    /**
3981     * @deprecated
3982     */
3983    @Deprecated
3984    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3985        // reader
3986        synchronized (mPackages) {
3987            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3988                    .entrySet().iterator();
3989            final int userId = UserHandle.getCallingUserId();
3990            while (i.hasNext()) {
3991                Map.Entry<String, PackageParser.Provider> entry = i.next();
3992                PackageParser.Provider p = entry.getValue();
3993                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3994
3995                if (ps != null && p.syncable
3996                        && (!mSafeMode || (p.info.applicationInfo.flags
3997                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3998                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3999                            ps.readUserState(userId), userId);
4000                    if (info != null) {
4001                        outNames.add(entry.getKey());
4002                        outInfo.add(info);
4003                    }
4004                }
4005            }
4006        }
4007    }
4008
4009    @Override
4010    public List<ProviderInfo> queryContentProviders(String processName,
4011            int uid, int flags) {
4012        ArrayList<ProviderInfo> finalList = null;
4013        // reader
4014        synchronized (mPackages) {
4015            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
4016            final int userId = processName != null ?
4017                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4018            while (i.hasNext()) {
4019                final PackageParser.Provider p = i.next();
4020                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4021                if (ps != null && p.info.authority != null
4022                        && (processName == null
4023                                || (p.info.processName.equals(processName)
4024                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4025                        && mSettings.isEnabledLPr(p.info, flags, userId)
4026                        && (!mSafeMode
4027                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4028                    if (finalList == null) {
4029                        finalList = new ArrayList<ProviderInfo>(3);
4030                    }
4031                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4032                            ps.readUserState(userId), userId);
4033                    if (info != null) {
4034                        finalList.add(info);
4035                    }
4036                }
4037            }
4038        }
4039
4040        if (finalList != null) {
4041            Collections.sort(finalList, mProviderInitOrderSorter);
4042        }
4043
4044        return finalList;
4045    }
4046
4047    @Override
4048    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4049            int flags) {
4050        // reader
4051        synchronized (mPackages) {
4052            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4053            return PackageParser.generateInstrumentationInfo(i, flags);
4054        }
4055    }
4056
4057    @Override
4058    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4059            int flags) {
4060        ArrayList<InstrumentationInfo> finalList =
4061            new ArrayList<InstrumentationInfo>();
4062
4063        // reader
4064        synchronized (mPackages) {
4065            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4066            while (i.hasNext()) {
4067                final PackageParser.Instrumentation p = i.next();
4068                if (targetPackage == null
4069                        || targetPackage.equals(p.info.targetPackage)) {
4070                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4071                            flags);
4072                    if (ii != null) {
4073                        finalList.add(ii);
4074                    }
4075                }
4076            }
4077        }
4078
4079        return finalList;
4080    }
4081
4082    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4083        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4084        if (overlays == null) {
4085            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4086            return;
4087        }
4088        for (PackageParser.Package opkg : overlays.values()) {
4089            // Not much to do if idmap fails: we already logged the error
4090            // and we certainly don't want to abort installation of pkg simply
4091            // because an overlay didn't fit properly. For these reasons,
4092            // ignore the return value of createIdmapForPackagePairLI.
4093            createIdmapForPackagePairLI(pkg, opkg);
4094        }
4095    }
4096
4097    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4098            PackageParser.Package opkg) {
4099        if (!opkg.mTrustedOverlay) {
4100            Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " +
4101                    opkg.mScanPath + ": overlay not trusted");
4102            return false;
4103        }
4104        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4105        if (overlaySet == null) {
4106            Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " +
4107                    opkg.mScanPath + " but target package has no known overlays");
4108            return false;
4109        }
4110        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4111        if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) {
4112            Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath);
4113            return false;
4114        }
4115        PackageParser.Package[] overlayArray =
4116            overlaySet.values().toArray(new PackageParser.Package[0]);
4117        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4118            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4119                return p1.mOverlayPriority - p2.mOverlayPriority;
4120            }
4121        };
4122        Arrays.sort(overlayArray, cmp);
4123
4124        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4125        int i = 0;
4126        for (PackageParser.Package p : overlayArray) {
4127            pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir;
4128        }
4129        return true;
4130    }
4131
4132    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4133        String[] files = dir.list();
4134        if (files == null) {
4135            Log.d(TAG, "No files in app dir " + dir);
4136            return;
4137        }
4138
4139        if (DEBUG_PACKAGE_SCANNING) {
4140            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4141                    + " flags=0x" + Integer.toHexString(flags));
4142        }
4143
4144        int i;
4145        for (i=0; i<files.length; i++) {
4146            File file = new File(dir, files[i]);
4147            if (!isPackageFilename(files[i])) {
4148                // Ignore entries which are not apk's
4149                continue;
4150            }
4151            PackageParser.Package pkg = scanPackageLI(file,
4152                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null);
4153            // Don't mess around with apps in system partition.
4154            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4155                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
4156                // Delete the apk
4157                Slog.w(TAG, "Cleaning up failed install of " + file);
4158                file.delete();
4159            }
4160        }
4161    }
4162
4163    private static File getSettingsProblemFile() {
4164        File dataDir = Environment.getDataDirectory();
4165        File systemDir = new File(dataDir, "system");
4166        File fname = new File(systemDir, "uiderrors.txt");
4167        return fname;
4168    }
4169
4170    static void reportSettingsProblem(int priority, String msg) {
4171        try {
4172            File fname = getSettingsProblemFile();
4173            FileOutputStream out = new FileOutputStream(fname, true);
4174            PrintWriter pw = new FastPrintWriter(out);
4175            SimpleDateFormat formatter = new SimpleDateFormat();
4176            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4177            pw.println(dateString + ": " + msg);
4178            pw.close();
4179            FileUtils.setPermissions(
4180                    fname.toString(),
4181                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4182                    -1, -1);
4183        } catch (java.io.IOException e) {
4184        }
4185        Slog.println(priority, TAG, msg);
4186    }
4187
4188    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
4189            PackageParser.Package pkg, File srcFile, int parseFlags) {
4190        if (ps != null
4191                && ps.codePath.equals(srcFile)
4192                && ps.timeStamp == srcFile.lastModified()
4193                && !isCompatSignatureUpdateNeeded(pkg)) {
4194            if (ps.signatures.mSignatures != null
4195                    && ps.signatures.mSignatures.length != 0) {
4196                // Optimization: reuse the existing cached certificates
4197                // if the package appears to be unchanged.
4198                pkg.mSignatures = ps.signatures.mSignatures;
4199                return true;
4200            }
4201
4202            Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
4203        } else {
4204            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4205        }
4206
4207        if (!pp.collectCertificates(pkg, parseFlags)) {
4208            mLastScanError = pp.getParseError();
4209            return false;
4210        }
4211        return true;
4212    }
4213
4214    /*
4215     *  Scan a package and return the newly parsed package.
4216     *  Returns null in case of errors and the error code is stored in mLastScanError
4217     */
4218    private PackageParser.Package scanPackageLI(File scanFile,
4219            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
4220        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4221        String scanPath = scanFile.getPath();
4222        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
4223        parseFlags |= mDefParseFlags;
4224        PackageParser pp = new PackageParser(scanPath);
4225        pp.setSeparateProcesses(mSeparateProcesses);
4226        pp.setOnlyCoreApps(mOnlyCore);
4227        final PackageParser.Package pkg = pp.parsePackage(scanFile,
4228                scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0);
4229
4230        if (pkg == null) {
4231            mLastScanError = pp.getParseError();
4232            return null;
4233        }
4234
4235        PackageSetting ps = null;
4236        PackageSetting updatedPkg;
4237        // reader
4238        synchronized (mPackages) {
4239            // Look to see if we already know about this package.
4240            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4241            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4242                // This package has been renamed to its original name.  Let's
4243                // use that.
4244                ps = mSettings.peekPackageLPr(oldName);
4245            }
4246            // If there was no original package, see one for the real package name.
4247            if (ps == null) {
4248                ps = mSettings.peekPackageLPr(pkg.packageName);
4249            }
4250            // Check to see if this package could be hiding/updating a system
4251            // package.  Must look for it either under the original or real
4252            // package name depending on our state.
4253            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4254            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4255        }
4256        boolean updatedPkgBetter = false;
4257        // First check if this is a system package that may involve an update
4258        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4259            if (ps != null && !ps.codePath.equals(scanFile)) {
4260                // The path has changed from what was last scanned...  check the
4261                // version of the new path against what we have stored to determine
4262                // what to do.
4263                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4264                if (pkg.mVersionCode < ps.versionCode) {
4265                    // The system package has been updated and the code path does not match
4266                    // Ignore entry. Skip it.
4267                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4268                            + " ignored: updated version " + ps.versionCode
4269                            + " better than this " + pkg.mVersionCode);
4270                    if (!updatedPkg.codePath.equals(scanFile)) {
4271                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4272                                + ps.name + " changing from " + updatedPkg.codePathString
4273                                + " to " + scanFile);
4274                        updatedPkg.codePath = scanFile;
4275                        updatedPkg.codePathString = scanFile.toString();
4276                        // This is the point at which we know that the system-disk APK
4277                        // for this package has moved during a reboot (e.g. due to an OTA),
4278                        // so we need to reevaluate it for privilege policy.
4279                        if (locationIsPrivileged(scanFile)) {
4280                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4281                        }
4282                    }
4283                    updatedPkg.pkg = pkg;
4284                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4285                    return null;
4286                } else {
4287                    // The current app on the system partition is better than
4288                    // what we have updated to on the data partition; switch
4289                    // back to the system partition version.
4290                    // At this point, its safely assumed that package installation for
4291                    // apps in system partition will go through. If not there won't be a working
4292                    // version of the app
4293                    // writer
4294                    synchronized (mPackages) {
4295                        // Just remove the loaded entries from package lists.
4296                        mPackages.remove(ps.name);
4297                    }
4298                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4299                            + "reverting from " + ps.codePathString
4300                            + ": new version " + pkg.mVersionCode
4301                            + " better than installed " + ps.versionCode);
4302
4303                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4304                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4305                            getAppInstructionSetFromSettings(ps));
4306                    synchronized (mInstallLock) {
4307                        args.cleanUpResourcesLI();
4308                    }
4309                    synchronized (mPackages) {
4310                        mSettings.enableSystemPackageLPw(ps.name);
4311                    }
4312                    updatedPkgBetter = true;
4313                }
4314            }
4315        }
4316
4317        if (updatedPkg != null) {
4318            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4319            // initially
4320            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4321
4322            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4323            // flag set initially
4324            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4325                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4326            }
4327        }
4328        // Verify certificates against what was last scanned
4329        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
4330            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
4331            return null;
4332        }
4333
4334        /*
4335         * A new system app appeared, but we already had a non-system one of the
4336         * same name installed earlier.
4337         */
4338        boolean shouldHideSystemApp = false;
4339        if (updatedPkg == null && ps != null
4340                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4341            /*
4342             * Check to make sure the signatures match first. If they don't,
4343             * wipe the installed application and its data.
4344             */
4345            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4346                    != PackageManager.SIGNATURE_MATCH) {
4347                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4348                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4349                ps = null;
4350            } else {
4351                /*
4352                 * If the newly-added system app is an older version than the
4353                 * already installed version, hide it. It will be scanned later
4354                 * and re-added like an update.
4355                 */
4356                if (pkg.mVersionCode < ps.versionCode) {
4357                    shouldHideSystemApp = true;
4358                } else {
4359                    /*
4360                     * The newly found system app is a newer version that the
4361                     * one previously installed. Simply remove the
4362                     * already-installed application and replace it with our own
4363                     * while keeping the application data.
4364                     */
4365                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4366                            + ps.codePathString + ": new version " + pkg.mVersionCode
4367                            + " better than installed " + ps.versionCode);
4368                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4369                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4370                            getAppInstructionSetFromSettings(ps));
4371                    synchronized (mInstallLock) {
4372                        args.cleanUpResourcesLI();
4373                    }
4374                }
4375            }
4376        }
4377
4378        // The apk is forward locked (not public) if its code and resources
4379        // are kept in different files. (except for app in either system or
4380        // vendor path).
4381        // TODO grab this value from PackageSettings
4382        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4383            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4384                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4385            }
4386        }
4387
4388        String codePath = null;
4389        String resPath = null;
4390        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4391            if (ps != null && ps.resourcePathString != null) {
4392                resPath = ps.resourcePathString;
4393            } else {
4394                // Should not happen at all. Just log an error.
4395                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4396            }
4397        } else {
4398            resPath = pkg.mScanPath;
4399        }
4400
4401        codePath = pkg.mScanPath;
4402        // Set application objects path explicitly.
4403        setApplicationInfoPaths(pkg, codePath, resPath);
4404        // Note that we invoke the following method only if we are about to unpack an application
4405        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4406                | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride);
4407
4408        /*
4409         * If the system app should be overridden by a previously installed
4410         * data, hide the system app now and let the /data/app scan pick it up
4411         * again.
4412         */
4413        if (shouldHideSystemApp) {
4414            synchronized (mPackages) {
4415                /*
4416                 * We have to grant systems permissions before we hide, because
4417                 * grantPermissions will assume the package update is trying to
4418                 * expand its permissions.
4419                 */
4420                grantPermissionsLPw(pkg, true);
4421                mSettings.disableSystemPackageLPw(pkg.packageName);
4422            }
4423        }
4424
4425        return scannedPkg;
4426    }
4427
4428    private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
4429            String destResPath) {
4430        pkg.mPath = pkg.mScanPath = destCodePath;
4431        pkg.applicationInfo.sourceDir = destCodePath;
4432        pkg.applicationInfo.publicSourceDir = destResPath;
4433    }
4434
4435    private static String fixProcessName(String defProcessName,
4436            String processName, int uid) {
4437        if (processName == null) {
4438            return defProcessName;
4439        }
4440        return processName;
4441    }
4442
4443    private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) {
4444        if (pkgSetting.signatures.mSignatures != null) {
4445            // Already existing package. Make sure signatures match
4446            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4447                    == PackageManager.SIGNATURE_MATCH;
4448            if (!match) {
4449                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4450                        == PackageManager.SIGNATURE_MATCH;
4451            }
4452            if (!match) {
4453                Slog.e(TAG, "Package " + pkg.packageName
4454                        + " signatures do not match the previously installed version; ignoring!");
4455                mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4456                return false;
4457            }
4458        }
4459        // Check for shared user signatures
4460        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4461            // Already existing package. Make sure signatures match
4462            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4463                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4464            if (!match) {
4465                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4466                        == PackageManager.SIGNATURE_MATCH;
4467            }
4468            if (!match) {
4469                Slog.e(TAG, "Package " + pkg.packageName
4470                        + " has no signatures that match those in shared user "
4471                        + pkgSetting.sharedUser.name + "; ignoring!");
4472                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4473                return false;
4474            }
4475        }
4476        return true;
4477    }
4478
4479    /**
4480     * Enforces that only the system UID or root's UID can call a method exposed
4481     * via Binder.
4482     *
4483     * @param message used as message if SecurityException is thrown
4484     * @throws SecurityException if the caller is not system or root
4485     */
4486    private static final void enforceSystemOrRoot(String message) {
4487        final int uid = Binder.getCallingUid();
4488        if (uid != Process.SYSTEM_UID && uid != 0) {
4489            throw new SecurityException(message);
4490        }
4491    }
4492
4493    @Override
4494    public void performBootDexOpt() {
4495        enforceSystemOrRoot("Only the system can request dexopt be performed");
4496
4497        final HashSet<PackageParser.Package> pkgs;
4498        synchronized (mPackages) {
4499            pkgs = mDeferredDexOpt;
4500            mDeferredDexOpt = null;
4501        }
4502
4503        if (pkgs != null) {
4504            // Filter out packages that aren't recently used.
4505            //
4506            // The exception is first boot of a non-eng device, which
4507            // should do a full dexopt.
4508            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4509            if (eng || !isFirstBoot()) {
4510                // TODO: add a property to control this?
4511                long dexOptLRUThresholdInMinutes;
4512                if (eng) {
4513                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4514                } else {
4515                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4516                }
4517                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4518
4519                int total = pkgs.size();
4520                int skipped = 0;
4521                long now = System.currentTimeMillis();
4522                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4523                    PackageParser.Package pkg = i.next();
4524                    long then = pkg.mLastPackageUsageTimeInMills;
4525                    if (then + dexOptLRUThresholdInMills < now) {
4526                        if (DEBUG_DEXOPT) {
4527                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4528                                  ((then == 0) ? "never" : new Date(then)));
4529                        }
4530                        i.remove();
4531                        skipped++;
4532                    }
4533                }
4534                if (DEBUG_DEXOPT) {
4535                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4536                }
4537            }
4538
4539            int i = 0;
4540            for (PackageParser.Package pkg : pkgs) {
4541                i++;
4542                if (DEBUG_DEXOPT) {
4543                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4544                          + ": " + pkg.packageName);
4545                }
4546                if (!isFirstBoot()) {
4547                    try {
4548                        ActivityManagerNative.getDefault().showBootMessage(
4549                                mContext.getResources().getString(
4550                                        R.string.android_upgrading_apk,
4551                                        i, pkgs.size()), true);
4552                    } catch (RemoteException e) {
4553                    }
4554                }
4555                PackageParser.Package p = pkg;
4556                synchronized (mInstallLock) {
4557                    if (p.mDexOptNeeded) {
4558                        performDexOptLI(p, false /* force dex */, false /* defer */,
4559                                true /* include dependencies */);
4560                    }
4561                }
4562            }
4563        }
4564    }
4565
4566    @Override
4567    public boolean performDexOpt(String packageName) {
4568        enforceSystemOrRoot("Only the system can request dexopt be performed");
4569        return performDexOpt(packageName, true);
4570    }
4571
4572    public boolean performDexOpt(String packageName, boolean updateUsage) {
4573
4574        PackageParser.Package p;
4575        synchronized (mPackages) {
4576            p = mPackages.get(packageName);
4577            if (p == null) {
4578                return false;
4579            }
4580            if (updateUsage) {
4581                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4582            }
4583            mPackageUsage.write(false);
4584            if (!p.mDexOptNeeded) {
4585                return false;
4586            }
4587        }
4588
4589        synchronized (mInstallLock) {
4590            return performDexOptLI(p, false /* force dex */, false /* defer */,
4591                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4592        }
4593    }
4594
4595    public HashSet<String> getPackagesThatNeedDexOpt() {
4596        HashSet<String> pkgs = null;
4597        synchronized (mPackages) {
4598            for (PackageParser.Package p : mPackages.values()) {
4599                if (DEBUG_DEXOPT) {
4600                    Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded);
4601                }
4602                if (!p.mDexOptNeeded) {
4603                    continue;
4604                }
4605                if (pkgs == null) {
4606                    pkgs = new HashSet<String>();
4607                }
4608                pkgs.add(p.packageName);
4609            }
4610        }
4611        return pkgs;
4612    }
4613
4614    public void shutdown() {
4615        mPackageUsage.write(true);
4616    }
4617
4618    private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet,
4619             boolean forceDex, boolean defer, HashSet<String> done) {
4620        for (int i=0; i<libs.size(); i++) {
4621            PackageParser.Package libPkg;
4622            String libName;
4623            synchronized (mPackages) {
4624                libName = libs.get(i);
4625                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4626                if (lib != null && lib.apk != null) {
4627                    libPkg = mPackages.get(lib.apk);
4628                } else {
4629                    libPkg = null;
4630                }
4631            }
4632            if (libPkg != null && !done.contains(libName)) {
4633                performDexOptLI(libPkg, instructionSet, forceDex, defer, done);
4634            }
4635        }
4636    }
4637
4638    static final int DEX_OPT_SKIPPED = 0;
4639    static final int DEX_OPT_PERFORMED = 1;
4640    static final int DEX_OPT_DEFERRED = 2;
4641    static final int DEX_OPT_FAILED = -1;
4642
4643    private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride,
4644            boolean forceDex, boolean defer, HashSet<String> done) {
4645        final String instructionSet = instructionSetOverride != null ?
4646                instructionSetOverride : getAppInstructionSet(pkg.applicationInfo);
4647
4648        if (done != null) {
4649            done.add(pkg.packageName);
4650            if (pkg.usesLibraries != null) {
4651                performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done);
4652            }
4653            if (pkg.usesOptionalLibraries != null) {
4654                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done);
4655            }
4656        }
4657
4658        boolean performed = false;
4659        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4660            String path = pkg.mScanPath;
4661            try {
4662                boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path,
4663                                                                                pkg.packageName,
4664                                                                                instructionSet,
4665                                                                                defer);
4666                // There are three basic cases here:
4667                // 1.) we need to dexopt, either because we are forced or it is needed
4668                // 2.) we are defering a needed dexopt
4669                // 3.) we are skipping an unneeded dexopt
4670                if (forceDex || (!defer && isDexOptNeededInternal)) {
4671                    Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
4672                    final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4673                    int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4674                                                pkg.packageName, instructionSet);
4675                    // Note that we ran dexopt, since rerunning will
4676                    // probably just result in an error again.
4677                    pkg.mDexOptNeeded = false;
4678                    if (ret < 0) {
4679                        return DEX_OPT_FAILED;
4680                    }
4681                    return DEX_OPT_PERFORMED;
4682                }
4683                if (defer && isDexOptNeededInternal) {
4684                    if (mDeferredDexOpt == null) {
4685                        mDeferredDexOpt = new HashSet<PackageParser.Package>();
4686                    }
4687                    mDeferredDexOpt.add(pkg);
4688                    return DEX_OPT_DEFERRED;
4689                }
4690                pkg.mDexOptNeeded = false;
4691                return DEX_OPT_SKIPPED;
4692            } catch (FileNotFoundException e) {
4693                Slog.w(TAG, "Apk not found for dexopt: " + path);
4694                return DEX_OPT_FAILED;
4695            } catch (IOException e) {
4696                Slog.w(TAG, "IOException reading apk: " + path, e);
4697                return DEX_OPT_FAILED;
4698            } catch (StaleDexCacheError e) {
4699                Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4700                return DEX_OPT_FAILED;
4701            } catch (Exception e) {
4702                Slog.w(TAG, "Exception when doing dexopt : ", e);
4703                return DEX_OPT_FAILED;
4704            }
4705        }
4706        return DEX_OPT_SKIPPED;
4707    }
4708
4709    private String getAppInstructionSet(ApplicationInfo info) {
4710        String instructionSet = getPreferredInstructionSet();
4711
4712        if (info.cpuAbi != null) {
4713            instructionSet = VMRuntime.getInstructionSet(info.cpuAbi);
4714        }
4715
4716        return instructionSet;
4717    }
4718
4719    private String getAppInstructionSetFromSettings(PackageSetting ps) {
4720        String instructionSet = getPreferredInstructionSet();
4721
4722        if (ps.cpuAbiString != null) {
4723            instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
4724        }
4725
4726        return instructionSet;
4727    }
4728
4729    private static String getPreferredInstructionSet() {
4730        if (sPreferredInstructionSet == null) {
4731            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4732        }
4733
4734        return sPreferredInstructionSet;
4735    }
4736
4737    private static List<String> getAllInstructionSets() {
4738        final String[] allAbis = Build.SUPPORTED_ABIS;
4739        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4740
4741        for (String abi : allAbis) {
4742            final String instructionSet = VMRuntime.getInstructionSet(abi);
4743            if (!allInstructionSets.contains(instructionSet)) {
4744                allInstructionSets.add(instructionSet);
4745            }
4746        }
4747
4748        return allInstructionSets;
4749    }
4750
4751    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4752            boolean inclDependencies) {
4753        HashSet<String> done;
4754        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4755            done = new HashSet<String>();
4756            done.add(pkg.packageName);
4757        } else {
4758            done = null;
4759        }
4760        return performDexOptLI(pkg, null /* instruction set override */,  forceDex, defer, done);
4761    }
4762
4763    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4764        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4765            Slog.w(TAG, "Unable to update from " + oldPkg.name
4766                    + " to " + newPkg.packageName
4767                    + ": old package not in system partition");
4768            return false;
4769        } else if (mPackages.get(oldPkg.name) != null) {
4770            Slog.w(TAG, "Unable to update from " + oldPkg.name
4771                    + " to " + newPkg.packageName
4772                    + ": old package still exists");
4773            return false;
4774        }
4775        return true;
4776    }
4777
4778    File getDataPathForUser(int userId) {
4779        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4780    }
4781
4782    private File getDataPathForPackage(String packageName, int userId) {
4783        /*
4784         * Until we fully support multiple users, return the directory we
4785         * previously would have. The PackageManagerTests will need to be
4786         * revised when this is changed back..
4787         */
4788        if (userId == 0) {
4789            return new File(mAppDataDir, packageName);
4790        } else {
4791            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4792                + File.separator + packageName);
4793        }
4794    }
4795
4796    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4797        int[] users = sUserManager.getUserIds();
4798        int res = mInstaller.install(packageName, uid, uid, seinfo);
4799        if (res < 0) {
4800            return res;
4801        }
4802        for (int user : users) {
4803            if (user != 0) {
4804                res = mInstaller.createUserData(packageName,
4805                        UserHandle.getUid(user, uid), user, seinfo);
4806                if (res < 0) {
4807                    return res;
4808                }
4809            }
4810        }
4811        return res;
4812    }
4813
4814    private int removeDataDirsLI(String packageName) {
4815        int[] users = sUserManager.getUserIds();
4816        int res = 0;
4817        for (int user : users) {
4818            int resInner = mInstaller.remove(packageName, user);
4819            if (resInner < 0) {
4820                res = resInner;
4821            }
4822        }
4823
4824        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4825        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4826        if (!nativeLibraryFile.delete()) {
4827            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4828        }
4829
4830        return res;
4831    }
4832
4833    private int addSharedLibraryLPw(final SharedLibraryEntry file, int num,
4834            PackageParser.Package changingLib) {
4835        if (file.path != null) {
4836            mTmpSharedLibraries[num] = file.path;
4837            return num+1;
4838        }
4839        PackageParser.Package p = mPackages.get(file.apk);
4840        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4841            // If we are doing this while in the middle of updating a library apk,
4842            // then we need to make sure to use that new apk for determining the
4843            // dependencies here.  (We haven't yet finished committing the new apk
4844            // to the package manager state.)
4845            if (p == null || p.packageName.equals(changingLib.packageName)) {
4846                p = changingLib;
4847            }
4848        }
4849        if (p != null) {
4850            String path = p.mPath;
4851            for (int i=0; i<num; i++) {
4852                if (mTmpSharedLibraries[i].equals(path)) {
4853                    return num;
4854                }
4855            }
4856            mTmpSharedLibraries[num] = p.mPath;
4857            return num+1;
4858        }
4859        return num;
4860    }
4861
4862    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4863            PackageParser.Package changingLib) {
4864        // We might be upgrading from a version of the platform that did not
4865        // provide per-package native library directories for system apps.
4866        // Fix that up here.
4867        if (isSystemApp(pkg)) {
4868            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4869            setInternalAppNativeLibraryPath(pkg, ps);
4870        }
4871
4872        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4873            if (mTmpSharedLibraries == null ||
4874                    mTmpSharedLibraries.length < mSharedLibraries.size()) {
4875                mTmpSharedLibraries = new String[mSharedLibraries.size()];
4876            }
4877            int num = 0;
4878            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4879            for (int i=0; i<N; i++) {
4880                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4881                if (file == null) {
4882                    Slog.e(TAG, "Package " + pkg.packageName
4883                            + " requires unavailable shared library "
4884                            + pkg.usesLibraries.get(i) + "; failing!");
4885                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4886                    return false;
4887                }
4888                num = addSharedLibraryLPw(file, num, changingLib);
4889            }
4890            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4891            for (int i=0; i<N; i++) {
4892                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4893                if (file == null) {
4894                    Slog.w(TAG, "Package " + pkg.packageName
4895                            + " desires unavailable shared library "
4896                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4897                } else {
4898                    num = addSharedLibraryLPw(file, num, changingLib);
4899                }
4900            }
4901            if (num > 0) {
4902                pkg.usesLibraryFiles = new String[num];
4903                System.arraycopy(mTmpSharedLibraries, 0,
4904                        pkg.usesLibraryFiles, 0, num);
4905            } else {
4906                pkg.usesLibraryFiles = null;
4907            }
4908        }
4909        return true;
4910    }
4911
4912    private static boolean hasString(List<String> list, List<String> which) {
4913        if (list == null) {
4914            return false;
4915        }
4916        for (int i=list.size()-1; i>=0; i--) {
4917            for (int j=which.size()-1; j>=0; j--) {
4918                if (which.get(j).equals(list.get(i))) {
4919                    return true;
4920                }
4921            }
4922        }
4923        return false;
4924    }
4925
4926    private void updateAllSharedLibrariesLPw() {
4927        for (PackageParser.Package pkg : mPackages.values()) {
4928            updateSharedLibrariesLPw(pkg, null);
4929        }
4930    }
4931
4932    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4933            PackageParser.Package changingPkg) {
4934        ArrayList<PackageParser.Package> res = null;
4935        for (PackageParser.Package pkg : mPackages.values()) {
4936            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4937                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4938                if (res == null) {
4939                    res = new ArrayList<PackageParser.Package>();
4940                }
4941                res.add(pkg);
4942                updateSharedLibrariesLPw(pkg, changingPkg);
4943            }
4944        }
4945        return res;
4946    }
4947
4948    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4949            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
4950        File scanFile = new File(pkg.mScanPath);
4951        if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
4952                pkg.applicationInfo.publicSourceDir == null) {
4953            // Bail out. The resource and code paths haven't been set.
4954            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4955            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4956            return null;
4957        }
4958
4959        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4960            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4961        }
4962
4963        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4964            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4965        }
4966
4967        if (mCustomResolverComponentName != null &&
4968                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4969            setUpCustomResolverActivity(pkg);
4970        }
4971
4972        if (pkg.packageName.equals("android")) {
4973            synchronized (mPackages) {
4974                if (mAndroidApplication != null) {
4975                    Slog.w(TAG, "*************************************************");
4976                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4977                    Slog.w(TAG, " file=" + scanFile);
4978                    Slog.w(TAG, "*************************************************");
4979                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4980                    return null;
4981                }
4982
4983                // Set up information for our fall-back user intent resolution activity.
4984                mPlatformPackage = pkg;
4985                pkg.mVersionCode = mSdkVersion;
4986                mAndroidApplication = pkg.applicationInfo;
4987
4988                if (!mResolverReplaced) {
4989                    mResolveActivity.applicationInfo = mAndroidApplication;
4990                    mResolveActivity.name = ResolverActivity.class.getName();
4991                    mResolveActivity.packageName = mAndroidApplication.packageName;
4992                    mResolveActivity.processName = "system:ui";
4993                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4994                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
4995                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4996                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
4997                    mResolveActivity.exported = true;
4998                    mResolveActivity.enabled = true;
4999                    mResolveInfo.activityInfo = mResolveActivity;
5000                    mResolveInfo.priority = 0;
5001                    mResolveInfo.preferredOrder = 0;
5002                    mResolveInfo.match = 0;
5003                    mResolveComponentName = new ComponentName(
5004                            mAndroidApplication.packageName, mResolveActivity.name);
5005                }
5006            }
5007        }
5008
5009        if (DEBUG_PACKAGE_SCANNING) {
5010            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5011                Log.d(TAG, "Scanning package " + pkg.packageName);
5012        }
5013
5014        if (mPackages.containsKey(pkg.packageName)
5015                || mSharedLibraries.containsKey(pkg.packageName)) {
5016            Slog.w(TAG, "Application package " + pkg.packageName
5017                    + " already installed.  Skipping duplicate.");
5018            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
5019            return null;
5020        }
5021
5022        // Initialize package source and resource directories
5023        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
5024        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
5025
5026        SharedUserSetting suid = null;
5027        PackageSetting pkgSetting = null;
5028
5029        if (!isSystemApp(pkg)) {
5030            // Only system apps can use these features.
5031            pkg.mOriginalPackages = null;
5032            pkg.mRealPackage = null;
5033            pkg.mAdoptPermissions = null;
5034        }
5035
5036        // writer
5037        synchronized (mPackages) {
5038            if (pkg.mSharedUserId != null) {
5039                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5040                if (suid == null) {
5041                    Slog.w(TAG, "Creating application package " + pkg.packageName
5042                            + " for shared user failed");
5043                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5044                    return null;
5045                }
5046                if (DEBUG_PACKAGE_SCANNING) {
5047                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5048                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5049                                + "): packages=" + suid.packages);
5050                }
5051            }
5052
5053            // Check if we are renaming from an original package name.
5054            PackageSetting origPackage = null;
5055            String realName = null;
5056            if (pkg.mOriginalPackages != null) {
5057                // This package may need to be renamed to a previously
5058                // installed name.  Let's check on that...
5059                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5060                if (pkg.mOriginalPackages.contains(renamed)) {
5061                    // This package had originally been installed as the
5062                    // original name, and we have already taken care of
5063                    // transitioning to the new one.  Just update the new
5064                    // one to continue using the old name.
5065                    realName = pkg.mRealPackage;
5066                    if (!pkg.packageName.equals(renamed)) {
5067                        // Callers into this function may have already taken
5068                        // care of renaming the package; only do it here if
5069                        // it is not already done.
5070                        pkg.setPackageName(renamed);
5071                    }
5072
5073                } else {
5074                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5075                        if ((origPackage = mSettings.peekPackageLPr(
5076                                pkg.mOriginalPackages.get(i))) != null) {
5077                            // We do have the package already installed under its
5078                            // original name...  should we use it?
5079                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5080                                // New package is not compatible with original.
5081                                origPackage = null;
5082                                continue;
5083                            } else if (origPackage.sharedUser != null) {
5084                                // Make sure uid is compatible between packages.
5085                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5086                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5087                                            + " to " + pkg.packageName + ": old uid "
5088                                            + origPackage.sharedUser.name
5089                                            + " differs from " + pkg.mSharedUserId);
5090                                    origPackage = null;
5091                                    continue;
5092                                }
5093                            } else {
5094                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5095                                        + pkg.packageName + " to old name " + origPackage.name);
5096                            }
5097                            break;
5098                        }
5099                    }
5100                }
5101            }
5102
5103            if (mTransferedPackages.contains(pkg.packageName)) {
5104                Slog.w(TAG, "Package " + pkg.packageName
5105                        + " was transferred to another, but its .apk remains");
5106            }
5107
5108            // Just create the setting, don't add it yet. For already existing packages
5109            // the PkgSetting exists already and doesn't have to be created.
5110            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5111                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
5112                    pkg.applicationInfo.cpuAbi,
5113                    pkg.applicationInfo.flags, user, false);
5114            if (pkgSetting == null) {
5115                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
5116                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5117                return null;
5118            }
5119
5120            if (pkgSetting.origPackage != null) {
5121                // If we are first transitioning from an original package,
5122                // fix up the new package's name now.  We need to do this after
5123                // looking up the package under its new name, so getPackageLP
5124                // can take care of fiddling things correctly.
5125                pkg.setPackageName(origPackage.name);
5126
5127                // File a report about this.
5128                String msg = "New package " + pkgSetting.realName
5129                        + " renamed to replace old package " + pkgSetting.name;
5130                reportSettingsProblem(Log.WARN, msg);
5131
5132                // Make a note of it.
5133                mTransferedPackages.add(origPackage.name);
5134
5135                // No longer need to retain this.
5136                pkgSetting.origPackage = null;
5137            }
5138
5139            if (realName != null) {
5140                // Make a note of it.
5141                mTransferedPackages.add(pkg.packageName);
5142            }
5143
5144            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5145                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5146            }
5147
5148            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5149                // Check all shared libraries and map to their actual file path.
5150                // We only do this here for apps not on a system dir, because those
5151                // are the only ones that can fail an install due to this.  We
5152                // will take care of the system apps by updating all of their
5153                // library paths after the scan is done.
5154                if (!updateSharedLibrariesLPw(pkg, null)) {
5155                    return null;
5156                }
5157            }
5158
5159            if (mFoundPolicyFile) {
5160                SELinuxMMAC.assignSeinfoValue(pkg);
5161            }
5162
5163            pkg.applicationInfo.uid = pkgSetting.appId;
5164            pkg.mExtras = pkgSetting;
5165
5166            if (!verifySignaturesLP(pkgSetting, pkg)) {
5167                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5168                    return null;
5169                }
5170                // The signature has changed, but this package is in the system
5171                // image...  let's recover!
5172                pkgSetting.signatures.mSignatures = pkg.mSignatures;
5173                // However...  if this package is part of a shared user, but it
5174                // doesn't match the signature of the shared user, let's fail.
5175                // What this means is that you can't change the signatures
5176                // associated with an overall shared user, which doesn't seem all
5177                // that unreasonable.
5178                if (pkgSetting.sharedUser != null) {
5179                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5180                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5181                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
5182                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5183                        return null;
5184                    }
5185                }
5186                // File a report about this.
5187                String msg = "System package " + pkg.packageName
5188                        + " signature changed; retaining data.";
5189                reportSettingsProblem(Log.WARN, msg);
5190            }
5191
5192            // Verify that this new package doesn't have any content providers
5193            // that conflict with existing packages.  Only do this if the
5194            // package isn't already installed, since we don't want to break
5195            // things that are installed.
5196            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5197                final int N = pkg.providers.size();
5198                int i;
5199                for (i=0; i<N; i++) {
5200                    PackageParser.Provider p = pkg.providers.get(i);
5201                    if (p.info.authority != null) {
5202                        String names[] = p.info.authority.split(";");
5203                        for (int j = 0; j < names.length; j++) {
5204                            if (mProvidersByAuthority.containsKey(names[j])) {
5205                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5206                                Slog.w(TAG, "Can't install because provider name " + names[j] +
5207                                        " (in package " + pkg.applicationInfo.packageName +
5208                                        ") is already used by "
5209                                        + ((other != null && other.getComponentName() != null)
5210                                                ? other.getComponentName().getPackageName() : "?"));
5211                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
5212                                return null;
5213                            }
5214                        }
5215                    }
5216                }
5217            }
5218
5219            if (pkg.mAdoptPermissions != null) {
5220                // This package wants to adopt ownership of permissions from
5221                // another package.
5222                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5223                    final String origName = pkg.mAdoptPermissions.get(i);
5224                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5225                    if (orig != null) {
5226                        if (verifyPackageUpdateLPr(orig, pkg)) {
5227                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5228                                    + pkg.packageName);
5229                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5230                        }
5231                    }
5232                }
5233            }
5234        }
5235
5236        final String pkgName = pkg.packageName;
5237
5238        final long scanFileTime = scanFile.lastModified();
5239        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5240        pkg.applicationInfo.processName = fixProcessName(
5241                pkg.applicationInfo.packageName,
5242                pkg.applicationInfo.processName,
5243                pkg.applicationInfo.uid);
5244
5245        File dataPath;
5246        if (mPlatformPackage == pkg) {
5247            // The system package is special.
5248            dataPath = new File (Environment.getDataDirectory(), "system");
5249            pkg.applicationInfo.dataDir = dataPath.getPath();
5250        } else {
5251            // This is a normal package, need to make its data directory.
5252            dataPath = getDataPathForPackage(pkg.packageName, 0);
5253
5254            boolean uidError = false;
5255
5256            if (dataPath.exists()) {
5257                int currentUid = 0;
5258                try {
5259                    StructStat stat = Os.stat(dataPath.getPath());
5260                    currentUid = stat.st_uid;
5261                } catch (ErrnoException e) {
5262                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5263                }
5264
5265                // If we have mismatched owners for the data path, we have a problem.
5266                if (currentUid != pkg.applicationInfo.uid) {
5267                    boolean recovered = false;
5268                    if (currentUid == 0) {
5269                        // The directory somehow became owned by root.  Wow.
5270                        // This is probably because the system was stopped while
5271                        // installd was in the middle of messing with its libs
5272                        // directory.  Ask installd to fix that.
5273                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5274                                pkg.applicationInfo.uid);
5275                        if (ret >= 0) {
5276                            recovered = true;
5277                            String msg = "Package " + pkg.packageName
5278                                    + " unexpectedly changed to uid 0; recovered to " +
5279                                    + pkg.applicationInfo.uid;
5280                            reportSettingsProblem(Log.WARN, msg);
5281                        }
5282                    }
5283                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5284                            || (scanMode&SCAN_BOOTING) != 0)) {
5285                        // If this is a system app, we can at least delete its
5286                        // current data so the application will still work.
5287                        int ret = removeDataDirsLI(pkgName);
5288                        if (ret >= 0) {
5289                            // TODO: Kill the processes first
5290                            // Old data gone!
5291                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5292                                    ? "System package " : "Third party package ";
5293                            String msg = prefix + pkg.packageName
5294                                    + " has changed from uid: "
5295                                    + currentUid + " to "
5296                                    + pkg.applicationInfo.uid + "; old data erased";
5297                            reportSettingsProblem(Log.WARN, msg);
5298                            recovered = true;
5299
5300                            // And now re-install the app.
5301                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5302                                                   pkg.applicationInfo.seinfo);
5303                            if (ret == -1) {
5304                                // Ack should not happen!
5305                                msg = prefix + pkg.packageName
5306                                        + " could not have data directory re-created after delete.";
5307                                reportSettingsProblem(Log.WARN, msg);
5308                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5309                                return null;
5310                            }
5311                        }
5312                        if (!recovered) {
5313                            mHasSystemUidErrors = true;
5314                        }
5315                    } else if (!recovered) {
5316                        // If we allow this install to proceed, we will be broken.
5317                        // Abort, abort!
5318                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
5319                        return null;
5320                    }
5321                    if (!recovered) {
5322                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5323                            + pkg.applicationInfo.uid + "/fs_"
5324                            + currentUid;
5325                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5326                        String msg = "Package " + pkg.packageName
5327                                + " has mismatched uid: "
5328                                + currentUid + " on disk, "
5329                                + pkg.applicationInfo.uid + " in settings";
5330                        // writer
5331                        synchronized (mPackages) {
5332                            mSettings.mReadMessages.append(msg);
5333                            mSettings.mReadMessages.append('\n');
5334                            uidError = true;
5335                            if (!pkgSetting.uidError) {
5336                                reportSettingsProblem(Log.ERROR, msg);
5337                            }
5338                        }
5339                    }
5340                }
5341                pkg.applicationInfo.dataDir = dataPath.getPath();
5342                if (mShouldRestoreconData) {
5343                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5344                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5345                                pkg.applicationInfo.uid);
5346                }
5347            } else {
5348                if (DEBUG_PACKAGE_SCANNING) {
5349                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5350                        Log.v(TAG, "Want this data dir: " + dataPath);
5351                }
5352                //invoke installer to do the actual installation
5353                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5354                                           pkg.applicationInfo.seinfo);
5355                if (ret < 0) {
5356                    // Error from installer
5357                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5358                    return null;
5359                }
5360
5361                if (dataPath.exists()) {
5362                    pkg.applicationInfo.dataDir = dataPath.getPath();
5363                } else {
5364                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5365                    pkg.applicationInfo.dataDir = null;
5366                }
5367            }
5368
5369            /*
5370             * Set the data dir to the default "/data/data/<package name>/lib"
5371             * if we got here without anyone telling us different (e.g., apps
5372             * stored on SD card have their native libraries stored in the ASEC
5373             * container with the APK).
5374             *
5375             * This happens during an upgrade from a package settings file that
5376             * doesn't have a native library path attribute at all.
5377             */
5378            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
5379                if (pkgSetting.nativeLibraryPathString == null) {
5380                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
5381                } else {
5382                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
5383                }
5384            }
5385            pkgSetting.uidError = uidError;
5386        }
5387
5388        String path = scanFile.getPath();
5389        /* Note: We don't want to unpack the native binaries for
5390         *        system applications, unless they have been updated
5391         *        (the binaries are already under /system/lib).
5392         *        Also, don't unpack libs for apps on the external card
5393         *        since they should have their libraries in the ASEC
5394         *        container already.
5395         *
5396         *        In other words, we're going to unpack the binaries
5397         *        only for non-system apps and system app upgrades.
5398         */
5399        if (pkg.applicationInfo.nativeLibraryDir != null) {
5400            final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5401            try {
5402                // Enable gross and lame hacks for apps that are built with old
5403                // SDK tools. We must scan their APKs for renderscript bitcode and
5404                // not launch them if it's present. Don't bother checking on devices
5405                // that don't have 64 bit support.
5406                String[] abiList = Build.SUPPORTED_ABIS;
5407                boolean hasLegacyRenderscriptBitcode = false;
5408                if (abiOverride != null) {
5409                    abiList = new String[] { abiOverride };
5410                } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
5411                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5412                    abiList = Build.SUPPORTED_32_BIT_ABIS;
5413                    hasLegacyRenderscriptBitcode = true;
5414                }
5415
5416                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5417                final String dataPathString = dataPath.getCanonicalPath();
5418
5419                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5420                    /*
5421                     * Upgrading from a previous version of the OS sometimes
5422                     * leaves native libraries in the /data/data/<app>/lib
5423                     * directory for system apps even when they shouldn't be.
5424                     * Recent changes in the JNI library search path
5425                     * necessitates we remove those to match previous behavior.
5426                     */
5427                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
5428                        Log.i(TAG, "removed obsolete native libraries for system package "
5429                                + path);
5430                    }
5431                    if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5432                        pkg.applicationInfo.cpuAbi = abiList[0];
5433                        pkgSetting.cpuAbiString = abiList[0];
5434                    } else {
5435                        setInternalAppAbi(pkg, pkgSetting);
5436                    }
5437                } else {
5438                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
5439                        /*
5440                        * Update native library dir if it starts with
5441                        * /data/data
5442                        */
5443                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
5444                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
5445                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5446                        }
5447
5448                        try {
5449                            int copyRet = copyNativeLibrariesForInternalApp(handle,
5450                                    nativeLibraryDir, abiList);
5451                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5452                                Slog.e(TAG, "Unable to copy native libraries");
5453                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5454                                return null;
5455                            }
5456
5457                            // We've successfully copied native libraries across, so we make a
5458                            // note of what ABI we're using
5459                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5460                                pkg.applicationInfo.cpuAbi = abiList[copyRet];
5461                            } else if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5462                                pkg.applicationInfo.cpuAbi = abiList[0];
5463                            } else {
5464                                pkg.applicationInfo.cpuAbi = null;
5465                            }
5466                        } catch (IOException e) {
5467                            Slog.e(TAG, "Unable to copy native libraries", e);
5468                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5469                            return null;
5470                        }
5471                    } else {
5472                        // We don't have to copy the shared libraries if we're in the ASEC container
5473                        // but we still need to scan the file to figure out what ABI the app needs.
5474                        //
5475                        // TODO: This duplicates work done in the default container service. It's possible
5476                        // to clean this up but we'll need to change the interface between this service
5477                        // and IMediaContainerService (but doing so will spread this logic out, rather
5478                        // than centralizing it).
5479                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5480                        if (abi >= 0) {
5481                            pkg.applicationInfo.cpuAbi = abiList[abi];
5482                        } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) {
5483                            // Note that (non upgraded) system apps will not have any native
5484                            // libraries bundled in their APK, but we're guaranteed not to be
5485                            // such an app at this point.
5486                            if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5487                                pkg.applicationInfo.cpuAbi = abiList[0];
5488                            } else {
5489                                pkg.applicationInfo.cpuAbi = null;
5490                            }
5491                        } else {
5492                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5493                            return null;
5494                        }
5495                    }
5496
5497                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5498                    final int[] userIds = sUserManager.getUserIds();
5499                    synchronized (mInstallLock) {
5500                        for (int userId : userIds) {
5501                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
5502                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
5503                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
5504                                        + ")");
5505                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5506                                return null;
5507                            }
5508                        }
5509                    }
5510                }
5511
5512                pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi;
5513            } catch (IOException ioe) {
5514                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5515            } finally {
5516                handle.close();
5517            }
5518        }
5519        pkg.mScanPath = path;
5520
5521        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5522            // We don't do this here during boot because we can do it all
5523            // at once after scanning all existing packages.
5524            //
5525            // We also do this *before* we perform dexopt on this package, so that
5526            // we can avoid redundant dexopts, and also to make sure we've got the
5527            // code and package path correct.
5528            if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5529                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) {
5530                mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE;
5531                return null;
5532            }
5533        }
5534
5535        if ((scanMode&SCAN_NO_DEX) == 0) {
5536            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5537                    == DEX_OPT_FAILED) {
5538                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5539                    removeDataDirsLI(pkg.packageName);
5540                }
5541
5542                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5543                return null;
5544            }
5545        }
5546
5547        if (mFactoryTest && pkg.requestedPermissions.contains(
5548                android.Manifest.permission.FACTORY_TEST)) {
5549            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5550        }
5551
5552        ArrayList<PackageParser.Package> clientLibPkgs = null;
5553
5554        // writer
5555        synchronized (mPackages) {
5556            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5557                // Only system apps can add new shared libraries.
5558                if (pkg.libraryNames != null) {
5559                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5560                        String name = pkg.libraryNames.get(i);
5561                        boolean allowed = false;
5562                        if (isUpdatedSystemApp(pkg)) {
5563                            // New library entries can only be added through the
5564                            // system image.  This is important to get rid of a lot
5565                            // of nasty edge cases: for example if we allowed a non-
5566                            // system update of the app to add a library, then uninstalling
5567                            // the update would make the library go away, and assumptions
5568                            // we made such as through app install filtering would now
5569                            // have allowed apps on the device which aren't compatible
5570                            // with it.  Better to just have the restriction here, be
5571                            // conservative, and create many fewer cases that can negatively
5572                            // impact the user experience.
5573                            final PackageSetting sysPs = mSettings
5574                                    .getDisabledSystemPkgLPr(pkg.packageName);
5575                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5576                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5577                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5578                                        allowed = true;
5579                                        allowed = true;
5580                                        break;
5581                                    }
5582                                }
5583                            }
5584                        } else {
5585                            allowed = true;
5586                        }
5587                        if (allowed) {
5588                            if (!mSharedLibraries.containsKey(name)) {
5589                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5590                            } else if (!name.equals(pkg.packageName)) {
5591                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5592                                        + name + " already exists; skipping");
5593                            }
5594                        } else {
5595                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5596                                    + name + " that is not declared on system image; skipping");
5597                        }
5598                    }
5599                    if ((scanMode&SCAN_BOOTING) == 0) {
5600                        // If we are not booting, we need to update any applications
5601                        // that are clients of our shared library.  If we are booting,
5602                        // this will all be done once the scan is complete.
5603                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5604                    }
5605                }
5606            }
5607        }
5608
5609        // We also need to dexopt any apps that are dependent on this library.  Note that
5610        // if these fail, we should abort the install since installing the library will
5611        // result in some apps being broken.
5612        if (clientLibPkgs != null) {
5613            if ((scanMode&SCAN_NO_DEX) == 0) {
5614                for (int i=0; i<clientLibPkgs.size(); i++) {
5615                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5616                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5617                            == DEX_OPT_FAILED) {
5618                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5619                            removeDataDirsLI(pkg.packageName);
5620                        }
5621
5622                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5623                        return null;
5624                    }
5625                }
5626            }
5627        }
5628
5629        // Request the ActivityManager to kill the process(only for existing packages)
5630        // so that we do not end up in a confused state while the user is still using the older
5631        // version of the application while the new one gets installed.
5632        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5633            // If the package lives in an asec, tell everyone that the container is going
5634            // away so they can clean up any references to its resources (which would prevent
5635            // vold from being able to unmount the asec)
5636            if (isForwardLocked(pkg) || isExternal(pkg)) {
5637                if (DEBUG_INSTALL) {
5638                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5639                }
5640                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5641                final ArrayList<String> pkgList = new ArrayList<String>(1);
5642                pkgList.add(pkg.applicationInfo.packageName);
5643                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5644            }
5645
5646            // Post the request that it be killed now that the going-away broadcast is en route
5647            killApplication(pkg.applicationInfo.packageName,
5648                        pkg.applicationInfo.uid, "update pkg");
5649        }
5650
5651        // Also need to kill any apps that are dependent on the library.
5652        if (clientLibPkgs != null) {
5653            for (int i=0; i<clientLibPkgs.size(); i++) {
5654                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5655                killApplication(clientPkg.applicationInfo.packageName,
5656                        clientPkg.applicationInfo.uid, "update lib");
5657            }
5658        }
5659
5660        // writer
5661        synchronized (mPackages) {
5662            // We don't expect installation to fail beyond this point,
5663            if ((scanMode&SCAN_MONITOR) != 0) {
5664                mAppDirs.put(pkg.mPath, pkg);
5665            }
5666            // Add the new setting to mSettings
5667            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5668            // Add the new setting to mPackages
5669            mPackages.put(pkg.applicationInfo.packageName, pkg);
5670            // Make sure we don't accidentally delete its data.
5671            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5672            while (iter.hasNext()) {
5673                PackageCleanItem item = iter.next();
5674                if (pkgName.equals(item.packageName)) {
5675                    iter.remove();
5676                }
5677            }
5678
5679            // Take care of first install / last update times.
5680            if (currentTime != 0) {
5681                if (pkgSetting.firstInstallTime == 0) {
5682                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5683                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5684                    pkgSetting.lastUpdateTime = currentTime;
5685                }
5686            } else if (pkgSetting.firstInstallTime == 0) {
5687                // We need *something*.  Take time time stamp of the file.
5688                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5689            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5690                if (scanFileTime != pkgSetting.timeStamp) {
5691                    // A package on the system image has changed; consider this
5692                    // to be an update.
5693                    pkgSetting.lastUpdateTime = scanFileTime;
5694                }
5695            }
5696
5697            // Add the package's KeySets to the global KeySetManager
5698            KeySetManager ksm = mSettings.mKeySetManager;
5699            try {
5700                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5701                if (pkg.mKeySetMapping != null) {
5702                    for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) {
5703                        if (entry.getValue() != null) {
5704                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5705                                entry.getValue(), entry.getKey());
5706                        }
5707                    }
5708                }
5709            } catch (NullPointerException e) {
5710                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5711            } catch (IllegalArgumentException e) {
5712                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5713            }
5714
5715            int N = pkg.providers.size();
5716            StringBuilder r = null;
5717            int i;
5718            for (i=0; i<N; i++) {
5719                PackageParser.Provider p = pkg.providers.get(i);
5720                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5721                        p.info.processName, pkg.applicationInfo.uid);
5722                mProviders.addProvider(p);
5723                p.syncable = p.info.isSyncable;
5724                if (p.info.authority != null) {
5725                    String names[] = p.info.authority.split(";");
5726                    p.info.authority = null;
5727                    for (int j = 0; j < names.length; j++) {
5728                        if (j == 1 && p.syncable) {
5729                            // We only want the first authority for a provider to possibly be
5730                            // syncable, so if we already added this provider using a different
5731                            // authority clear the syncable flag. We copy the provider before
5732                            // changing it because the mProviders object contains a reference
5733                            // to a provider that we don't want to change.
5734                            // Only do this for the second authority since the resulting provider
5735                            // object can be the same for all future authorities for this provider.
5736                            p = new PackageParser.Provider(p);
5737                            p.syncable = false;
5738                        }
5739                        if (!mProvidersByAuthority.containsKey(names[j])) {
5740                            mProvidersByAuthority.put(names[j], p);
5741                            if (p.info.authority == null) {
5742                                p.info.authority = names[j];
5743                            } else {
5744                                p.info.authority = p.info.authority + ";" + names[j];
5745                            }
5746                            if (DEBUG_PACKAGE_SCANNING) {
5747                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5748                                    Log.d(TAG, "Registered content provider: " + names[j]
5749                                            + ", className = " + p.info.name + ", isSyncable = "
5750                                            + p.info.isSyncable);
5751                            }
5752                        } else {
5753                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5754                            Slog.w(TAG, "Skipping provider name " + names[j] +
5755                                    " (in package " + pkg.applicationInfo.packageName +
5756                                    "): name already used by "
5757                                    + ((other != null && other.getComponentName() != null)
5758                                            ? other.getComponentName().getPackageName() : "?"));
5759                        }
5760                    }
5761                }
5762                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5763                    if (r == null) {
5764                        r = new StringBuilder(256);
5765                    } else {
5766                        r.append(' ');
5767                    }
5768                    r.append(p.info.name);
5769                }
5770            }
5771            if (r != null) {
5772                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5773            }
5774
5775            N = pkg.services.size();
5776            r = null;
5777            for (i=0; i<N; i++) {
5778                PackageParser.Service s = pkg.services.get(i);
5779                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5780                        s.info.processName, pkg.applicationInfo.uid);
5781                mServices.addService(s);
5782                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5783                    if (r == null) {
5784                        r = new StringBuilder(256);
5785                    } else {
5786                        r.append(' ');
5787                    }
5788                    r.append(s.info.name);
5789                }
5790            }
5791            if (r != null) {
5792                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5793            }
5794
5795            N = pkg.receivers.size();
5796            r = null;
5797            for (i=0; i<N; i++) {
5798                PackageParser.Activity a = pkg.receivers.get(i);
5799                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5800                        a.info.processName, pkg.applicationInfo.uid);
5801                mReceivers.addActivity(a, "receiver");
5802                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5803                    if (r == null) {
5804                        r = new StringBuilder(256);
5805                    } else {
5806                        r.append(' ');
5807                    }
5808                    r.append(a.info.name);
5809                }
5810            }
5811            if (r != null) {
5812                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5813            }
5814
5815            N = pkg.activities.size();
5816            r = null;
5817            for (i=0; i<N; i++) {
5818                PackageParser.Activity a = pkg.activities.get(i);
5819                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5820                        a.info.processName, pkg.applicationInfo.uid);
5821                mActivities.addActivity(a, "activity");
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(a.info.name);
5829                }
5830            }
5831            if (r != null) {
5832                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5833            }
5834
5835            N = pkg.permissionGroups.size();
5836            r = null;
5837            for (i=0; i<N; i++) {
5838                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5839                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5840                if (cur == null) {
5841                    mPermissionGroups.put(pg.info.name, pg);
5842                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5843                        if (r == null) {
5844                            r = new StringBuilder(256);
5845                        } else {
5846                            r.append(' ');
5847                        }
5848                        r.append(pg.info.name);
5849                    }
5850                } else {
5851                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5852                            + pg.info.packageName + " ignored: original from "
5853                            + cur.info.packageName);
5854                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5855                        if (r == null) {
5856                            r = new StringBuilder(256);
5857                        } else {
5858                            r.append(' ');
5859                        }
5860                        r.append("DUP:");
5861                        r.append(pg.info.name);
5862                    }
5863                }
5864            }
5865            if (r != null) {
5866                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5867            }
5868
5869            N = pkg.permissions.size();
5870            r = null;
5871            for (i=0; i<N; i++) {
5872                PackageParser.Permission p = pkg.permissions.get(i);
5873                HashMap<String, BasePermission> permissionMap =
5874                        p.tree ? mSettings.mPermissionTrees
5875                        : mSettings.mPermissions;
5876                p.group = mPermissionGroups.get(p.info.group);
5877                if (p.info.group == null || p.group != null) {
5878                    BasePermission bp = permissionMap.get(p.info.name);
5879                    if (bp == null) {
5880                        bp = new BasePermission(p.info.name, p.info.packageName,
5881                                BasePermission.TYPE_NORMAL);
5882                        permissionMap.put(p.info.name, bp);
5883                    }
5884                    if (bp.perm == null) {
5885                        if (bp.sourcePackage != null
5886                                && !bp.sourcePackage.equals(p.info.packageName)) {
5887                            // If this is a permission that was formerly defined by a non-system
5888                            // app, but is now defined by a system app (following an upgrade),
5889                            // discard the previous declaration and consider the system's to be
5890                            // canonical.
5891                            if (isSystemApp(p.owner)) {
5892                                String msg = "New decl " + p.owner + " of permission  "
5893                                        + p.info.name + " is system";
5894                                reportSettingsProblem(Log.WARN, msg);
5895                                bp.sourcePackage = null;
5896                            }
5897                        }
5898                        if (bp.sourcePackage == null
5899                                || bp.sourcePackage.equals(p.info.packageName)) {
5900                            BasePermission tree = findPermissionTreeLP(p.info.name);
5901                            if (tree == null
5902                                    || tree.sourcePackage.equals(p.info.packageName)) {
5903                                bp.packageSetting = pkgSetting;
5904                                bp.perm = p;
5905                                bp.uid = pkg.applicationInfo.uid;
5906                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5907                                    if (r == null) {
5908                                        r = new StringBuilder(256);
5909                                    } else {
5910                                        r.append(' ');
5911                                    }
5912                                    r.append(p.info.name);
5913                                }
5914                            } else {
5915                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5916                                        + p.info.packageName + " ignored: base tree "
5917                                        + tree.name + " is from package "
5918                                        + tree.sourcePackage);
5919                            }
5920                        } else {
5921                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5922                                    + p.info.packageName + " ignored: original from "
5923                                    + bp.sourcePackage);
5924                        }
5925                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5926                        if (r == null) {
5927                            r = new StringBuilder(256);
5928                        } else {
5929                            r.append(' ');
5930                        }
5931                        r.append("DUP:");
5932                        r.append(p.info.name);
5933                    }
5934                    if (bp.perm == p) {
5935                        bp.protectionLevel = p.info.protectionLevel;
5936                    }
5937                } else {
5938                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5939                            + p.info.packageName + " ignored: no group "
5940                            + p.group);
5941                }
5942            }
5943            if (r != null) {
5944                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5945            }
5946
5947            N = pkg.instrumentation.size();
5948            r = null;
5949            for (i=0; i<N; i++) {
5950                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5951                a.info.packageName = pkg.applicationInfo.packageName;
5952                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5953                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5954                a.info.dataDir = pkg.applicationInfo.dataDir;
5955                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5956                mInstrumentation.put(a.getComponentName(), a);
5957                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5958                    if (r == null) {
5959                        r = new StringBuilder(256);
5960                    } else {
5961                        r.append(' ');
5962                    }
5963                    r.append(a.info.name);
5964                }
5965            }
5966            if (r != null) {
5967                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5968            }
5969
5970            if (pkg.protectedBroadcasts != null) {
5971                N = pkg.protectedBroadcasts.size();
5972                for (i=0; i<N; i++) {
5973                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5974                }
5975            }
5976
5977            pkgSetting.setTimeStamp(scanFileTime);
5978
5979            // Create idmap files for pairs of (packages, overlay packages).
5980            // Note: "android", ie framework-res.apk, is handled by native layers.
5981            if (pkg.mOverlayTarget != null) {
5982                // This is an overlay package.
5983                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5984                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5985                        mOverlays.put(pkg.mOverlayTarget,
5986                                new HashMap<String, PackageParser.Package>());
5987                    }
5988                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5989                    map.put(pkg.packageName, pkg);
5990                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5991                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5992                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5993                        return null;
5994                    }
5995                }
5996            } else if (mOverlays.containsKey(pkg.packageName) &&
5997                    !pkg.packageName.equals("android")) {
5998                // This is a regular package, with one or more known overlay packages.
5999                createIdmapsForPackageLI(pkg);
6000            }
6001        }
6002
6003        return pkg;
6004    }
6005
6006    /**
6007     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6008     * i.e, so that all packages can be run inside a single process if required.
6009     *
6010     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6011     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6012     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6013     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6014     * updating a package that belongs to a shared user.
6015     */
6016    private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6017            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6018        String requiredInstructionSet = null;
6019        if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) {
6020            requiredInstructionSet = VMRuntime.getInstructionSet(
6021                     scannedPackage.applicationInfo.cpuAbi);
6022        }
6023
6024        PackageSetting requirer = null;
6025        for (PackageSetting ps : packagesForUser) {
6026            // If packagesForUser contains scannedPackage, we skip it. This will happen
6027            // when scannedPackage is an update of an existing package. Without this check,
6028            // we will never be able to change the ABI of any package belonging to a shared
6029            // user, even if it's compatible with other packages.
6030            if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) {
6031                if (ps.cpuAbiString == null) {
6032                    continue;
6033                }
6034
6035                final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
6036                if (requiredInstructionSet != null) {
6037                    if (!instructionSet.equals(requiredInstructionSet)) {
6038                        // We have a mismatch between instruction sets (say arm vs arm64).
6039                        // bail out.
6040                        String errorMessage = "Instruction set mismatch, "
6041                                + ((requirer == null) ? "[caller]" : requirer)
6042                                + " requires " + requiredInstructionSet + " whereas " + ps
6043                                + " requires " + instructionSet;
6044                        Slog.e(TAG, errorMessage);
6045
6046                        reportSettingsProblem(Log.WARN, errorMessage);
6047                        // Give up, don't bother making any other changes to the package settings.
6048                        return false;
6049                    }
6050                } else {
6051                    requiredInstructionSet = instructionSet;
6052                    requirer = ps;
6053                }
6054            }
6055        }
6056
6057        if (requiredInstructionSet != null) {
6058            String adjustedAbi;
6059            if (requirer != null) {
6060                // requirer != null implies that either scannedPackage was null or that scannedPackage
6061                // did not require an ABI, in which case we have to adjust scannedPackage to match
6062                // the ABI of the set (which is the same as requirer's ABI)
6063                adjustedAbi = requirer.cpuAbiString;
6064                if (scannedPackage != null) {
6065                    scannedPackage.applicationInfo.cpuAbi = adjustedAbi;
6066                }
6067            } else {
6068                // requirer == null implies that we're updating all ABIs in the set to
6069                // match scannedPackage.
6070                adjustedAbi =  scannedPackage.applicationInfo.cpuAbi;
6071            }
6072
6073            for (PackageSetting ps : packagesForUser) {
6074                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6075                    if (ps.cpuAbiString != null) {
6076                        continue;
6077                    }
6078
6079                    ps.cpuAbiString = adjustedAbi;
6080                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6081                        ps.pkg.applicationInfo.cpuAbi = adjustedAbi;
6082                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6083
6084                        if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) {
6085                            ps.cpuAbiString = null;
6086                            ps.pkg.applicationInfo.cpuAbi = null;
6087                            return false;
6088                        } else {
6089                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
6090                        }
6091                    }
6092                }
6093            }
6094        }
6095
6096        return true;
6097    }
6098
6099    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6100        synchronized (mPackages) {
6101            mResolverReplaced = true;
6102            // Set up information for custom user intent resolution activity.
6103            mResolveActivity.applicationInfo = pkg.applicationInfo;
6104            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6105            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6106            mResolveActivity.processName = null;
6107            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6108            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6109                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6110            mResolveActivity.theme = 0;
6111            mResolveActivity.exported = true;
6112            mResolveActivity.enabled = true;
6113            mResolveInfo.activityInfo = mResolveActivity;
6114            mResolveInfo.priority = 0;
6115            mResolveInfo.preferredOrder = 0;
6116            mResolveInfo.match = 0;
6117            mResolveComponentName = mCustomResolverComponentName;
6118            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6119                    mResolveComponentName);
6120        }
6121    }
6122
6123    private String calculateApkRoot(final String codePathString) {
6124        final File codePath = new File(codePathString);
6125        final File codeRoot;
6126        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6127            codeRoot = Environment.getRootDirectory();
6128        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6129            codeRoot = Environment.getOemDirectory();
6130        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6131            codeRoot = Environment.getVendorDirectory();
6132        } else {
6133            // Unrecognized code path; take its top real segment as the apk root:
6134            // e.g. /something/app/blah.apk => /something
6135            try {
6136                File f = codePath.getCanonicalFile();
6137                File parent = f.getParentFile();    // non-null because codePath is a file
6138                File tmp;
6139                while ((tmp = parent.getParentFile()) != null) {
6140                    f = parent;
6141                    parent = tmp;
6142                }
6143                codeRoot = f;
6144                Slog.w(TAG, "Unrecognized code path "
6145                        + codePath + " - using " + codeRoot);
6146            } catch (IOException e) {
6147                // Can't canonicalize the lib path -- shenanigans?
6148                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6149                return Environment.getRootDirectory().getPath();
6150            }
6151        }
6152        return codeRoot.getPath();
6153    }
6154
6155    // This is the initial scan-time determination of how to handle a given
6156    // package for purposes of native library location.
6157    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
6158            PackageSetting pkgSetting) {
6159        // "bundled" here means system-installed with no overriding update
6160        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
6161        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6162        final File libDir;
6163        if (bundledApk) {
6164            // If "/system/lib64/apkname" exists, assume that is the per-package
6165            // native library directory to use; otherwise use "/system/lib/apkname".
6166            String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6167            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
6168            File packLib64 = new File(lib64, apkName);
6169            libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
6170        } else {
6171            libDir = mAppLibInstallDir;
6172        }
6173        final String nativeLibraryPath = (new File(libDir, apkName)).getPath();
6174        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
6175        // pkgSetting might be null during rescan following uninstall of updates
6176        // to a bundled app, so accommodate that possibility.  The settings in
6177        // that case will be established later from the parsed package.
6178        if (pkgSetting != null) {
6179            pkgSetting.nativeLibraryPathString = nativeLibraryPath;
6180        }
6181    }
6182
6183    // Deduces the required ABI of an upgraded system app.
6184    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
6185        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6186        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6187
6188        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
6189        // or similar.
6190        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
6191        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
6192
6193        // Assume that the bundled native libraries always correspond to the
6194        // most preferred 32 or 64 bit ABI.
6195        if (lib64.exists()) {
6196            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6197            pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
6198        } else if (lib.exists()) {
6199            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6200            pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
6201        } else {
6202            // This is the case where the app has no native code.
6203            pkg.applicationInfo.cpuAbi = null;
6204            pkgSetting.cpuAbiString = null;
6205        }
6206    }
6207
6208    private static int copyNativeLibrariesForInternalApp(ApkHandle handle,
6209            final File nativeLibraryDir, String[] abiList) throws IOException {
6210        if (!nativeLibraryDir.isDirectory()) {
6211            nativeLibraryDir.delete();
6212
6213            if (!nativeLibraryDir.mkdir()) {
6214                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
6215            }
6216
6217            try {
6218                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6219            } catch (ErrnoException e) {
6220                throw new IOException("Cannot chmod native library directory "
6221                        + nativeLibraryDir.getPath(), e);
6222            }
6223        } else if (!SELinux.restorecon(nativeLibraryDir)) {
6224            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
6225        }
6226
6227        /*
6228         * If this is an internal application or our nativeLibraryPath points to
6229         * the app-lib directory, unpack the libraries if necessary.
6230         */
6231        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6232        if (abi >= 0) {
6233            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
6234                    nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
6235            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6236                return copyRet;
6237            }
6238        }
6239
6240        return abi;
6241    }
6242
6243    private void killApplication(String pkgName, int appId, String reason) {
6244        // Request the ActivityManager to kill the process(only for existing packages)
6245        // so that we do not end up in a confused state while the user is still using the older
6246        // version of the application while the new one gets installed.
6247        IActivityManager am = ActivityManagerNative.getDefault();
6248        if (am != null) {
6249            try {
6250                am.killApplicationWithAppId(pkgName, appId, reason);
6251            } catch (RemoteException e) {
6252            }
6253        }
6254    }
6255
6256    void removePackageLI(PackageSetting ps, boolean chatty) {
6257        if (DEBUG_INSTALL) {
6258            if (chatty)
6259                Log.d(TAG, "Removing package " + ps.name);
6260        }
6261
6262        // writer
6263        synchronized (mPackages) {
6264            mPackages.remove(ps.name);
6265            if (ps.codePathString != null) {
6266                mAppDirs.remove(ps.codePathString);
6267            }
6268
6269            final PackageParser.Package pkg = ps.pkg;
6270            if (pkg != null) {
6271                cleanPackageDataStructuresLILPw(pkg, chatty);
6272            }
6273        }
6274    }
6275
6276    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6277        if (DEBUG_INSTALL) {
6278            if (chatty)
6279                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6280        }
6281
6282        // writer
6283        synchronized (mPackages) {
6284            mPackages.remove(pkg.applicationInfo.packageName);
6285            if (pkg.mPath != null) {
6286                mAppDirs.remove(pkg.mPath);
6287            }
6288            cleanPackageDataStructuresLILPw(pkg, chatty);
6289        }
6290    }
6291
6292    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6293        int N = pkg.providers.size();
6294        StringBuilder r = null;
6295        int i;
6296        for (i=0; i<N; i++) {
6297            PackageParser.Provider p = pkg.providers.get(i);
6298            mProviders.removeProvider(p);
6299            if (p.info.authority == null) {
6300
6301                /* There was another ContentProvider with this authority when
6302                 * this app was installed so this authority is null,
6303                 * Ignore it as we don't have to unregister the provider.
6304                 */
6305                continue;
6306            }
6307            String names[] = p.info.authority.split(";");
6308            for (int j = 0; j < names.length; j++) {
6309                if (mProvidersByAuthority.get(names[j]) == p) {
6310                    mProvidersByAuthority.remove(names[j]);
6311                    if (DEBUG_REMOVE) {
6312                        if (chatty)
6313                            Log.d(TAG, "Unregistered content provider: " + names[j]
6314                                    + ", className = " + p.info.name + ", isSyncable = "
6315                                    + p.info.isSyncable);
6316                    }
6317                }
6318            }
6319            if (DEBUG_REMOVE && chatty) {
6320                if (r == null) {
6321                    r = new StringBuilder(256);
6322                } else {
6323                    r.append(' ');
6324                }
6325                r.append(p.info.name);
6326            }
6327        }
6328        if (r != null) {
6329            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6330        }
6331
6332        N = pkg.services.size();
6333        r = null;
6334        for (i=0; i<N; i++) {
6335            PackageParser.Service s = pkg.services.get(i);
6336            mServices.removeService(s);
6337            if (chatty) {
6338                if (r == null) {
6339                    r = new StringBuilder(256);
6340                } else {
6341                    r.append(' ');
6342                }
6343                r.append(s.info.name);
6344            }
6345        }
6346        if (r != null) {
6347            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6348        }
6349
6350        N = pkg.receivers.size();
6351        r = null;
6352        for (i=0; i<N; i++) {
6353            PackageParser.Activity a = pkg.receivers.get(i);
6354            mReceivers.removeActivity(a, "receiver");
6355            if (DEBUG_REMOVE && chatty) {
6356                if (r == null) {
6357                    r = new StringBuilder(256);
6358                } else {
6359                    r.append(' ');
6360                }
6361                r.append(a.info.name);
6362            }
6363        }
6364        if (r != null) {
6365            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6366        }
6367
6368        N = pkg.activities.size();
6369        r = null;
6370        for (i=0; i<N; i++) {
6371            PackageParser.Activity a = pkg.activities.get(i);
6372            mActivities.removeActivity(a, "activity");
6373            if (DEBUG_REMOVE && chatty) {
6374                if (r == null) {
6375                    r = new StringBuilder(256);
6376                } else {
6377                    r.append(' ');
6378                }
6379                r.append(a.info.name);
6380            }
6381        }
6382        if (r != null) {
6383            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6384        }
6385
6386        N = pkg.permissions.size();
6387        r = null;
6388        for (i=0; i<N; i++) {
6389            PackageParser.Permission p = pkg.permissions.get(i);
6390            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6391            if (bp == null) {
6392                bp = mSettings.mPermissionTrees.get(p.info.name);
6393            }
6394            if (bp != null && bp.perm == p) {
6395                bp.perm = null;
6396                if (DEBUG_REMOVE && chatty) {
6397                    if (r == null) {
6398                        r = new StringBuilder(256);
6399                    } else {
6400                        r.append(' ');
6401                    }
6402                    r.append(p.info.name);
6403                }
6404            }
6405        }
6406        if (r != null) {
6407            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6408        }
6409
6410        N = pkg.instrumentation.size();
6411        r = null;
6412        for (i=0; i<N; i++) {
6413            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6414            mInstrumentation.remove(a.getComponentName());
6415            if (DEBUG_REMOVE && chatty) {
6416                if (r == null) {
6417                    r = new StringBuilder(256);
6418                } else {
6419                    r.append(' ');
6420                }
6421                r.append(a.info.name);
6422            }
6423        }
6424        if (r != null) {
6425            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6426        }
6427
6428        r = null;
6429        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6430            // Only system apps can hold shared libraries.
6431            if (pkg.libraryNames != null) {
6432                for (i=0; i<pkg.libraryNames.size(); i++) {
6433                    String name = pkg.libraryNames.get(i);
6434                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6435                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6436                        mSharedLibraries.remove(name);
6437                        if (DEBUG_REMOVE && chatty) {
6438                            if (r == null) {
6439                                r = new StringBuilder(256);
6440                            } else {
6441                                r.append(' ');
6442                            }
6443                            r.append(name);
6444                        }
6445                    }
6446                }
6447            }
6448        }
6449        if (r != null) {
6450            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6451        }
6452    }
6453
6454    private static final boolean isPackageFilename(String name) {
6455        return name != null && name.endsWith(".apk");
6456    }
6457
6458    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6459        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6460            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6461                return true;
6462            }
6463        }
6464        return false;
6465    }
6466
6467    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6468    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6469    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6470
6471    private void updatePermissionsLPw(String changingPkg,
6472            PackageParser.Package pkgInfo, int flags) {
6473        // Make sure there are no dangling permission trees.
6474        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6475        while (it.hasNext()) {
6476            final BasePermission bp = it.next();
6477            if (bp.packageSetting == null) {
6478                // We may not yet have parsed the package, so just see if
6479                // we still know about its settings.
6480                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6481            }
6482            if (bp.packageSetting == null) {
6483                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6484                        + " from package " + bp.sourcePackage);
6485                it.remove();
6486            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6487                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6488                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6489                            + " from package " + bp.sourcePackage);
6490                    flags |= UPDATE_PERMISSIONS_ALL;
6491                    it.remove();
6492                }
6493            }
6494        }
6495
6496        // Make sure all dynamic permissions have been assigned to a package,
6497        // and make sure there are no dangling permissions.
6498        it = mSettings.mPermissions.values().iterator();
6499        while (it.hasNext()) {
6500            final BasePermission bp = it.next();
6501            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6502                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6503                        + bp.name + " pkg=" + bp.sourcePackage
6504                        + " info=" + bp.pendingInfo);
6505                if (bp.packageSetting == null && bp.pendingInfo != null) {
6506                    final BasePermission tree = findPermissionTreeLP(bp.name);
6507                    if (tree != null && tree.perm != null) {
6508                        bp.packageSetting = tree.packageSetting;
6509                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6510                                new PermissionInfo(bp.pendingInfo));
6511                        bp.perm.info.packageName = tree.perm.info.packageName;
6512                        bp.perm.info.name = bp.name;
6513                        bp.uid = tree.uid;
6514                    }
6515                }
6516            }
6517            if (bp.packageSetting == null) {
6518                // We may not yet have parsed the package, so just see if
6519                // we still know about its settings.
6520                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6521            }
6522            if (bp.packageSetting == null) {
6523                Slog.w(TAG, "Removing dangling permission: " + bp.name
6524                        + " from package " + bp.sourcePackage);
6525                it.remove();
6526            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6527                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6528                    Slog.i(TAG, "Removing old permission: " + bp.name
6529                            + " from package " + bp.sourcePackage);
6530                    flags |= UPDATE_PERMISSIONS_ALL;
6531                    it.remove();
6532                }
6533            }
6534        }
6535
6536        // Now update the permissions for all packages, in particular
6537        // replace the granted permissions of the system packages.
6538        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6539            for (PackageParser.Package pkg : mPackages.values()) {
6540                if (pkg != pkgInfo) {
6541                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6542                }
6543            }
6544        }
6545
6546        if (pkgInfo != null) {
6547            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6548        }
6549    }
6550
6551    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6552        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6553        if (ps == null) {
6554            return;
6555        }
6556        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6557        HashSet<String> origPermissions = gp.grantedPermissions;
6558        boolean changedPermission = false;
6559
6560        if (replace) {
6561            ps.permissionsFixed = false;
6562            if (gp == ps) {
6563                origPermissions = new HashSet<String>(gp.grantedPermissions);
6564                gp.grantedPermissions.clear();
6565                gp.gids = mGlobalGids;
6566            }
6567        }
6568
6569        if (gp.gids == null) {
6570            gp.gids = mGlobalGids;
6571        }
6572
6573        final int N = pkg.requestedPermissions.size();
6574        for (int i=0; i<N; i++) {
6575            final String name = pkg.requestedPermissions.get(i);
6576            final boolean required = pkg.requestedPermissionsRequired.get(i);
6577            final BasePermission bp = mSettings.mPermissions.get(name);
6578            if (DEBUG_INSTALL) {
6579                if (gp != ps) {
6580                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6581                }
6582            }
6583
6584            if (bp == null || bp.packageSetting == null) {
6585                Slog.w(TAG, "Unknown permission " + name
6586                        + " in package " + pkg.packageName);
6587                continue;
6588            }
6589
6590            final String perm = bp.name;
6591            boolean allowed;
6592            boolean allowedSig = false;
6593            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6594            if (level == PermissionInfo.PROTECTION_NORMAL
6595                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6596                // We grant a normal or dangerous permission if any of the following
6597                // are true:
6598                // 1) The permission is required
6599                // 2) The permission is optional, but was granted in the past
6600                // 3) The permission is optional, but was requested by an
6601                //    app in /system (not /data)
6602                //
6603                // Otherwise, reject the permission.
6604                allowed = (required || origPermissions.contains(perm)
6605                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6606            } else if (bp.packageSetting == null) {
6607                // This permission is invalid; skip it.
6608                allowed = false;
6609            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6610                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6611                if (allowed) {
6612                    allowedSig = true;
6613                }
6614            } else {
6615                allowed = false;
6616            }
6617            if (DEBUG_INSTALL) {
6618                if (gp != ps) {
6619                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6620                }
6621            }
6622            if (allowed) {
6623                if (!isSystemApp(ps) && ps.permissionsFixed) {
6624                    // If this is an existing, non-system package, then
6625                    // we can't add any new permissions to it.
6626                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6627                        // Except...  if this is a permission that was added
6628                        // to the platform (note: need to only do this when
6629                        // updating the platform).
6630                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6631                    }
6632                }
6633                if (allowed) {
6634                    if (!gp.grantedPermissions.contains(perm)) {
6635                        changedPermission = true;
6636                        gp.grantedPermissions.add(perm);
6637                        gp.gids = appendInts(gp.gids, bp.gids);
6638                    } else if (!ps.haveGids) {
6639                        gp.gids = appendInts(gp.gids, bp.gids);
6640                    }
6641                } else {
6642                    Slog.w(TAG, "Not granting permission " + perm
6643                            + " to package " + pkg.packageName
6644                            + " because it was previously installed without");
6645                }
6646            } else {
6647                if (gp.grantedPermissions.remove(perm)) {
6648                    changedPermission = true;
6649                    gp.gids = removeInts(gp.gids, bp.gids);
6650                    Slog.i(TAG, "Un-granting permission " + perm
6651                            + " from package " + pkg.packageName
6652                            + " (protectionLevel=" + bp.protectionLevel
6653                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6654                            + ")");
6655                } else {
6656                    Slog.w(TAG, "Not granting permission " + perm
6657                            + " to package " + pkg.packageName
6658                            + " (protectionLevel=" + bp.protectionLevel
6659                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6660                            + ")");
6661                }
6662            }
6663        }
6664
6665        if ((changedPermission || replace) && !ps.permissionsFixed &&
6666                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6667            // This is the first that we have heard about this package, so the
6668            // permissions we have now selected are fixed until explicitly
6669            // changed.
6670            ps.permissionsFixed = true;
6671        }
6672        ps.haveGids = true;
6673    }
6674
6675    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6676        boolean allowed = false;
6677        final int NP = PackageParser.NEW_PERMISSIONS.length;
6678        for (int ip=0; ip<NP; ip++) {
6679            final PackageParser.NewPermissionInfo npi
6680                    = PackageParser.NEW_PERMISSIONS[ip];
6681            if (npi.name.equals(perm)
6682                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6683                allowed = true;
6684                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6685                        + pkg.packageName);
6686                break;
6687            }
6688        }
6689        return allowed;
6690    }
6691
6692    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6693                                          BasePermission bp, HashSet<String> origPermissions) {
6694        boolean allowed;
6695        allowed = (compareSignatures(
6696                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6697                        == PackageManager.SIGNATURE_MATCH)
6698                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6699                        == PackageManager.SIGNATURE_MATCH);
6700        if (!allowed && (bp.protectionLevel
6701                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6702            if (isSystemApp(pkg)) {
6703                // For updated system applications, a system permission
6704                // is granted only if it had been defined by the original application.
6705                if (isUpdatedSystemApp(pkg)) {
6706                    final PackageSetting sysPs = mSettings
6707                            .getDisabledSystemPkgLPr(pkg.packageName);
6708                    final GrantedPermissions origGp = sysPs.sharedUser != null
6709                            ? sysPs.sharedUser : sysPs;
6710
6711                    if (origGp.grantedPermissions.contains(perm)) {
6712                        // If the original was granted this permission, we take
6713                        // that grant decision as read and propagate it to the
6714                        // update.
6715                        allowed = true;
6716                    } else {
6717                        // The system apk may have been updated with an older
6718                        // version of the one on the data partition, but which
6719                        // granted a new system permission that it didn't have
6720                        // before.  In this case we do want to allow the app to
6721                        // now get the new permission if the ancestral apk is
6722                        // privileged to get it.
6723                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6724                            for (int j=0;
6725                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6726                                if (perm.equals(
6727                                        sysPs.pkg.requestedPermissions.get(j))) {
6728                                    allowed = true;
6729                                    break;
6730                                }
6731                            }
6732                        }
6733                    }
6734                } else {
6735                    allowed = isPrivilegedApp(pkg);
6736                }
6737            }
6738        }
6739        if (!allowed && (bp.protectionLevel
6740                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6741            // For development permissions, a development permission
6742            // is granted only if it was already granted.
6743            allowed = origPermissions.contains(perm);
6744        }
6745        return allowed;
6746    }
6747
6748    final class ActivityIntentResolver
6749            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6750        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6751                boolean defaultOnly, int userId) {
6752            if (!sUserManager.exists(userId)) return null;
6753            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6754            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6755        }
6756
6757        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6758                int userId) {
6759            if (!sUserManager.exists(userId)) return null;
6760            mFlags = flags;
6761            return super.queryIntent(intent, resolvedType,
6762                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6763        }
6764
6765        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6766                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6767            if (!sUserManager.exists(userId)) return null;
6768            if (packageActivities == null) {
6769                return null;
6770            }
6771            mFlags = flags;
6772            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6773            final int N = packageActivities.size();
6774            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6775                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6776
6777            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6778            for (int i = 0; i < N; ++i) {
6779                intentFilters = packageActivities.get(i).intents;
6780                if (intentFilters != null && intentFilters.size() > 0) {
6781                    PackageParser.ActivityIntentInfo[] array =
6782                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6783                    intentFilters.toArray(array);
6784                    listCut.add(array);
6785                }
6786            }
6787            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6788        }
6789
6790        public final void addActivity(PackageParser.Activity a, String type) {
6791            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6792            mActivities.put(a.getComponentName(), a);
6793            if (DEBUG_SHOW_INFO)
6794                Log.v(
6795                TAG, "  " + type + " " +
6796                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6797            if (DEBUG_SHOW_INFO)
6798                Log.v(TAG, "    Class=" + a.info.name);
6799            final int NI = a.intents.size();
6800            for (int j=0; j<NI; j++) {
6801                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6802                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6803                    intent.setPriority(0);
6804                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6805                            + a.className + " with priority > 0, forcing to 0");
6806                }
6807                if (DEBUG_SHOW_INFO) {
6808                    Log.v(TAG, "    IntentFilter:");
6809                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6810                }
6811                if (!intent.debugCheck()) {
6812                    Log.w(TAG, "==> For Activity " + a.info.name);
6813                }
6814                addFilter(intent);
6815            }
6816        }
6817
6818        public final void removeActivity(PackageParser.Activity a, String type) {
6819            mActivities.remove(a.getComponentName());
6820            if (DEBUG_SHOW_INFO) {
6821                Log.v(TAG, "  " + type + " "
6822                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6823                                : a.info.name) + ":");
6824                Log.v(TAG, "    Class=" + a.info.name);
6825            }
6826            final int NI = a.intents.size();
6827            for (int j=0; j<NI; j++) {
6828                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6829                if (DEBUG_SHOW_INFO) {
6830                    Log.v(TAG, "    IntentFilter:");
6831                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6832                }
6833                removeFilter(intent);
6834            }
6835        }
6836
6837        @Override
6838        protected boolean allowFilterResult(
6839                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6840            ActivityInfo filterAi = filter.activity.info;
6841            for (int i=dest.size()-1; i>=0; i--) {
6842                ActivityInfo destAi = dest.get(i).activityInfo;
6843                if (destAi.name == filterAi.name
6844                        && destAi.packageName == filterAi.packageName) {
6845                    return false;
6846                }
6847            }
6848            return true;
6849        }
6850
6851        @Override
6852        protected ActivityIntentInfo[] newArray(int size) {
6853            return new ActivityIntentInfo[size];
6854        }
6855
6856        @Override
6857        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6858            if (!sUserManager.exists(userId)) return true;
6859            PackageParser.Package p = filter.activity.owner;
6860            if (p != null) {
6861                PackageSetting ps = (PackageSetting)p.mExtras;
6862                if (ps != null) {
6863                    // System apps are never considered stopped for purposes of
6864                    // filtering, because there may be no way for the user to
6865                    // actually re-launch them.
6866                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6867                            && ps.getStopped(userId);
6868                }
6869            }
6870            return false;
6871        }
6872
6873        @Override
6874        protected boolean isPackageForFilter(String packageName,
6875                PackageParser.ActivityIntentInfo info) {
6876            return packageName.equals(info.activity.owner.packageName);
6877        }
6878
6879        @Override
6880        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6881                int match, int userId) {
6882            if (!sUserManager.exists(userId)) return null;
6883            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6884                return null;
6885            }
6886            final PackageParser.Activity activity = info.activity;
6887            if (mSafeMode && (activity.info.applicationInfo.flags
6888                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6889                return null;
6890            }
6891            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6892            if (ps == null) {
6893                return null;
6894            }
6895            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6896                    ps.readUserState(userId), userId);
6897            if (ai == null) {
6898                return null;
6899            }
6900            final ResolveInfo res = new ResolveInfo();
6901            res.activityInfo = ai;
6902            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6903                res.filter = info;
6904            }
6905            res.priority = info.getPriority();
6906            res.preferredOrder = activity.owner.mPreferredOrder;
6907            //System.out.println("Result: " + res.activityInfo.className +
6908            //                   " = " + res.priority);
6909            res.match = match;
6910            res.isDefault = info.hasDefault;
6911            res.labelRes = info.labelRes;
6912            res.nonLocalizedLabel = info.nonLocalizedLabel;
6913            res.icon = info.icon;
6914            res.system = isSystemApp(res.activityInfo.applicationInfo);
6915            return res;
6916        }
6917
6918        @Override
6919        protected void sortResults(List<ResolveInfo> results) {
6920            Collections.sort(results, mResolvePrioritySorter);
6921        }
6922
6923        @Override
6924        protected void dumpFilter(PrintWriter out, String prefix,
6925                PackageParser.ActivityIntentInfo filter) {
6926            out.print(prefix); out.print(
6927                    Integer.toHexString(System.identityHashCode(filter.activity)));
6928                    out.print(' ');
6929                    filter.activity.printComponentShortName(out);
6930                    out.print(" filter ");
6931                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6932        }
6933
6934//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6935//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6936//            final List<ResolveInfo> retList = Lists.newArrayList();
6937//            while (i.hasNext()) {
6938//                final ResolveInfo resolveInfo = i.next();
6939//                if (isEnabledLP(resolveInfo.activityInfo)) {
6940//                    retList.add(resolveInfo);
6941//                }
6942//            }
6943//            return retList;
6944//        }
6945
6946        // Keys are String (activity class name), values are Activity.
6947        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6948                = new HashMap<ComponentName, PackageParser.Activity>();
6949        private int mFlags;
6950    }
6951
6952    private final class ServiceIntentResolver
6953            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6954        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6955                boolean defaultOnly, int userId) {
6956            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6957            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6958        }
6959
6960        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6961                int userId) {
6962            if (!sUserManager.exists(userId)) return null;
6963            mFlags = flags;
6964            return super.queryIntent(intent, resolvedType,
6965                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6966        }
6967
6968        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6969                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6970            if (!sUserManager.exists(userId)) return null;
6971            if (packageServices == null) {
6972                return null;
6973            }
6974            mFlags = flags;
6975            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6976            final int N = packageServices.size();
6977            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6978                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6979
6980            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6981            for (int i = 0; i < N; ++i) {
6982                intentFilters = packageServices.get(i).intents;
6983                if (intentFilters != null && intentFilters.size() > 0) {
6984                    PackageParser.ServiceIntentInfo[] array =
6985                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6986                    intentFilters.toArray(array);
6987                    listCut.add(array);
6988                }
6989            }
6990            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6991        }
6992
6993        public final void addService(PackageParser.Service s) {
6994            mServices.put(s.getComponentName(), s);
6995            if (DEBUG_SHOW_INFO) {
6996                Log.v(TAG, "  "
6997                        + (s.info.nonLocalizedLabel != null
6998                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6999                Log.v(TAG, "    Class=" + s.info.name);
7000            }
7001            final int NI = s.intents.size();
7002            int j;
7003            for (j=0; j<NI; j++) {
7004                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7005                if (DEBUG_SHOW_INFO) {
7006                    Log.v(TAG, "    IntentFilter:");
7007                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7008                }
7009                if (!intent.debugCheck()) {
7010                    Log.w(TAG, "==> For Service " + s.info.name);
7011                }
7012                addFilter(intent);
7013            }
7014        }
7015
7016        public final void removeService(PackageParser.Service s) {
7017            mServices.remove(s.getComponentName());
7018            if (DEBUG_SHOW_INFO) {
7019                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7020                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7021                Log.v(TAG, "    Class=" + s.info.name);
7022            }
7023            final int NI = s.intents.size();
7024            int j;
7025            for (j=0; j<NI; j++) {
7026                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7027                if (DEBUG_SHOW_INFO) {
7028                    Log.v(TAG, "    IntentFilter:");
7029                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7030                }
7031                removeFilter(intent);
7032            }
7033        }
7034
7035        @Override
7036        protected boolean allowFilterResult(
7037                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7038            ServiceInfo filterSi = filter.service.info;
7039            for (int i=dest.size()-1; i>=0; i--) {
7040                ServiceInfo destAi = dest.get(i).serviceInfo;
7041                if (destAi.name == filterSi.name
7042                        && destAi.packageName == filterSi.packageName) {
7043                    return false;
7044                }
7045            }
7046            return true;
7047        }
7048
7049        @Override
7050        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7051            return new PackageParser.ServiceIntentInfo[size];
7052        }
7053
7054        @Override
7055        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7056            if (!sUserManager.exists(userId)) return true;
7057            PackageParser.Package p = filter.service.owner;
7058            if (p != null) {
7059                PackageSetting ps = (PackageSetting)p.mExtras;
7060                if (ps != null) {
7061                    // System apps are never considered stopped for purposes of
7062                    // filtering, because there may be no way for the user to
7063                    // actually re-launch them.
7064                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7065                            && ps.getStopped(userId);
7066                }
7067            }
7068            return false;
7069        }
7070
7071        @Override
7072        protected boolean isPackageForFilter(String packageName,
7073                PackageParser.ServiceIntentInfo info) {
7074            return packageName.equals(info.service.owner.packageName);
7075        }
7076
7077        @Override
7078        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7079                int match, int userId) {
7080            if (!sUserManager.exists(userId)) return null;
7081            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7082            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7083                return null;
7084            }
7085            final PackageParser.Service service = info.service;
7086            if (mSafeMode && (service.info.applicationInfo.flags
7087                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7088                return null;
7089            }
7090            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7091            if (ps == null) {
7092                return null;
7093            }
7094            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7095                    ps.readUserState(userId), userId);
7096            if (si == null) {
7097                return null;
7098            }
7099            final ResolveInfo res = new ResolveInfo();
7100            res.serviceInfo = si;
7101            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7102                res.filter = filter;
7103            }
7104            res.priority = info.getPriority();
7105            res.preferredOrder = service.owner.mPreferredOrder;
7106            //System.out.println("Result: " + res.activityInfo.className +
7107            //                   " = " + res.priority);
7108            res.match = match;
7109            res.isDefault = info.hasDefault;
7110            res.labelRes = info.labelRes;
7111            res.nonLocalizedLabel = info.nonLocalizedLabel;
7112            res.icon = info.icon;
7113            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7114            return res;
7115        }
7116
7117        @Override
7118        protected void sortResults(List<ResolveInfo> results) {
7119            Collections.sort(results, mResolvePrioritySorter);
7120        }
7121
7122        @Override
7123        protected void dumpFilter(PrintWriter out, String prefix,
7124                PackageParser.ServiceIntentInfo filter) {
7125            out.print(prefix); out.print(
7126                    Integer.toHexString(System.identityHashCode(filter.service)));
7127                    out.print(' ');
7128                    filter.service.printComponentShortName(out);
7129                    out.print(" filter ");
7130                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7131        }
7132
7133//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7134//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7135//            final List<ResolveInfo> retList = Lists.newArrayList();
7136//            while (i.hasNext()) {
7137//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7138//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7139//                    retList.add(resolveInfo);
7140//                }
7141//            }
7142//            return retList;
7143//        }
7144
7145        // Keys are String (activity class name), values are Activity.
7146        private final HashMap<ComponentName, PackageParser.Service> mServices
7147                = new HashMap<ComponentName, PackageParser.Service>();
7148        private int mFlags;
7149    };
7150
7151    private final class ProviderIntentResolver
7152            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7153        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7154                boolean defaultOnly, int userId) {
7155            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7156            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7157        }
7158
7159        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7160                int userId) {
7161            if (!sUserManager.exists(userId))
7162                return null;
7163            mFlags = flags;
7164            return super.queryIntent(intent, resolvedType,
7165                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7166        }
7167
7168        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7169                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7170            if (!sUserManager.exists(userId))
7171                return null;
7172            if (packageProviders == null) {
7173                return null;
7174            }
7175            mFlags = flags;
7176            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7177            final int N = packageProviders.size();
7178            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7179                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7180
7181            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7182            for (int i = 0; i < N; ++i) {
7183                intentFilters = packageProviders.get(i).intents;
7184                if (intentFilters != null && intentFilters.size() > 0) {
7185                    PackageParser.ProviderIntentInfo[] array =
7186                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7187                    intentFilters.toArray(array);
7188                    listCut.add(array);
7189                }
7190            }
7191            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7192        }
7193
7194        public final void addProvider(PackageParser.Provider p) {
7195            if (mProviders.containsKey(p.getComponentName())) {
7196                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7197                return;
7198            }
7199
7200            mProviders.put(p.getComponentName(), p);
7201            if (DEBUG_SHOW_INFO) {
7202                Log.v(TAG, "  "
7203                        + (p.info.nonLocalizedLabel != null
7204                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7205                Log.v(TAG, "    Class=" + p.info.name);
7206            }
7207            final int NI = p.intents.size();
7208            int j;
7209            for (j = 0; j < NI; j++) {
7210                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7211                if (DEBUG_SHOW_INFO) {
7212                    Log.v(TAG, "    IntentFilter:");
7213                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7214                }
7215                if (!intent.debugCheck()) {
7216                    Log.w(TAG, "==> For Provider " + p.info.name);
7217                }
7218                addFilter(intent);
7219            }
7220        }
7221
7222        public final void removeProvider(PackageParser.Provider p) {
7223            mProviders.remove(p.getComponentName());
7224            if (DEBUG_SHOW_INFO) {
7225                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7226                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7227                Log.v(TAG, "    Class=" + p.info.name);
7228            }
7229            final int NI = p.intents.size();
7230            int j;
7231            for (j = 0; j < NI; j++) {
7232                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7233                if (DEBUG_SHOW_INFO) {
7234                    Log.v(TAG, "    IntentFilter:");
7235                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7236                }
7237                removeFilter(intent);
7238            }
7239        }
7240
7241        @Override
7242        protected boolean allowFilterResult(
7243                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7244            ProviderInfo filterPi = filter.provider.info;
7245            for (int i = dest.size() - 1; i >= 0; i--) {
7246                ProviderInfo destPi = dest.get(i).providerInfo;
7247                if (destPi.name == filterPi.name
7248                        && destPi.packageName == filterPi.packageName) {
7249                    return false;
7250                }
7251            }
7252            return true;
7253        }
7254
7255        @Override
7256        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7257            return new PackageParser.ProviderIntentInfo[size];
7258        }
7259
7260        @Override
7261        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7262            if (!sUserManager.exists(userId))
7263                return true;
7264            PackageParser.Package p = filter.provider.owner;
7265            if (p != null) {
7266                PackageSetting ps = (PackageSetting) p.mExtras;
7267                if (ps != null) {
7268                    // System apps are never considered stopped for purposes of
7269                    // filtering, because there may be no way for the user to
7270                    // actually re-launch them.
7271                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7272                            && ps.getStopped(userId);
7273                }
7274            }
7275            return false;
7276        }
7277
7278        @Override
7279        protected boolean isPackageForFilter(String packageName,
7280                PackageParser.ProviderIntentInfo info) {
7281            return packageName.equals(info.provider.owner.packageName);
7282        }
7283
7284        @Override
7285        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7286                int match, int userId) {
7287            if (!sUserManager.exists(userId))
7288                return null;
7289            final PackageParser.ProviderIntentInfo info = filter;
7290            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7291                return null;
7292            }
7293            final PackageParser.Provider provider = info.provider;
7294            if (mSafeMode && (provider.info.applicationInfo.flags
7295                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7296                return null;
7297            }
7298            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7299            if (ps == null) {
7300                return null;
7301            }
7302            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7303                    ps.readUserState(userId), userId);
7304            if (pi == null) {
7305                return null;
7306            }
7307            final ResolveInfo res = new ResolveInfo();
7308            res.providerInfo = pi;
7309            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7310                res.filter = filter;
7311            }
7312            res.priority = info.getPriority();
7313            res.preferredOrder = provider.owner.mPreferredOrder;
7314            res.match = match;
7315            res.isDefault = info.hasDefault;
7316            res.labelRes = info.labelRes;
7317            res.nonLocalizedLabel = info.nonLocalizedLabel;
7318            res.icon = info.icon;
7319            res.system = isSystemApp(res.providerInfo.applicationInfo);
7320            return res;
7321        }
7322
7323        @Override
7324        protected void sortResults(List<ResolveInfo> results) {
7325            Collections.sort(results, mResolvePrioritySorter);
7326        }
7327
7328        @Override
7329        protected void dumpFilter(PrintWriter out, String prefix,
7330                PackageParser.ProviderIntentInfo filter) {
7331            out.print(prefix);
7332            out.print(
7333                    Integer.toHexString(System.identityHashCode(filter.provider)));
7334            out.print(' ');
7335            filter.provider.printComponentShortName(out);
7336            out.print(" filter ");
7337            out.println(Integer.toHexString(System.identityHashCode(filter)));
7338        }
7339
7340        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7341                = new HashMap<ComponentName, PackageParser.Provider>();
7342        private int mFlags;
7343    };
7344
7345    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7346            new Comparator<ResolveInfo>() {
7347        public int compare(ResolveInfo r1, ResolveInfo r2) {
7348            int v1 = r1.priority;
7349            int v2 = r2.priority;
7350            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7351            if (v1 != v2) {
7352                return (v1 > v2) ? -1 : 1;
7353            }
7354            v1 = r1.preferredOrder;
7355            v2 = r2.preferredOrder;
7356            if (v1 != v2) {
7357                return (v1 > v2) ? -1 : 1;
7358            }
7359            if (r1.isDefault != r2.isDefault) {
7360                return r1.isDefault ? -1 : 1;
7361            }
7362            v1 = r1.match;
7363            v2 = r2.match;
7364            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7365            if (v1 != v2) {
7366                return (v1 > v2) ? -1 : 1;
7367            }
7368            if (r1.system != r2.system) {
7369                return r1.system ? -1 : 1;
7370            }
7371            return 0;
7372        }
7373    };
7374
7375    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7376            new Comparator<ProviderInfo>() {
7377        public int compare(ProviderInfo p1, ProviderInfo p2) {
7378            final int v1 = p1.initOrder;
7379            final int v2 = p2.initOrder;
7380            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7381        }
7382    };
7383
7384    static final void sendPackageBroadcast(String action, String pkg,
7385            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7386            int[] userIds) {
7387        IActivityManager am = ActivityManagerNative.getDefault();
7388        if (am != null) {
7389            try {
7390                if (userIds == null) {
7391                    userIds = am.getRunningUserIds();
7392                }
7393                for (int id : userIds) {
7394                    final Intent intent = new Intent(action,
7395                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7396                    if (extras != null) {
7397                        intent.putExtras(extras);
7398                    }
7399                    if (targetPkg != null) {
7400                        intent.setPackage(targetPkg);
7401                    }
7402                    // Modify the UID when posting to other users
7403                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7404                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7405                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7406                        intent.putExtra(Intent.EXTRA_UID, uid);
7407                    }
7408                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7409                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7410                    if (DEBUG_BROADCASTS) {
7411                        RuntimeException here = new RuntimeException("here");
7412                        here.fillInStackTrace();
7413                        Slog.d(TAG, "Sending to user " + id + ": "
7414                                + intent.toShortString(false, true, false, false)
7415                                + " " + intent.getExtras(), here);
7416                    }
7417                    am.broadcastIntent(null, intent, null, finishedReceiver,
7418                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7419                            finishedReceiver != null, false, id);
7420                }
7421            } catch (RemoteException ex) {
7422            }
7423        }
7424    }
7425
7426    /**
7427     * Check if the external storage media is available. This is true if there
7428     * is a mounted external storage medium or if the external storage is
7429     * emulated.
7430     */
7431    private boolean isExternalMediaAvailable() {
7432        return mMediaMounted || Environment.isExternalStorageEmulated();
7433    }
7434
7435    @Override
7436    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7437        // writer
7438        synchronized (mPackages) {
7439            if (!isExternalMediaAvailable()) {
7440                // If the external storage is no longer mounted at this point,
7441                // the caller may not have been able to delete all of this
7442                // packages files and can not delete any more.  Bail.
7443                return null;
7444            }
7445            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7446            if (lastPackage != null) {
7447                pkgs.remove(lastPackage);
7448            }
7449            if (pkgs.size() > 0) {
7450                return pkgs.get(0);
7451            }
7452        }
7453        return null;
7454    }
7455
7456    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7457        if (false) {
7458            RuntimeException here = new RuntimeException("here");
7459            here.fillInStackTrace();
7460            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7461                    + " andCode=" + andCode, here);
7462        }
7463        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7464                userId, andCode ? 1 : 0, packageName));
7465    }
7466
7467    void startCleaningPackages() {
7468        // reader
7469        synchronized (mPackages) {
7470            if (!isExternalMediaAvailable()) {
7471                return;
7472            }
7473            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7474                return;
7475            }
7476        }
7477        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7478        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7479        IActivityManager am = ActivityManagerNative.getDefault();
7480        if (am != null) {
7481            try {
7482                am.startService(null, intent, null, UserHandle.USER_OWNER);
7483            } catch (RemoteException e) {
7484            }
7485        }
7486    }
7487
7488    private final class AppDirObserver extends FileObserver {
7489        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7490            super(path, mask);
7491            mRootDir = path;
7492            mIsRom = isrom;
7493            mIsPrivileged = isPrivileged;
7494        }
7495
7496        public void onEvent(int event, String path) {
7497            String removedPackage = null;
7498            int removedAppId = -1;
7499            int[] removedUsers = null;
7500            String addedPackage = null;
7501            int addedAppId = -1;
7502            int[] addedUsers = null;
7503
7504            // TODO post a message to the handler to obtain serial ordering
7505            synchronized (mInstallLock) {
7506                String fullPathStr = null;
7507                File fullPath = null;
7508                if (path != null) {
7509                    fullPath = new File(mRootDir, path);
7510                    fullPathStr = fullPath.getPath();
7511                }
7512
7513                if (DEBUG_APP_DIR_OBSERVER)
7514                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7515
7516                if (!isPackageFilename(path)) {
7517                    if (DEBUG_APP_DIR_OBSERVER)
7518                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7519                    return;
7520                }
7521
7522                // Ignore packages that are being installed or
7523                // have just been installed.
7524                if (ignoreCodePath(fullPathStr)) {
7525                    return;
7526                }
7527                PackageParser.Package p = null;
7528                PackageSetting ps = null;
7529                // reader
7530                synchronized (mPackages) {
7531                    p = mAppDirs.get(fullPathStr);
7532                    if (p != null) {
7533                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7534                        if (ps != null) {
7535                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7536                        } else {
7537                            removedUsers = sUserManager.getUserIds();
7538                        }
7539                    }
7540                    addedUsers = sUserManager.getUserIds();
7541                }
7542                if ((event&REMOVE_EVENTS) != 0) {
7543                    if (ps != null) {
7544                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7545                        removePackageLI(ps, true);
7546                        removedPackage = ps.name;
7547                        removedAppId = ps.appId;
7548                    }
7549                }
7550
7551                if ((event&ADD_EVENTS) != 0) {
7552                    if (p == null) {
7553                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7554                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7555                        if (mIsRom) {
7556                            flags |= PackageParser.PARSE_IS_SYSTEM
7557                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7558                            if (mIsPrivileged) {
7559                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7560                            }
7561                        }
7562                        p = scanPackageLI(fullPath, flags,
7563                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7564                                System.currentTimeMillis(), UserHandle.ALL, null);
7565                        if (p != null) {
7566                            /*
7567                             * TODO this seems dangerous as the package may have
7568                             * changed since we last acquired the mPackages
7569                             * lock.
7570                             */
7571                            // writer
7572                            synchronized (mPackages) {
7573                                updatePermissionsLPw(p.packageName, p,
7574                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7575                            }
7576                            addedPackage = p.applicationInfo.packageName;
7577                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7578                        }
7579                    }
7580                }
7581
7582                // reader
7583                synchronized (mPackages) {
7584                    mSettings.writeLPr();
7585                }
7586            }
7587
7588            if (removedPackage != null) {
7589                Bundle extras = new Bundle(1);
7590                extras.putInt(Intent.EXTRA_UID, removedAppId);
7591                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7592                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7593                        extras, null, null, removedUsers);
7594            }
7595            if (addedPackage != null) {
7596                Bundle extras = new Bundle(1);
7597                extras.putInt(Intent.EXTRA_UID, addedAppId);
7598                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7599                        extras, null, null, addedUsers);
7600            }
7601        }
7602
7603        private final String mRootDir;
7604        private final boolean mIsRom;
7605        private final boolean mIsPrivileged;
7606    }
7607
7608    /*
7609     * The old-style observer methods all just trampoline to the newer signature with
7610     * expanded install observer API.  The older API continues to work but does not
7611     * supply the additional details of the Observer2 API.
7612     */
7613
7614    /* Called when a downloaded package installation has been confirmed by the user */
7615    public void installPackage(
7616            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
7617        installPackageEtc(packageURI, observer, null, flags, null);
7618    }
7619
7620    /* Called when a downloaded package installation has been confirmed by the user */
7621    @Override
7622    public void installPackage(
7623            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
7624            final String installerPackageName) {
7625        installPackageWithVerificationEtc(packageURI, observer, null, flags,
7626                installerPackageName, null, null, null);
7627    }
7628
7629    @Override
7630    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
7631            int flags, String installerPackageName, Uri verificationURI,
7632            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7633        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7634                VerificationParams.NO_UID, manifestDigest);
7635        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7636                installerPackageName, verificationParams, encryptionParams);
7637    }
7638
7639    @Override
7640    public void installPackageWithVerificationAndEncryption(Uri packageURI,
7641            IPackageInstallObserver observer, int flags, String installerPackageName,
7642            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7643        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7644                installerPackageName, verificationParams, encryptionParams);
7645    }
7646
7647    /*
7648     * And here are the "live" versions that take both observer arguments
7649     */
7650    public void installPackageEtc(
7651            final Uri packageURI, final IPackageInstallObserver observer,
7652            IPackageInstallObserver2 observer2, final int flags) {
7653        installPackageEtc(packageURI, observer, observer2, flags, null);
7654    }
7655
7656    public void installPackageEtc(
7657            final Uri packageURI, final IPackageInstallObserver observer,
7658            final IPackageInstallObserver2 observer2, final int flags,
7659            final String installerPackageName) {
7660        installPackageWithVerificationEtc(packageURI, observer, observer2, flags,
7661                installerPackageName, null, null, null);
7662    }
7663
7664    @Override
7665    public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer,
7666            IPackageInstallObserver2 observer2,
7667            int flags, String installerPackageName, Uri verificationURI,
7668            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7669        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7670                VerificationParams.NO_UID, manifestDigest);
7671        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags,
7672                installerPackageName, verificationParams, encryptionParams);
7673    }
7674
7675    /*
7676     * All of the installPackage...*() methods redirect to this one for the master implementation
7677     */
7678    public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI,
7679            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7680            int flags, String installerPackageName,
7681            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7682        if (observer == null && observer2 == null) {
7683            throw new IllegalArgumentException("No install observer supplied");
7684        }
7685        installPackageWithVerificationEncryptionAndAbiOverrideEtc(packageURI, observer, observer2,
7686                flags, installerPackageName, verificationParams, encryptionParams, null);
7687    }
7688
7689    @Override
7690    public void installPackageWithVerificationEncryptionAndAbiOverrideEtc(Uri packageURI,
7691            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7692            int flags, String installerPackageName,
7693            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams,
7694            String packageAbiOverride) {
7695        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7696                null);
7697
7698        final int uid = Binder.getCallingUid();
7699        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7700            try {
7701                if (observer != null) {
7702                    observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7703                }
7704                if (observer2 != null) {
7705                    observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7706                }
7707            } catch (RemoteException re) {
7708            }
7709            return;
7710        }
7711
7712        UserHandle user;
7713        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7714            user = UserHandle.ALL;
7715        } else {
7716            user = new UserHandle(UserHandle.getUserId(uid));
7717        }
7718
7719        final int filteredFlags;
7720
7721        if (uid == Process.SHELL_UID || uid == 0) {
7722            if (DEBUG_INSTALL) {
7723                Slog.v(TAG, "Install from ADB");
7724            }
7725            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7726        } else {
7727            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7728        }
7729
7730        verificationParams.setInstallerUid(uid);
7731
7732        final Message msg = mHandler.obtainMessage(INIT_COPY);
7733        msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags,
7734                installerPackageName, verificationParams, encryptionParams, user,
7735                packageAbiOverride);
7736        mHandler.sendMessage(msg);
7737    }
7738
7739    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7740        Bundle extras = new Bundle(1);
7741        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7742
7743        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7744                packageName, extras, null, null, new int[] {userId});
7745        try {
7746            IActivityManager am = ActivityManagerNative.getDefault();
7747            final boolean isSystem =
7748                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7749            if (isSystem && am.isUserRunning(userId, false)) {
7750                // The just-installed/enabled app is bundled on the system, so presumed
7751                // to be able to run automatically without needing an explicit launch.
7752                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7753                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7754                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7755                        .setPackage(packageName);
7756                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7757                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7758            }
7759        } catch (RemoteException e) {
7760            // shouldn't happen
7761            Slog.w(TAG, "Unable to bootstrap installed package", e);
7762        }
7763    }
7764
7765    @Override
7766    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7767            int userId) {
7768        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7769        PackageSetting pkgSetting;
7770        final int uid = Binder.getCallingUid();
7771        if (UserHandle.getUserId(uid) != userId) {
7772            mContext.enforceCallingOrSelfPermission(
7773                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7774                    "setApplicationBlockedSetting for user " + userId);
7775        }
7776
7777        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7778            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7779            return false;
7780        }
7781
7782        long callingId = Binder.clearCallingIdentity();
7783        try {
7784            boolean sendAdded = false;
7785            boolean sendRemoved = false;
7786            // writer
7787            synchronized (mPackages) {
7788                pkgSetting = mSettings.mPackages.get(packageName);
7789                if (pkgSetting == null) {
7790                    return false;
7791                }
7792                if (pkgSetting.getBlocked(userId) != blocked) {
7793                    pkgSetting.setBlocked(blocked, userId);
7794                    mSettings.writePackageRestrictionsLPr(userId);
7795                    if (blocked) {
7796                        sendRemoved = true;
7797                    } else {
7798                        sendAdded = true;
7799                    }
7800                }
7801            }
7802            if (sendAdded) {
7803                sendPackageAddedForUser(packageName, pkgSetting, userId);
7804                return true;
7805            }
7806            if (sendRemoved) {
7807                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7808                        "blocking pkg");
7809                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7810            }
7811        } finally {
7812            Binder.restoreCallingIdentity(callingId);
7813        }
7814        return false;
7815    }
7816
7817    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7818            int userId) {
7819        final PackageRemovedInfo info = new PackageRemovedInfo();
7820        info.removedPackage = packageName;
7821        info.removedUsers = new int[] {userId};
7822        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7823        info.sendBroadcast(false, false, false);
7824    }
7825
7826    /**
7827     * Returns true if application is not found or there was an error. Otherwise it returns
7828     * the blocked state of the package for the given user.
7829     */
7830    @Override
7831    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7832        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7833        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7834                "getApplicationBlocked for user " + userId);
7835        PackageSetting pkgSetting;
7836        long callingId = Binder.clearCallingIdentity();
7837        try {
7838            // writer
7839            synchronized (mPackages) {
7840                pkgSetting = mSettings.mPackages.get(packageName);
7841                if (pkgSetting == null) {
7842                    return true;
7843                }
7844                return pkgSetting.getBlocked(userId);
7845            }
7846        } finally {
7847            Binder.restoreCallingIdentity(callingId);
7848        }
7849    }
7850
7851    void installStage(String basePackageName, File stageDir, IPackageInstallObserver2 observer,
7852            int flags) {
7853        // TODO: install stage!
7854        try {
7855            observer.packageInstalled(basePackageName, null,
7856                    PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
7857        } catch (RemoteException ignored) {
7858        }
7859    }
7860
7861    /**
7862     * @hide
7863     */
7864    @Override
7865    public int installExistingPackageAsUser(String packageName, int userId) {
7866        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7867                null);
7868        PackageSetting pkgSetting;
7869        final int uid = Binder.getCallingUid();
7870        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7871        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7872            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7873        }
7874
7875        long callingId = Binder.clearCallingIdentity();
7876        try {
7877            boolean sendAdded = false;
7878            Bundle extras = new Bundle(1);
7879
7880            // writer
7881            synchronized (mPackages) {
7882                pkgSetting = mSettings.mPackages.get(packageName);
7883                if (pkgSetting == null) {
7884                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7885                }
7886                if (!pkgSetting.getInstalled(userId)) {
7887                    pkgSetting.setInstalled(true, userId);
7888                    pkgSetting.setBlocked(false, userId);
7889                    mSettings.writePackageRestrictionsLPr(userId);
7890                    sendAdded = true;
7891                }
7892            }
7893
7894            if (sendAdded) {
7895                sendPackageAddedForUser(packageName, pkgSetting, userId);
7896            }
7897        } finally {
7898            Binder.restoreCallingIdentity(callingId);
7899        }
7900
7901        return PackageManager.INSTALL_SUCCEEDED;
7902    }
7903
7904    boolean isUserRestricted(int userId, String restrictionKey) {
7905        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7906        if (restrictions.getBoolean(restrictionKey, false)) {
7907            Log.w(TAG, "User is restricted: " + restrictionKey);
7908            return true;
7909        }
7910        return false;
7911    }
7912
7913    @Override
7914    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7915        mContext.enforceCallingOrSelfPermission(
7916                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7917                "Only package verification agents can verify applications");
7918
7919        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7920        final PackageVerificationResponse response = new PackageVerificationResponse(
7921                verificationCode, Binder.getCallingUid());
7922        msg.arg1 = id;
7923        msg.obj = response;
7924        mHandler.sendMessage(msg);
7925    }
7926
7927    @Override
7928    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7929            long millisecondsToDelay) {
7930        mContext.enforceCallingOrSelfPermission(
7931                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7932                "Only package verification agents can extend verification timeouts");
7933
7934        final PackageVerificationState state = mPendingVerification.get(id);
7935        final PackageVerificationResponse response = new PackageVerificationResponse(
7936                verificationCodeAtTimeout, Binder.getCallingUid());
7937
7938        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7939            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7940        }
7941        if (millisecondsToDelay < 0) {
7942            millisecondsToDelay = 0;
7943        }
7944        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7945                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7946            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7947        }
7948
7949        if ((state != null) && !state.timeoutExtended()) {
7950            state.extendTimeout();
7951
7952            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7953            msg.arg1 = id;
7954            msg.obj = response;
7955            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7956        }
7957    }
7958
7959    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7960            int verificationCode, UserHandle user) {
7961        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7962        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7963        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7964        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7965        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7966
7967        mContext.sendBroadcastAsUser(intent, user,
7968                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7969    }
7970
7971    private ComponentName matchComponentForVerifier(String packageName,
7972            List<ResolveInfo> receivers) {
7973        ActivityInfo targetReceiver = null;
7974
7975        final int NR = receivers.size();
7976        for (int i = 0; i < NR; i++) {
7977            final ResolveInfo info = receivers.get(i);
7978            if (info.activityInfo == null) {
7979                continue;
7980            }
7981
7982            if (packageName.equals(info.activityInfo.packageName)) {
7983                targetReceiver = info.activityInfo;
7984                break;
7985            }
7986        }
7987
7988        if (targetReceiver == null) {
7989            return null;
7990        }
7991
7992        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7993    }
7994
7995    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7996            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7997        if (pkgInfo.verifiers.length == 0) {
7998            return null;
7999        }
8000
8001        final int N = pkgInfo.verifiers.length;
8002        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8003        for (int i = 0; i < N; i++) {
8004            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8005
8006            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8007                    receivers);
8008            if (comp == null) {
8009                continue;
8010            }
8011
8012            final int verifierUid = getUidForVerifier(verifierInfo);
8013            if (verifierUid == -1) {
8014                continue;
8015            }
8016
8017            if (DEBUG_VERIFY) {
8018                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8019                        + " with the correct signature");
8020            }
8021            sufficientVerifiers.add(comp);
8022            verificationState.addSufficientVerifier(verifierUid);
8023        }
8024
8025        return sufficientVerifiers;
8026    }
8027
8028    private int getUidForVerifier(VerifierInfo verifierInfo) {
8029        synchronized (mPackages) {
8030            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8031            if (pkg == null) {
8032                return -1;
8033            } else if (pkg.mSignatures.length != 1) {
8034                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8035                        + " has more than one signature; ignoring");
8036                return -1;
8037            }
8038
8039            /*
8040             * If the public key of the package's signature does not match
8041             * our expected public key, then this is a different package and
8042             * we should skip.
8043             */
8044
8045            final byte[] expectedPublicKey;
8046            try {
8047                final Signature verifierSig = pkg.mSignatures[0];
8048                final PublicKey publicKey = verifierSig.getPublicKey();
8049                expectedPublicKey = publicKey.getEncoded();
8050            } catch (CertificateException e) {
8051                return -1;
8052            }
8053
8054            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8055
8056            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8057                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8058                        + " does not have the expected public key; ignoring");
8059                return -1;
8060            }
8061
8062            return pkg.applicationInfo.uid;
8063        }
8064    }
8065
8066    @Override
8067    public void finishPackageInstall(int token) {
8068        enforceSystemOrRoot("Only the system is allowed to finish installs");
8069
8070        if (DEBUG_INSTALL) {
8071            Slog.v(TAG, "BM finishing package install for " + token);
8072        }
8073
8074        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8075        mHandler.sendMessage(msg);
8076    }
8077
8078    /**
8079     * Get the verification agent timeout.
8080     *
8081     * @return verification timeout in milliseconds
8082     */
8083    private long getVerificationTimeout() {
8084        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8085                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8086                DEFAULT_VERIFICATION_TIMEOUT);
8087    }
8088
8089    /**
8090     * Get the default verification agent response code.
8091     *
8092     * @return default verification response code
8093     */
8094    private int getDefaultVerificationResponse() {
8095        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8096                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8097                DEFAULT_VERIFICATION_RESPONSE);
8098    }
8099
8100    /**
8101     * Check whether or not package verification has been enabled.
8102     *
8103     * @return true if verification should be performed
8104     */
8105    private boolean isVerificationEnabled(int flags) {
8106        if (!DEFAULT_VERIFY_ENABLE) {
8107            return false;
8108        }
8109
8110        // Check if installing from ADB
8111        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8112            // Do not run verification in a test harness environment
8113            if (ActivityManager.isRunningInTestHarness()) {
8114                return false;
8115            }
8116            // Check if the developer does not want package verification for ADB installs
8117            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8118                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8119                return false;
8120            }
8121        }
8122
8123        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8124                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8125    }
8126
8127    /**
8128     * Get the "allow unknown sources" setting.
8129     *
8130     * @return the current "allow unknown sources" setting
8131     */
8132    private int getUnknownSourcesSettings() {
8133        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8134                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8135                -1);
8136    }
8137
8138    @Override
8139    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8140        final int uid = Binder.getCallingUid();
8141        // writer
8142        synchronized (mPackages) {
8143            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8144            if (targetPackageSetting == null) {
8145                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8146            }
8147
8148            PackageSetting installerPackageSetting;
8149            if (installerPackageName != null) {
8150                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8151                if (installerPackageSetting == null) {
8152                    throw new IllegalArgumentException("Unknown installer package: "
8153                            + installerPackageName);
8154                }
8155            } else {
8156                installerPackageSetting = null;
8157            }
8158
8159            Signature[] callerSignature;
8160            Object obj = mSettings.getUserIdLPr(uid);
8161            if (obj != null) {
8162                if (obj instanceof SharedUserSetting) {
8163                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8164                } else if (obj instanceof PackageSetting) {
8165                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8166                } else {
8167                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8168                }
8169            } else {
8170                throw new SecurityException("Unknown calling uid " + uid);
8171            }
8172
8173            // Verify: can't set installerPackageName to a package that is
8174            // not signed with the same cert as the caller.
8175            if (installerPackageSetting != null) {
8176                if (compareSignatures(callerSignature,
8177                        installerPackageSetting.signatures.mSignatures)
8178                        != PackageManager.SIGNATURE_MATCH) {
8179                    throw new SecurityException(
8180                            "Caller does not have same cert as new installer package "
8181                            + installerPackageName);
8182                }
8183            }
8184
8185            // Verify: if target already has an installer package, it must
8186            // be signed with the same cert as the caller.
8187            if (targetPackageSetting.installerPackageName != null) {
8188                PackageSetting setting = mSettings.mPackages.get(
8189                        targetPackageSetting.installerPackageName);
8190                // If the currently set package isn't valid, then it's always
8191                // okay to change it.
8192                if (setting != null) {
8193                    if (compareSignatures(callerSignature,
8194                            setting.signatures.mSignatures)
8195                            != PackageManager.SIGNATURE_MATCH) {
8196                        throw new SecurityException(
8197                                "Caller does not have same cert as old installer package "
8198                                + targetPackageSetting.installerPackageName);
8199                    }
8200                }
8201            }
8202
8203            // Okay!
8204            targetPackageSetting.installerPackageName = installerPackageName;
8205            scheduleWriteSettingsLocked();
8206        }
8207    }
8208
8209    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8210        // Queue up an async operation since the package installation may take a little while.
8211        mHandler.post(new Runnable() {
8212            public void run() {
8213                mHandler.removeCallbacks(this);
8214                 // Result object to be returned
8215                PackageInstalledInfo res = new PackageInstalledInfo();
8216                res.returnCode = currentStatus;
8217                res.uid = -1;
8218                res.pkg = null;
8219                res.removedInfo = new PackageRemovedInfo();
8220                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8221                    args.doPreInstall(res.returnCode);
8222                    synchronized (mInstallLock) {
8223                        installPackageLI(args, true, res);
8224                    }
8225                    args.doPostInstall(res.returnCode, res.uid);
8226                }
8227
8228                // A restore should be performed at this point if (a) the install
8229                // succeeded, (b) the operation is not an update, and (c) the new
8230                // package has a backupAgent defined.
8231                final boolean update = res.removedInfo.removedPackage != null;
8232                boolean doRestore = (!update
8233                        && res.pkg != null
8234                        && res.pkg.applicationInfo.backupAgentName != null);
8235
8236                // Set up the post-install work request bookkeeping.  This will be used
8237                // and cleaned up by the post-install event handling regardless of whether
8238                // there's a restore pass performed.  Token values are >= 1.
8239                int token;
8240                if (mNextInstallToken < 0) mNextInstallToken = 1;
8241                token = mNextInstallToken++;
8242
8243                PostInstallData data = new PostInstallData(args, res);
8244                mRunningInstalls.put(token, data);
8245                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8246
8247                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8248                    // Pass responsibility to the Backup Manager.  It will perform a
8249                    // restore if appropriate, then pass responsibility back to the
8250                    // Package Manager to run the post-install observer callbacks
8251                    // and broadcasts.
8252                    IBackupManager bm = IBackupManager.Stub.asInterface(
8253                            ServiceManager.getService(Context.BACKUP_SERVICE));
8254                    if (bm != null) {
8255                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8256                                + " to BM for possible restore");
8257                        try {
8258                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8259                        } catch (RemoteException e) {
8260                            // can't happen; the backup manager is local
8261                        } catch (Exception e) {
8262                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8263                            doRestore = false;
8264                        }
8265                    } else {
8266                        Slog.e(TAG, "Backup Manager not found!");
8267                        doRestore = false;
8268                    }
8269                }
8270
8271                if (!doRestore) {
8272                    // No restore possible, or the Backup Manager was mysteriously not
8273                    // available -- just fire the post-install work request directly.
8274                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8275                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8276                    mHandler.sendMessage(msg);
8277                }
8278            }
8279        });
8280    }
8281
8282    private abstract class HandlerParams {
8283        private static final int MAX_RETRIES = 4;
8284
8285        /**
8286         * Number of times startCopy() has been attempted and had a non-fatal
8287         * error.
8288         */
8289        private int mRetries = 0;
8290
8291        /** User handle for the user requesting the information or installation. */
8292        private final UserHandle mUser;
8293
8294        HandlerParams(UserHandle user) {
8295            mUser = user;
8296        }
8297
8298        UserHandle getUser() {
8299            return mUser;
8300        }
8301
8302        final boolean startCopy() {
8303            boolean res;
8304            try {
8305                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8306
8307                if (++mRetries > MAX_RETRIES) {
8308                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8309                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8310                    handleServiceError();
8311                    return false;
8312                } else {
8313                    handleStartCopy();
8314                    res = true;
8315                }
8316            } catch (RemoteException e) {
8317                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8318                mHandler.sendEmptyMessage(MCS_RECONNECT);
8319                res = false;
8320            }
8321            handleReturnCode();
8322            return res;
8323        }
8324
8325        final void serviceError() {
8326            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8327            handleServiceError();
8328            handleReturnCode();
8329        }
8330
8331        abstract void handleStartCopy() throws RemoteException;
8332        abstract void handleServiceError();
8333        abstract void handleReturnCode();
8334    }
8335
8336    class MeasureParams extends HandlerParams {
8337        private final PackageStats mStats;
8338        private boolean mSuccess;
8339
8340        private final IPackageStatsObserver mObserver;
8341
8342        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8343            super(new UserHandle(stats.userHandle));
8344            mObserver = observer;
8345            mStats = stats;
8346        }
8347
8348        @Override
8349        public String toString() {
8350            return "MeasureParams{"
8351                + Integer.toHexString(System.identityHashCode(this))
8352                + " " + mStats.packageName + "}";
8353        }
8354
8355        @Override
8356        void handleStartCopy() throws RemoteException {
8357            synchronized (mInstallLock) {
8358                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8359            }
8360
8361            if (mSuccess) {
8362                final boolean mounted;
8363                if (Environment.isExternalStorageEmulated()) {
8364                    mounted = true;
8365                } else {
8366                    final String status = Environment.getExternalStorageState();
8367                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8368                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8369                }
8370
8371                if (mounted) {
8372                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8373
8374                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8375                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8376
8377                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8378                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8379
8380                    // Always subtract cache size, since it's a subdirectory
8381                    mStats.externalDataSize -= mStats.externalCacheSize;
8382
8383                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8384                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8385
8386                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8387                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8388                }
8389            }
8390        }
8391
8392        @Override
8393        void handleReturnCode() {
8394            if (mObserver != null) {
8395                try {
8396                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8397                } catch (RemoteException e) {
8398                    Slog.i(TAG, "Observer no longer exists.");
8399                }
8400            }
8401        }
8402
8403        @Override
8404        void handleServiceError() {
8405            Slog.e(TAG, "Could not measure application " + mStats.packageName
8406                            + " external storage");
8407        }
8408    }
8409
8410    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8411            throws RemoteException {
8412        long result = 0;
8413        for (File path : paths) {
8414            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8415        }
8416        return result;
8417    }
8418
8419    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8420        for (File path : paths) {
8421            try {
8422                mcs.clearDirectory(path.getAbsolutePath());
8423            } catch (RemoteException e) {
8424            }
8425        }
8426    }
8427
8428    class InstallParams extends HandlerParams {
8429        final IPackageInstallObserver observer;
8430        final IPackageInstallObserver2 observer2;
8431        int flags;
8432
8433        private final Uri mPackageURI;
8434        final String installerPackageName;
8435        final VerificationParams verificationParams;
8436        private InstallArgs mArgs;
8437        private int mRet;
8438        private File mTempPackage;
8439        final ContainerEncryptionParams encryptionParams;
8440        final String packageAbiOverride;
8441        final String packageInstructionSetOverride;
8442
8443        InstallParams(Uri packageURI,
8444                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8445                int flags, String installerPackageName, VerificationParams verificationParams,
8446                ContainerEncryptionParams encryptionParams, UserHandle user,
8447                String packageAbiOverride) {
8448            super(user);
8449            this.mPackageURI = packageURI;
8450            this.flags = flags;
8451            this.observer = observer;
8452            this.observer2 = observer2;
8453            this.installerPackageName = installerPackageName;
8454            this.verificationParams = verificationParams;
8455            this.encryptionParams = encryptionParams;
8456            this.packageAbiOverride = packageAbiOverride;
8457            this.packageInstructionSetOverride = (packageAbiOverride == null) ?
8458                    packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride);
8459        }
8460
8461        @Override
8462        public String toString() {
8463            return "InstallParams{"
8464                + Integer.toHexString(System.identityHashCode(this))
8465                + " " + mPackageURI + "}";
8466        }
8467
8468        public ManifestDigest getManifestDigest() {
8469            if (verificationParams == null) {
8470                return null;
8471            }
8472            return verificationParams.getManifestDigest();
8473        }
8474
8475        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8476            String packageName = pkgLite.packageName;
8477            int installLocation = pkgLite.installLocation;
8478            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8479            // reader
8480            synchronized (mPackages) {
8481                PackageParser.Package pkg = mPackages.get(packageName);
8482                if (pkg != null) {
8483                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8484                        // Check for downgrading.
8485                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8486                            if (pkgLite.versionCode < pkg.mVersionCode) {
8487                                Slog.w(TAG, "Can't install update of " + packageName
8488                                        + " update version " + pkgLite.versionCode
8489                                        + " is older than installed version "
8490                                        + pkg.mVersionCode);
8491                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8492                            }
8493                        }
8494                        // Check for updated system application.
8495                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8496                            if (onSd) {
8497                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8498                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8499                            }
8500                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8501                        } else {
8502                            if (onSd) {
8503                                // Install flag overrides everything.
8504                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8505                            }
8506                            // If current upgrade specifies particular preference
8507                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8508                                // Application explicitly specified internal.
8509                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8510                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8511                                // App explictly prefers external. Let policy decide
8512                            } else {
8513                                // Prefer previous location
8514                                if (isExternal(pkg)) {
8515                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8516                                }
8517                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8518                            }
8519                        }
8520                    } else {
8521                        // Invalid install. Return error code
8522                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8523                    }
8524                }
8525            }
8526            // All the special cases have been taken care of.
8527            // Return result based on recommended install location.
8528            if (onSd) {
8529                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8530            }
8531            return pkgLite.recommendedInstallLocation;
8532        }
8533
8534        private long getMemoryLowThreshold() {
8535            final DeviceStorageMonitorInternal
8536                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8537            if (dsm == null) {
8538                return 0L;
8539            }
8540            return dsm.getMemoryLowThreshold();
8541        }
8542
8543        /*
8544         * Invoke remote method to get package information and install
8545         * location values. Override install location based on default
8546         * policy if needed and then create install arguments based
8547         * on the install location.
8548         */
8549        public void handleStartCopy() throws RemoteException {
8550            int ret = PackageManager.INSTALL_SUCCEEDED;
8551            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8552            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8553            PackageInfoLite pkgLite = null;
8554
8555            if (onInt && onSd) {
8556                // Check if both bits are set.
8557                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8558                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8559            } else {
8560                final long lowThreshold = getMemoryLowThreshold();
8561                if (lowThreshold == 0L) {
8562                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8563                }
8564
8565                try {
8566                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
8567                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8568
8569                    final File packageFile;
8570                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
8571                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
8572                        if (mTempPackage != null) {
8573                            ParcelFileDescriptor out;
8574                            try {
8575                                out = ParcelFileDescriptor.open(mTempPackage,
8576                                        ParcelFileDescriptor.MODE_READ_WRITE);
8577                            } catch (FileNotFoundException e) {
8578                                out = null;
8579                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
8580                            }
8581
8582                            // Make a temporary file for decryption.
8583                            ret = mContainerService
8584                                    .copyResource(mPackageURI, encryptionParams, out);
8585                            IoUtils.closeQuietly(out);
8586
8587                            packageFile = mTempPackage;
8588
8589                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
8590                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
8591                                            | FileUtils.S_IROTH,
8592                                    -1, -1);
8593                        } else {
8594                            packageFile = null;
8595                        }
8596                    } else {
8597                        packageFile = new File(mPackageURI.getPath());
8598                    }
8599
8600                    if (packageFile != null) {
8601                        // Remote call to find out default install location
8602                        final String packageFilePath = packageFile.getAbsolutePath();
8603                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
8604                                lowThreshold, packageAbiOverride);
8605
8606                        /*
8607                         * If we have too little free space, try to free cache
8608                         * before giving up.
8609                         */
8610                        if (pkgLite.recommendedInstallLocation
8611                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8612                            final long size = mContainerService.calculateInstalledSize(
8613                                    packageFilePath, isForwardLocked(), packageAbiOverride);
8614                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8615                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
8616                                        flags, lowThreshold, packageAbiOverride);
8617                            }
8618                            /*
8619                             * The cache free must have deleted the file we
8620                             * downloaded to install.
8621                             *
8622                             * TODO: fix the "freeCache" call to not delete
8623                             *       the file we care about.
8624                             */
8625                            if (pkgLite.recommendedInstallLocation
8626                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8627                                pkgLite.recommendedInstallLocation
8628                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8629                            }
8630                        }
8631                    }
8632                } finally {
8633                    mContext.revokeUriPermission(mPackageURI,
8634                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8635                }
8636            }
8637
8638            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8639                int loc = pkgLite.recommendedInstallLocation;
8640                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8641                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8642                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8643                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8644                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8645                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8646                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8647                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8648                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8649                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8650                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8651                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8652                } else {
8653                    // Override with defaults if needed.
8654                    loc = installLocationPolicy(pkgLite, flags);
8655                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8656                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8657                    } else if (!onSd && !onInt) {
8658                        // Override install location with flags
8659                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8660                            // Set the flag to install on external media.
8661                            flags |= PackageManager.INSTALL_EXTERNAL;
8662                            flags &= ~PackageManager.INSTALL_INTERNAL;
8663                        } else {
8664                            // Make sure the flag for installing on external
8665                            // media is unset
8666                            flags |= PackageManager.INSTALL_INTERNAL;
8667                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8668                        }
8669                    }
8670                }
8671            }
8672
8673            final InstallArgs args = createInstallArgs(this);
8674            mArgs = args;
8675
8676            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8677                 /*
8678                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8679                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8680                 */
8681                int userIdentifier = getUser().getIdentifier();
8682                if (userIdentifier == UserHandle.USER_ALL
8683                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8684                    userIdentifier = UserHandle.USER_OWNER;
8685                }
8686
8687                /*
8688                 * Determine if we have any installed package verifiers. If we
8689                 * do, then we'll defer to them to verify the packages.
8690                 */
8691                final int requiredUid = mRequiredVerifierPackage == null ? -1
8692                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8693                if (requiredUid != -1 && isVerificationEnabled(flags)) {
8694                    final Intent verification = new Intent(
8695                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8696                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
8697                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8698
8699                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8700                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8701                            0 /* TODO: Which userId? */);
8702
8703                    if (DEBUG_VERIFY) {
8704                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8705                                + verification.toString() + " with " + pkgLite.verifiers.length
8706                                + " optional verifiers");
8707                    }
8708
8709                    final int verificationId = mPendingVerificationToken++;
8710
8711                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8712
8713                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8714                            installerPackageName);
8715
8716                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8717
8718                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8719                            pkgLite.packageName);
8720
8721                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8722                            pkgLite.versionCode);
8723
8724                    if (verificationParams != null) {
8725                        if (verificationParams.getVerificationURI() != null) {
8726                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8727                                 verificationParams.getVerificationURI());
8728                        }
8729                        if (verificationParams.getOriginatingURI() != null) {
8730                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8731                                  verificationParams.getOriginatingURI());
8732                        }
8733                        if (verificationParams.getReferrer() != null) {
8734                            verification.putExtra(Intent.EXTRA_REFERRER,
8735                                  verificationParams.getReferrer());
8736                        }
8737                        if (verificationParams.getOriginatingUid() >= 0) {
8738                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8739                                  verificationParams.getOriginatingUid());
8740                        }
8741                        if (verificationParams.getInstallerUid() >= 0) {
8742                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8743                                  verificationParams.getInstallerUid());
8744                        }
8745                    }
8746
8747                    final PackageVerificationState verificationState = new PackageVerificationState(
8748                            requiredUid, args);
8749
8750                    mPendingVerification.append(verificationId, verificationState);
8751
8752                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8753                            receivers, verificationState);
8754
8755                    /*
8756                     * If any sufficient verifiers were listed in the package
8757                     * manifest, attempt to ask them.
8758                     */
8759                    if (sufficientVerifiers != null) {
8760                        final int N = sufficientVerifiers.size();
8761                        if (N == 0) {
8762                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8763                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8764                        } else {
8765                            for (int i = 0; i < N; i++) {
8766                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8767
8768                                final Intent sufficientIntent = new Intent(verification);
8769                                sufficientIntent.setComponent(verifierComponent);
8770
8771                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8772                            }
8773                        }
8774                    }
8775
8776                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8777                            mRequiredVerifierPackage, receivers);
8778                    if (ret == PackageManager.INSTALL_SUCCEEDED
8779                            && mRequiredVerifierPackage != null) {
8780                        /*
8781                         * Send the intent to the required verification agent,
8782                         * but only start the verification timeout after the
8783                         * target BroadcastReceivers have run.
8784                         */
8785                        verification.setComponent(requiredVerifierComponent);
8786                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8787                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8788                                new BroadcastReceiver() {
8789                                    @Override
8790                                    public void onReceive(Context context, Intent intent) {
8791                                        final Message msg = mHandler
8792                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8793                                        msg.arg1 = verificationId;
8794                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8795                                    }
8796                                }, null, 0, null, null);
8797
8798                        /*
8799                         * We don't want the copy to proceed until verification
8800                         * succeeds, so null out this field.
8801                         */
8802                        mArgs = null;
8803                    }
8804                } else {
8805                    /*
8806                     * No package verification is enabled, so immediately start
8807                     * the remote call to initiate copy using temporary file.
8808                     */
8809                    ret = args.copyApk(mContainerService, true);
8810                }
8811            }
8812
8813            mRet = ret;
8814        }
8815
8816        @Override
8817        void handleReturnCode() {
8818            // If mArgs is null, then MCS couldn't be reached. When it
8819            // reconnects, it will try again to install. At that point, this
8820            // will succeed.
8821            if (mArgs != null) {
8822                processPendingInstall(mArgs, mRet);
8823
8824                if (mTempPackage != null) {
8825                    if (!mTempPackage.delete()) {
8826                        Slog.w(TAG, "Couldn't delete temporary file: " +
8827                                mTempPackage.getAbsolutePath());
8828                    }
8829                }
8830            }
8831        }
8832
8833        @Override
8834        void handleServiceError() {
8835            mArgs = createInstallArgs(this);
8836            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8837        }
8838
8839        public boolean isForwardLocked() {
8840            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8841        }
8842
8843        public Uri getPackageUri() {
8844            if (mTempPackage != null) {
8845                return Uri.fromFile(mTempPackage);
8846            } else {
8847                return mPackageURI;
8848            }
8849        }
8850    }
8851
8852    /*
8853     * Utility class used in movePackage api.
8854     * srcArgs and targetArgs are not set for invalid flags and make
8855     * sure to do null checks when invoking methods on them.
8856     * We probably want to return ErrorPrams for both failed installs
8857     * and moves.
8858     */
8859    class MoveParams extends HandlerParams {
8860        final IPackageMoveObserver observer;
8861        final int flags;
8862        final String packageName;
8863        final InstallArgs srcArgs;
8864        final InstallArgs targetArgs;
8865        int uid;
8866        int mRet;
8867
8868        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8869                String packageName, String dataDir, String instructionSet,
8870                int uid, UserHandle user) {
8871            super(user);
8872            this.srcArgs = srcArgs;
8873            this.observer = observer;
8874            this.flags = flags;
8875            this.packageName = packageName;
8876            this.uid = uid;
8877            if (srcArgs != null) {
8878                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8879                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet);
8880            } else {
8881                targetArgs = null;
8882            }
8883        }
8884
8885        @Override
8886        public String toString() {
8887            return "MoveParams{"
8888                + Integer.toHexString(System.identityHashCode(this))
8889                + " " + packageName + "}";
8890        }
8891
8892        public void handleStartCopy() throws RemoteException {
8893            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8894            // Check for storage space on target medium
8895            if (!targetArgs.checkFreeStorage(mContainerService)) {
8896                Log.w(TAG, "Insufficient storage to install");
8897                return;
8898            }
8899
8900            mRet = srcArgs.doPreCopy();
8901            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8902                return;
8903            }
8904
8905            mRet = targetArgs.copyApk(mContainerService, false);
8906            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8907                srcArgs.doPostCopy(uid);
8908                return;
8909            }
8910
8911            mRet = srcArgs.doPostCopy(uid);
8912            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8913                return;
8914            }
8915
8916            mRet = targetArgs.doPreInstall(mRet);
8917            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8918                return;
8919            }
8920
8921            if (DEBUG_SD_INSTALL) {
8922                StringBuilder builder = new StringBuilder();
8923                if (srcArgs != null) {
8924                    builder.append("src: ");
8925                    builder.append(srcArgs.getCodePath());
8926                }
8927                if (targetArgs != null) {
8928                    builder.append(" target : ");
8929                    builder.append(targetArgs.getCodePath());
8930                }
8931                Log.i(TAG, builder.toString());
8932            }
8933        }
8934
8935        @Override
8936        void handleReturnCode() {
8937            targetArgs.doPostInstall(mRet, uid);
8938            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8939            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8940                currentStatus = PackageManager.MOVE_SUCCEEDED;
8941            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8942                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8943            }
8944            processPendingMove(this, currentStatus);
8945        }
8946
8947        @Override
8948        void handleServiceError() {
8949            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8950        }
8951    }
8952
8953    /**
8954     * Used during creation of InstallArgs
8955     *
8956     * @param flags package installation flags
8957     * @return true if should be installed on external storage
8958     */
8959    private static boolean installOnSd(int flags) {
8960        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8961            return false;
8962        }
8963        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8964            return true;
8965        }
8966        return false;
8967    }
8968
8969    /**
8970     * Used during creation of InstallArgs
8971     *
8972     * @param flags package installation flags
8973     * @return true if should be installed as forward locked
8974     */
8975    private static boolean installForwardLocked(int flags) {
8976        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8977    }
8978
8979    private InstallArgs createInstallArgs(InstallParams params) {
8980        if (installOnSd(params.flags) || params.isForwardLocked()) {
8981            return new AsecInstallArgs(params);
8982        } else {
8983            return new FileInstallArgs(params);
8984        }
8985    }
8986
8987    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
8988            String nativeLibraryPath, String instructionSet) {
8989        final boolean isInAsec;
8990        if (installOnSd(flags)) {
8991            /* Apps on SD card are always in ASEC containers. */
8992            isInAsec = true;
8993        } else if (installForwardLocked(flags)
8994                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8995            /*
8996             * Forward-locked apps are only in ASEC containers if they're the
8997             * new style
8998             */
8999            isInAsec = true;
9000        } else {
9001            isInAsec = false;
9002        }
9003
9004        if (isInAsec) {
9005            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
9006                    instructionSet, installOnSd(flags), installForwardLocked(flags));
9007        } else {
9008            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
9009                    instructionSet);
9010        }
9011    }
9012
9013    // Used by package mover
9014    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir,
9015            String instructionSet) {
9016        if (installOnSd(flags) || installForwardLocked(flags)) {
9017            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
9018                    + AsecInstallArgs.RES_FILE_NAME);
9019            return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags),
9020                    installForwardLocked(flags));
9021        } else {
9022            return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet);
9023        }
9024    }
9025
9026    static abstract class InstallArgs {
9027        final IPackageInstallObserver observer;
9028        final IPackageInstallObserver2 observer2;
9029        // Always refers to PackageManager flags only
9030        final int flags;
9031        final Uri packageURI;
9032        final String installerPackageName;
9033        final ManifestDigest manifestDigest;
9034        final UserHandle user;
9035        final String instructionSet;
9036        final String abiOverride;
9037
9038        InstallArgs(Uri packageURI,
9039                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
9040                int flags, String installerPackageName, ManifestDigest manifestDigest,
9041                UserHandle user, String instructionSet, String abiOverride) {
9042            this.packageURI = packageURI;
9043            this.flags = flags;
9044            this.observer = observer;
9045            this.observer2 = observer2;
9046            this.installerPackageName = installerPackageName;
9047            this.manifestDigest = manifestDigest;
9048            this.user = user;
9049            this.instructionSet = instructionSet;
9050            this.abiOverride = abiOverride;
9051        }
9052
9053        abstract void createCopyFile();
9054        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9055        abstract int doPreInstall(int status);
9056        abstract boolean doRename(int status, String pkgName, String oldCodePath);
9057
9058        abstract int doPostInstall(int status, int uid);
9059        abstract String getCodePath();
9060        abstract String getResourcePath();
9061        abstract String getNativeLibraryPath();
9062        // Need installer lock especially for dex file removal.
9063        abstract void cleanUpResourcesLI();
9064        abstract boolean doPostDeleteLI(boolean delete);
9065        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9066
9067        /**
9068         * Called before the source arguments are copied. This is used mostly
9069         * for MoveParams when it needs to read the source file to put it in the
9070         * destination.
9071         */
9072        int doPreCopy() {
9073            return PackageManager.INSTALL_SUCCEEDED;
9074        }
9075
9076        /**
9077         * Called after the source arguments are copied. This is used mostly for
9078         * MoveParams when it needs to read the source file to put it in the
9079         * destination.
9080         *
9081         * @return
9082         */
9083        int doPostCopy(int uid) {
9084            return PackageManager.INSTALL_SUCCEEDED;
9085        }
9086
9087        protected boolean isFwdLocked() {
9088            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9089        }
9090
9091        UserHandle getUser() {
9092            return user;
9093        }
9094    }
9095
9096    class FileInstallArgs extends InstallArgs {
9097        File installDir;
9098        String codeFileName;
9099        String resourceFileName;
9100        String libraryPath;
9101        boolean created = false;
9102
9103        FileInstallArgs(InstallParams params) {
9104            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9105                    params.installerPackageName, params.getManifestDigest(),
9106                    params.getUser(), params.packageInstructionSetOverride,
9107                    params.packageAbiOverride);
9108        }
9109
9110        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9111                String instructionSet) {
9112            super(null, null, null, 0, null, null, null, instructionSet, null);
9113            File codeFile = new File(fullCodePath);
9114            installDir = codeFile.getParentFile();
9115            codeFileName = fullCodePath;
9116            resourceFileName = fullResourcePath;
9117            libraryPath = nativeLibraryPath;
9118        }
9119
9120        FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) {
9121            super(packageURI, null, null, 0, null, null, null, instructionSet, null);
9122            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9123            String apkName = getNextCodePath(null, pkgName, ".apk");
9124            codeFileName = new File(installDir, apkName + ".apk").getPath();
9125            resourceFileName = getResourcePathFromCodePath();
9126            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
9127        }
9128
9129        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9130            final long lowThreshold;
9131
9132            final DeviceStorageMonitorInternal
9133                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9134            if (dsm == null) {
9135                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9136                lowThreshold = 0L;
9137            } else {
9138                if (dsm.isMemoryLow()) {
9139                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9140                    return false;
9141                }
9142
9143                lowThreshold = dsm.getMemoryLowThreshold();
9144            }
9145
9146            try {
9147                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9148                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9149                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
9150            } finally {
9151                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9152            }
9153        }
9154
9155        String getCodePath() {
9156            return codeFileName;
9157        }
9158
9159        void createCopyFile() {
9160            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9161            codeFileName = createTempPackageFile(installDir).getPath();
9162            resourceFileName = getResourcePathFromCodePath();
9163            libraryPath = getLibraryPathFromCodePath();
9164            created = true;
9165        }
9166
9167        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9168            if (temp) {
9169                // Generate temp file name
9170                createCopyFile();
9171            }
9172            // Get a ParcelFileDescriptor to write to the output file
9173            File codeFile = new File(codeFileName);
9174            if (!created) {
9175                try {
9176                    codeFile.createNewFile();
9177                    // Set permissions
9178                    if (!setPermissions()) {
9179                        // Failed setting permissions.
9180                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9181                    }
9182                } catch (IOException e) {
9183                   Slog.w(TAG, "Failed to create file " + codeFile);
9184                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9185                }
9186            }
9187            ParcelFileDescriptor out = null;
9188            try {
9189                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
9190            } catch (FileNotFoundException e) {
9191                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
9192                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9193            }
9194            // Copy the resource now
9195            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9196            try {
9197                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9198                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9199                ret = imcs.copyResource(packageURI, null, out);
9200            } finally {
9201                IoUtils.closeQuietly(out);
9202                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9203            }
9204
9205            if (isFwdLocked()) {
9206                final File destResourceFile = new File(getResourcePath());
9207
9208                // Copy the public files
9209                try {
9210                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
9211                } catch (IOException e) {
9212                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
9213                            + " forward-locked app.");
9214                    destResourceFile.delete();
9215                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9216                }
9217            }
9218
9219            final File nativeLibraryFile = new File(getNativeLibraryPath());
9220            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
9221            if (nativeLibraryFile.exists()) {
9222                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9223                nativeLibraryFile.delete();
9224            }
9225
9226            final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(codeFile);
9227            String[] abiList = (abiOverride != null) ?
9228                    new String[] { abiOverride } : Build.SUPPORTED_ABIS;
9229            try {
9230                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
9231                        abiOverride == null &&
9232                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9233                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9234                }
9235
9236                int copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList);
9237                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9238                    return copyRet;
9239                }
9240            } catch (IOException e) {
9241                Slog.e(TAG, "Copying native libraries failed", e);
9242                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9243            } finally {
9244                handle.close();
9245            }
9246
9247            return ret;
9248        }
9249
9250        int doPreInstall(int status) {
9251            if (status != PackageManager.INSTALL_SUCCEEDED) {
9252                cleanUp();
9253            }
9254            return status;
9255        }
9256
9257        boolean doRename(int status, final String pkgName, String oldCodePath) {
9258            if (status != PackageManager.INSTALL_SUCCEEDED) {
9259                cleanUp();
9260                return false;
9261            } else {
9262                final File oldCodeFile = new File(getCodePath());
9263                final File oldResourceFile = new File(getResourcePath());
9264                final File oldLibraryFile = new File(getNativeLibraryPath());
9265
9266                // Rename APK file based on packageName
9267                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
9268                final File newCodeFile = new File(installDir, apkName + ".apk");
9269                if (!oldCodeFile.renameTo(newCodeFile)) {
9270                    return false;
9271                }
9272                codeFileName = newCodeFile.getPath();
9273
9274                // Rename public resource file if it's forward-locked.
9275                final File newResFile = new File(getResourcePathFromCodePath());
9276                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
9277                    return false;
9278                }
9279                resourceFileName = newResFile.getPath();
9280
9281                // Rename library path
9282                final File newLibraryFile = new File(getLibraryPathFromCodePath());
9283                if (newLibraryFile.exists()) {
9284                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
9285                    newLibraryFile.delete();
9286                }
9287                if (!oldLibraryFile.renameTo(newLibraryFile)) {
9288                    Slog.e(TAG, "Cannot rename native library directory "
9289                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
9290                    return false;
9291                }
9292                libraryPath = newLibraryFile.getPath();
9293
9294                // Attempt to set permissions
9295                if (!setPermissions()) {
9296                    return false;
9297                }
9298
9299                if (!SELinux.restorecon(newCodeFile)) {
9300                    return false;
9301                }
9302
9303                return true;
9304            }
9305        }
9306
9307        int doPostInstall(int status, int uid) {
9308            if (status != PackageManager.INSTALL_SUCCEEDED) {
9309                cleanUp();
9310            }
9311            return status;
9312        }
9313
9314        String getResourcePath() {
9315            return resourceFileName;
9316        }
9317
9318        private String getResourcePathFromCodePath() {
9319            final String codePath = getCodePath();
9320            if (isFwdLocked()) {
9321                final StringBuilder sb = new StringBuilder();
9322
9323                sb.append(mAppInstallDir.getPath());
9324                sb.append('/');
9325                sb.append(getApkName(codePath));
9326                sb.append(".zip");
9327
9328                /*
9329                 * If our APK is a temporary file, mark the resource as a
9330                 * temporary file as well so it can be cleaned up after
9331                 * catastrophic failure.
9332                 */
9333                if (codePath.endsWith(".tmp")) {
9334                    sb.append(".tmp");
9335                }
9336
9337                return sb.toString();
9338            } else {
9339                return codePath;
9340            }
9341        }
9342
9343        private String getLibraryPathFromCodePath() {
9344            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
9345        }
9346
9347        @Override
9348        String getNativeLibraryPath() {
9349            if (libraryPath == null) {
9350                libraryPath = getLibraryPathFromCodePath();
9351            }
9352            return libraryPath;
9353        }
9354
9355        private boolean cleanUp() {
9356            boolean ret = true;
9357            String sourceDir = getCodePath();
9358            String publicSourceDir = getResourcePath();
9359            if (sourceDir != null) {
9360                File sourceFile = new File(sourceDir);
9361                if (!sourceFile.exists()) {
9362                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
9363                    ret = false;
9364                }
9365                // Delete application's code and resources
9366                sourceFile.delete();
9367            }
9368            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
9369                final File publicSourceFile = new File(publicSourceDir);
9370                if (!publicSourceFile.exists()) {
9371                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
9372                }
9373                if (publicSourceFile.exists()) {
9374                    publicSourceFile.delete();
9375                }
9376            }
9377
9378            if (libraryPath != null) {
9379                File nativeLibraryFile = new File(libraryPath);
9380                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9381                if (!nativeLibraryFile.delete()) {
9382                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
9383                }
9384            }
9385
9386            return ret;
9387        }
9388
9389        void cleanUpResourcesLI() {
9390            String sourceDir = getCodePath();
9391            if (cleanUp()) {
9392                if (instructionSet == null) {
9393                    throw new IllegalStateException("instructionSet == null");
9394                }
9395                int retCode = mInstaller.rmdex(sourceDir, instructionSet);
9396                if (retCode < 0) {
9397                    Slog.w(TAG, "Couldn't remove dex file for package: "
9398                            +  " at location "
9399                            + sourceDir + ", retcode=" + retCode);
9400                    // we don't consider this to be a failure of the core package deletion
9401                }
9402            }
9403        }
9404
9405        private boolean setPermissions() {
9406            // TODO Do this in a more elegant way later on. for now just a hack
9407            if (!isFwdLocked()) {
9408                final int filePermissions =
9409                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
9410                    |FileUtils.S_IROTH;
9411                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
9412                if (retCode != 0) {
9413                    Slog.e(TAG, "Couldn't set new package file permissions for " +
9414                            getCodePath()
9415                            + ". The return code was: " + retCode);
9416                    // TODO Define new internal error
9417                    return false;
9418                }
9419                return true;
9420            }
9421            return true;
9422        }
9423
9424        boolean doPostDeleteLI(boolean delete) {
9425            // XXX err, shouldn't we respect the delete flag?
9426            cleanUpResourcesLI();
9427            return true;
9428        }
9429    }
9430
9431    private boolean isAsecExternal(String cid) {
9432        final String asecPath = PackageHelper.getSdFilesystem(cid);
9433        return !asecPath.startsWith(mAsecInternalPath);
9434    }
9435
9436    /**
9437     * Extract the MountService "container ID" from the full code path of an
9438     * .apk.
9439     */
9440    static String cidFromCodePath(String fullCodePath) {
9441        int eidx = fullCodePath.lastIndexOf("/");
9442        String subStr1 = fullCodePath.substring(0, eidx);
9443        int sidx = subStr1.lastIndexOf("/");
9444        return subStr1.substring(sidx+1, eidx);
9445    }
9446
9447    class AsecInstallArgs extends InstallArgs {
9448        static final String RES_FILE_NAME = "pkg.apk";
9449        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9450
9451        String cid;
9452        String packagePath;
9453        String resourcePath;
9454        String libraryPath;
9455
9456        AsecInstallArgs(InstallParams params) {
9457            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9458                    params.installerPackageName, params.getManifestDigest(),
9459                    params.getUser(), params.packageInstructionSetOverride,
9460                    params.packageAbiOverride);
9461        }
9462
9463        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9464                String instructionSet, boolean isExternal, boolean isForwardLocked) {
9465            super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9466                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9467                    null, null, null, instructionSet, null);
9468            // Extract cid from fullCodePath
9469            int eidx = fullCodePath.lastIndexOf("/");
9470            String subStr1 = fullCodePath.substring(0, eidx);
9471            int sidx = subStr1.lastIndexOf("/");
9472            cid = subStr1.substring(sidx+1, eidx);
9473            setCachePath(subStr1);
9474        }
9475
9476        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
9477            super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
9478                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9479                    null, null, null, instructionSet, null);
9480            this.cid = cid;
9481            setCachePath(PackageHelper.getSdDir(cid));
9482        }
9483
9484        AsecInstallArgs(Uri packageURI, String cid, String instructionSet,
9485                boolean isExternal, boolean isForwardLocked) {
9486            super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9487                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9488                    null, null, null, instructionSet, null);
9489            this.cid = cid;
9490        }
9491
9492        void createCopyFile() {
9493            cid = getTempContainerId();
9494        }
9495
9496        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9497            try {
9498                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9499                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9500                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked(), abiOverride);
9501            } finally {
9502                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9503            }
9504        }
9505
9506        private final boolean isExternal() {
9507            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9508        }
9509
9510        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9511            if (temp) {
9512                createCopyFile();
9513            } else {
9514                /*
9515                 * Pre-emptively destroy the container since it's destroyed if
9516                 * copying fails due to it existing anyway.
9517                 */
9518                PackageHelper.destroySdDir(cid);
9519            }
9520
9521            final String newCachePath;
9522            try {
9523                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9524                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9525                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
9526                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked(),
9527                        abiOverride);
9528            } finally {
9529                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9530            }
9531
9532            if (newCachePath != null) {
9533                setCachePath(newCachePath);
9534                return PackageManager.INSTALL_SUCCEEDED;
9535            } else {
9536                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9537            }
9538        }
9539
9540        @Override
9541        String getCodePath() {
9542            return packagePath;
9543        }
9544
9545        @Override
9546        String getResourcePath() {
9547            return resourcePath;
9548        }
9549
9550        @Override
9551        String getNativeLibraryPath() {
9552            return libraryPath;
9553        }
9554
9555        int doPreInstall(int status) {
9556            if (status != PackageManager.INSTALL_SUCCEEDED) {
9557                // Destroy container
9558                PackageHelper.destroySdDir(cid);
9559            } else {
9560                boolean mounted = PackageHelper.isContainerMounted(cid);
9561                if (!mounted) {
9562                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9563                            Process.SYSTEM_UID);
9564                    if (newCachePath != null) {
9565                        setCachePath(newCachePath);
9566                    } else {
9567                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9568                    }
9569                }
9570            }
9571            return status;
9572        }
9573
9574        boolean doRename(int status, final String pkgName,
9575                String oldCodePath) {
9576            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
9577            String newCachePath = null;
9578            if (PackageHelper.isContainerMounted(cid)) {
9579                // Unmount the container
9580                if (!PackageHelper.unMountSdDir(cid)) {
9581                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9582                    return false;
9583                }
9584            }
9585            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9586                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9587                        " which might be stale. Will try to clean up.");
9588                // Clean up the stale container and proceed to recreate.
9589                if (!PackageHelper.destroySdDir(newCacheId)) {
9590                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9591                    return false;
9592                }
9593                // Successfully cleaned up stale container. Try to rename again.
9594                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9595                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9596                            + " inspite of cleaning it up.");
9597                    return false;
9598                }
9599            }
9600            if (!PackageHelper.isContainerMounted(newCacheId)) {
9601                Slog.w(TAG, "Mounting container " + newCacheId);
9602                newCachePath = PackageHelper.mountSdDir(newCacheId,
9603                        getEncryptKey(), Process.SYSTEM_UID);
9604            } else {
9605                newCachePath = PackageHelper.getSdDir(newCacheId);
9606            }
9607            if (newCachePath == null) {
9608                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9609                return false;
9610            }
9611            Log.i(TAG, "Succesfully renamed " + cid +
9612                    " to " + newCacheId +
9613                    " at new path: " + newCachePath);
9614            cid = newCacheId;
9615            setCachePath(newCachePath);
9616            return true;
9617        }
9618
9619        private void setCachePath(String newCachePath) {
9620            File cachePath = new File(newCachePath);
9621            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
9622            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9623
9624            if (isFwdLocked()) {
9625                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9626            } else {
9627                resourcePath = packagePath;
9628            }
9629        }
9630
9631        int doPostInstall(int status, int uid) {
9632            if (status != PackageManager.INSTALL_SUCCEEDED) {
9633                cleanUp();
9634            } else {
9635                final int groupOwner;
9636                final String protectedFile;
9637                if (isFwdLocked()) {
9638                    groupOwner = UserHandle.getSharedAppGid(uid);
9639                    protectedFile = RES_FILE_NAME;
9640                } else {
9641                    groupOwner = -1;
9642                    protectedFile = null;
9643                }
9644
9645                if (uid < Process.FIRST_APPLICATION_UID
9646                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9647                    Slog.e(TAG, "Failed to finalize " + cid);
9648                    PackageHelper.destroySdDir(cid);
9649                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9650                }
9651
9652                boolean mounted = PackageHelper.isContainerMounted(cid);
9653                if (!mounted) {
9654                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9655                }
9656            }
9657            return status;
9658        }
9659
9660        private void cleanUp() {
9661            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9662
9663            // Destroy secure container
9664            PackageHelper.destroySdDir(cid);
9665        }
9666
9667        void cleanUpResourcesLI() {
9668            String sourceFile = getCodePath();
9669            // Remove dex file
9670            if (instructionSet == null) {
9671                throw new IllegalStateException("instructionSet == null");
9672            }
9673            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9674            if (retCode < 0) {
9675                Slog.w(TAG, "Couldn't remove dex file for package: "
9676                        + " at location "
9677                        + sourceFile.toString() + ", retcode=" + retCode);
9678                // we don't consider this to be a failure of the core package deletion
9679            }
9680            cleanUp();
9681        }
9682
9683        boolean matchContainer(String app) {
9684            if (cid.startsWith(app)) {
9685                return true;
9686            }
9687            return false;
9688        }
9689
9690        String getPackageName() {
9691            return getAsecPackageName(cid);
9692        }
9693
9694        boolean doPostDeleteLI(boolean delete) {
9695            boolean ret = false;
9696            boolean mounted = PackageHelper.isContainerMounted(cid);
9697            if (mounted) {
9698                // Unmount first
9699                ret = PackageHelper.unMountSdDir(cid);
9700            }
9701            if (ret && delete) {
9702                cleanUpResourcesLI();
9703            }
9704            return ret;
9705        }
9706
9707        @Override
9708        int doPreCopy() {
9709            if (isFwdLocked()) {
9710                if (!PackageHelper.fixSdPermissions(cid,
9711                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9712                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9713                }
9714            }
9715
9716            return PackageManager.INSTALL_SUCCEEDED;
9717        }
9718
9719        @Override
9720        int doPostCopy(int uid) {
9721            if (isFwdLocked()) {
9722                if (uid < Process.FIRST_APPLICATION_UID
9723                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9724                                RES_FILE_NAME)) {
9725                    Slog.e(TAG, "Failed to finalize " + cid);
9726                    PackageHelper.destroySdDir(cid);
9727                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9728                }
9729            }
9730
9731            return PackageManager.INSTALL_SUCCEEDED;
9732        }
9733    };
9734
9735    static String getAsecPackageName(String packageCid) {
9736        int idx = packageCid.lastIndexOf("-");
9737        if (idx == -1) {
9738            return packageCid;
9739        }
9740        return packageCid.substring(0, idx);
9741    }
9742
9743    // Utility method used to create code paths based on package name and available index.
9744    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9745        String idxStr = "";
9746        int idx = 1;
9747        // Fall back to default value of idx=1 if prefix is not
9748        // part of oldCodePath
9749        if (oldCodePath != null) {
9750            String subStr = oldCodePath;
9751            // Drop the suffix right away
9752            if (subStr.endsWith(suffix)) {
9753                subStr = subStr.substring(0, subStr.length() - suffix.length());
9754            }
9755            // If oldCodePath already contains prefix find out the
9756            // ending index to either increment or decrement.
9757            int sidx = subStr.lastIndexOf(prefix);
9758            if (sidx != -1) {
9759                subStr = subStr.substring(sidx + prefix.length());
9760                if (subStr != null) {
9761                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9762                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9763                    }
9764                    try {
9765                        idx = Integer.parseInt(subStr);
9766                        if (idx <= 1) {
9767                            idx++;
9768                        } else {
9769                            idx--;
9770                        }
9771                    } catch(NumberFormatException e) {
9772                    }
9773                }
9774            }
9775        }
9776        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9777        return prefix + idxStr;
9778    }
9779
9780    // Utility method used to ignore ADD/REMOVE events
9781    // by directory observer.
9782    private static boolean ignoreCodePath(String fullPathStr) {
9783        String apkName = getApkName(fullPathStr);
9784        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9785        if (idx != -1 && ((idx+1) < apkName.length())) {
9786            // Make sure the package ends with a numeral
9787            String version = apkName.substring(idx+1);
9788            try {
9789                Integer.parseInt(version);
9790                return true;
9791            } catch (NumberFormatException e) {}
9792        }
9793        return false;
9794    }
9795
9796    // Utility method that returns the relative package path with respect
9797    // to the installation directory. Like say for /data/data/com.test-1.apk
9798    // string com.test-1 is returned.
9799    static String getApkName(String codePath) {
9800        if (codePath == null) {
9801            return null;
9802        }
9803        int sidx = codePath.lastIndexOf("/");
9804        int eidx = codePath.lastIndexOf(".");
9805        if (eidx == -1) {
9806            eidx = codePath.length();
9807        } else if (eidx == 0) {
9808            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
9809            return null;
9810        }
9811        return codePath.substring(sidx+1, eidx);
9812    }
9813
9814    class PackageInstalledInfo {
9815        String name;
9816        int uid;
9817        // The set of users that originally had this package installed.
9818        int[] origUsers;
9819        // The set of users that now have this package installed.
9820        int[] newUsers;
9821        PackageParser.Package pkg;
9822        int returnCode;
9823        PackageRemovedInfo removedInfo;
9824
9825        // In some error cases we want to convey more info back to the observer
9826        String origPackage;
9827        String origPermission;
9828    }
9829
9830    /*
9831     * Install a non-existing package.
9832     */
9833    private void installNewPackageLI(PackageParser.Package pkg,
9834            int parseFlags, int scanMode, UserHandle user,
9835            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9836        // Remember this for later, in case we need to rollback this install
9837        String pkgName = pkg.packageName;
9838
9839        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9840        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9841        synchronized(mPackages) {
9842            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9843                // A package with the same name is already installed, though
9844                // it has been renamed to an older name.  The package we
9845                // are trying to install should be installed as an update to
9846                // the existing one, but that has not been requested, so bail.
9847                Slog.w(TAG, "Attempt to re-install " + pkgName
9848                        + " without first uninstalling package running as "
9849                        + mSettings.mRenamedPackages.get(pkgName));
9850                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9851                return;
9852            }
9853            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
9854                // Don't allow installation over an existing package with the same name.
9855                Slog.w(TAG, "Attempt to re-install " + pkgName
9856                        + " without first uninstalling.");
9857                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9858                return;
9859            }
9860        }
9861        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9862        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9863                System.currentTimeMillis(), user, abiOverride);
9864        if (newPackage == null) {
9865            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9866            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9867                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9868            }
9869        } else {
9870            updateSettingsLI(newPackage,
9871                    installerPackageName,
9872                    null, null,
9873                    res);
9874            // delete the partially installed application. the data directory will have to be
9875            // restored if it was already existing
9876            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9877                // remove package from internal structures.  Note that we want deletePackageX to
9878                // delete the package data and cache directories that it created in
9879                // scanPackageLocked, unless those directories existed before we even tried to
9880                // install.
9881                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9882                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9883                                res.removedInfo, true);
9884            }
9885        }
9886    }
9887
9888    private void replacePackageLI(PackageParser.Package pkg,
9889            int parseFlags, int scanMode, UserHandle user,
9890            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9891
9892        PackageParser.Package oldPackage;
9893        String pkgName = pkg.packageName;
9894        int[] allUsers;
9895        boolean[] perUserInstalled;
9896
9897        // First find the old package info and check signatures
9898        synchronized(mPackages) {
9899            oldPackage = mPackages.get(pkgName);
9900            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9901            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9902                    != PackageManager.SIGNATURE_MATCH) {
9903                Slog.w(TAG, "New package has a different signature: " + pkgName);
9904                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9905                return;
9906            }
9907
9908            // In case of rollback, remember per-user/profile install state
9909            PackageSetting ps = mSettings.mPackages.get(pkgName);
9910            allUsers = sUserManager.getUserIds();
9911            perUserInstalled = new boolean[allUsers.length];
9912            for (int i = 0; i < allUsers.length; i++) {
9913                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9914            }
9915        }
9916        boolean sysPkg = (isSystemApp(oldPackage));
9917        if (sysPkg) {
9918            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9919                    user, allUsers, perUserInstalled, installerPackageName, res,
9920                    abiOverride);
9921        } else {
9922            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9923                    user, allUsers, perUserInstalled, installerPackageName, res,
9924                    abiOverride);
9925        }
9926    }
9927
9928    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9929            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9930            int[] allUsers, boolean[] perUserInstalled,
9931            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9932        PackageParser.Package newPackage = null;
9933        String pkgName = deletedPackage.packageName;
9934        boolean deletedPkg = true;
9935        boolean updatedSettings = false;
9936
9937        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9938                + deletedPackage);
9939        long origUpdateTime;
9940        if (pkg.mExtras != null) {
9941            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9942        } else {
9943            origUpdateTime = 0;
9944        }
9945
9946        // First delete the existing package while retaining the data directory
9947        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9948                res.removedInfo, true)) {
9949            // If the existing package wasn't successfully deleted
9950            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9951            deletedPkg = false;
9952        } else {
9953            // Successfully deleted the old package. Now proceed with re-installation
9954            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9955            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9956                    System.currentTimeMillis(), user, abiOverride);
9957            if (newPackage == null) {
9958                Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9959                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9960                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9961                }
9962            } else {
9963                updateSettingsLI(newPackage,
9964                        installerPackageName,
9965                        allUsers, perUserInstalled,
9966                        res);
9967                updatedSettings = true;
9968            }
9969        }
9970
9971        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9972            // remove package from internal structures.  Note that we want deletePackageX to
9973            // delete the package data and cache directories that it created in
9974            // scanPackageLocked, unless those directories existed before we even tried to
9975            // install.
9976            if(updatedSettings) {
9977                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9978                deletePackageLI(
9979                        pkgName, null, true, allUsers, perUserInstalled,
9980                        PackageManager.DELETE_KEEP_DATA,
9981                                res.removedInfo, true);
9982            }
9983            // Since we failed to install the new package we need to restore the old
9984            // package that we deleted.
9985            if (deletedPkg) {
9986                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9987                File restoreFile = new File(deletedPackage.mPath);
9988                // Parse old package
9989                boolean oldOnSd = isExternal(deletedPackage);
9990                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9991                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9992                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9993                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9994                        | SCAN_UPDATE_TIME;
9995                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9996                        origUpdateTime, null, null) == null) {
9997                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9998                    return;
9999                }
10000                // Restore of old package succeeded. Update permissions.
10001                // writer
10002                synchronized (mPackages) {
10003                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10004                            UPDATE_PERMISSIONS_ALL);
10005                    // can downgrade to reader
10006                    mSettings.writeLPr();
10007                }
10008                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10009            }
10010        }
10011    }
10012
10013    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10014            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10015            int[] allUsers, boolean[] perUserInstalled,
10016            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
10017        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10018                + ", old=" + deletedPackage);
10019        PackageParser.Package newPackage = null;
10020        boolean updatedSettings = false;
10021        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
10022                PackageParser.PARSE_IS_SYSTEM;
10023        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10024            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10025        }
10026        String packageName = deletedPackage.packageName;
10027        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
10028        if (packageName == null) {
10029            Slog.w(TAG, "Attempt to delete null packageName.");
10030            return;
10031        }
10032        PackageParser.Package oldPkg;
10033        PackageSetting oldPkgSetting;
10034        // reader
10035        synchronized (mPackages) {
10036            oldPkg = mPackages.get(packageName);
10037            oldPkgSetting = mSettings.mPackages.get(packageName);
10038            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10039                    (oldPkgSetting == null)) {
10040                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
10041                return;
10042            }
10043        }
10044
10045        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10046
10047        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10048        res.removedInfo.removedPackage = packageName;
10049        // Remove existing system package
10050        removePackageLI(oldPkgSetting, true);
10051        // writer
10052        synchronized (mPackages) {
10053            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10054                // We didn't need to disable the .apk as a current system package,
10055                // which means we are replacing another update that is already
10056                // installed.  We need to make sure to delete the older one's .apk.
10057                res.removedInfo.args = createInstallArgs(0,
10058                        deletedPackage.applicationInfo.sourceDir,
10059                        deletedPackage.applicationInfo.publicSourceDir,
10060                        deletedPackage.applicationInfo.nativeLibraryDir,
10061                        getAppInstructionSet(deletedPackage.applicationInfo));
10062            } else {
10063                res.removedInfo.args = null;
10064            }
10065        }
10066
10067        // Successfully disabled the old package. Now proceed with re-installation
10068        res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED;
10069        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10070        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride);
10071        if (newPackage == null) {
10072            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
10073            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
10074                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
10075            }
10076        } else {
10077            if (newPackage.mExtras != null) {
10078                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
10079                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10080                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10081
10082                // is the update attempting to change shared user? that isn't going to work...
10083                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10084                    Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser
10085                            + " to " + newPkgSetting.sharedUser);
10086                    res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
10087                    updatedSettings = true;
10088                }
10089            }
10090
10091            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10092                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10093                updatedSettings = true;
10094            }
10095        }
10096
10097        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10098            // Re installation failed. Restore old information
10099            // Remove new pkg information
10100            if (newPackage != null) {
10101                removeInstalledPackageLI(newPackage, true);
10102            }
10103            // Add back the old system package
10104            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null);
10105            // Restore the old system information in Settings
10106            synchronized(mPackages) {
10107                if (updatedSettings) {
10108                    mSettings.enableSystemPackageLPw(packageName);
10109                    mSettings.setInstallerPackageName(packageName,
10110                            oldPkgSetting.installerPackageName);
10111                }
10112                mSettings.writeLPr();
10113            }
10114        }
10115    }
10116
10117    // Utility method used to move dex files during install.
10118    private int moveDexFilesLI(PackageParser.Package newPackage) {
10119        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10120            final String instructionSet = getAppInstructionSet(newPackage.applicationInfo);
10121            int retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath,
10122                                             instructionSet);
10123            if (retCode != 0) {
10124                /*
10125                 * Programs may be lazily run through dexopt, so the
10126                 * source may not exist. However, something seems to
10127                 * have gone wrong, so note that dexopt needs to be
10128                 * run again and remove the source file. In addition,
10129                 * remove the target to make sure there isn't a stale
10130                 * file from a previous version of the package.
10131                 */
10132                newPackage.mDexOptNeeded = true;
10133                mInstaller.rmdex(newPackage.mScanPath, instructionSet);
10134                mInstaller.rmdex(newPackage.mPath, instructionSet);
10135            }
10136        }
10137        return PackageManager.INSTALL_SUCCEEDED;
10138    }
10139
10140    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10141            int[] allUsers, boolean[] perUserInstalled,
10142            PackageInstalledInfo res) {
10143        String pkgName = newPackage.packageName;
10144        synchronized (mPackages) {
10145            //write settings. the installStatus will be incomplete at this stage.
10146            //note that the new package setting would have already been
10147            //added to mPackages. It hasn't been persisted yet.
10148            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10149            mSettings.writeLPr();
10150        }
10151
10152        if ((res.returnCode = moveDexFilesLI(newPackage))
10153                != PackageManager.INSTALL_SUCCEEDED) {
10154            // Discontinue if moving dex files failed.
10155            return;
10156        }
10157
10158        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath);
10159
10160        synchronized (mPackages) {
10161            updatePermissionsLPw(newPackage.packageName, newPackage,
10162                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10163                            ? UPDATE_PERMISSIONS_ALL : 0));
10164            // For system-bundled packages, we assume that installing an upgraded version
10165            // of the package implies that the user actually wants to run that new code,
10166            // so we enable the package.
10167            if (isSystemApp(newPackage)) {
10168                // NB: implicit assumption that system package upgrades apply to all users
10169                if (DEBUG_INSTALL) {
10170                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10171                }
10172                PackageSetting ps = mSettings.mPackages.get(pkgName);
10173                if (ps != null) {
10174                    if (res.origUsers != null) {
10175                        for (int userHandle : res.origUsers) {
10176                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10177                                    userHandle, installerPackageName);
10178                        }
10179                    }
10180                    // Also convey the prior install/uninstall state
10181                    if (allUsers != null && perUserInstalled != null) {
10182                        for (int i = 0; i < allUsers.length; i++) {
10183                            if (DEBUG_INSTALL) {
10184                                Slog.d(TAG, "    user " + allUsers[i]
10185                                        + " => " + perUserInstalled[i]);
10186                            }
10187                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10188                        }
10189                        // these install state changes will be persisted in the
10190                        // upcoming call to mSettings.writeLPr().
10191                    }
10192                }
10193            }
10194            res.name = pkgName;
10195            res.uid = newPackage.applicationInfo.uid;
10196            res.pkg = newPackage;
10197            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10198            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10199            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10200            //to update install status
10201            mSettings.writeLPr();
10202        }
10203    }
10204
10205    private void installPackageLI(InstallArgs args,
10206            boolean newInstall, PackageInstalledInfo res) {
10207        int pFlags = args.flags;
10208        String installerPackageName = args.installerPackageName;
10209        File tmpPackageFile = new File(args.getCodePath());
10210        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10211        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10212        boolean replace = false;
10213        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10214                | (newInstall ? SCAN_NEW_INSTALL : 0);
10215        // Result object to be returned
10216        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10217
10218        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10219        // Retrieve PackageSettings and parse package
10220        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10221                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10222                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10223        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
10224        pp.setSeparateProcesses(mSeparateProcesses);
10225        final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
10226                null, mMetrics, parseFlags);
10227        if (pkg == null) {
10228            res.returnCode = pp.getParseError();
10229            return;
10230        }
10231        String pkgName = res.name = pkg.packageName;
10232        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10233            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10234                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
10235                return;
10236            }
10237        }
10238        if (!pp.collectCertificates(pkg, parseFlags)) {
10239            res.returnCode = pp.getParseError();
10240            return;
10241        }
10242
10243        /* If the installer passed in a manifest digest, compare it now. */
10244        if (args.manifestDigest != null) {
10245            if (DEBUG_INSTALL) {
10246                final String parsedManifest = pkg.manifestDigest == null ? "null"
10247                        : pkg.manifestDigest.toString();
10248                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10249                        + parsedManifest);
10250            }
10251
10252            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10253                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
10254                return;
10255            }
10256        } else if (DEBUG_INSTALL) {
10257            final String parsedManifest = pkg.manifestDigest == null
10258                    ? "null" : pkg.manifestDigest.toString();
10259            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10260        }
10261
10262        // Get rid of all references to package scan path via parser.
10263        pp = null;
10264        String oldCodePath = null;
10265        boolean systemApp = false;
10266        synchronized (mPackages) {
10267            // Check whether the newly-scanned package wants to define an already-defined perm
10268            int N = pkg.permissions.size();
10269            for (int i = 0; i < N; i++) {
10270                PackageParser.Permission perm = pkg.permissions.get(i);
10271                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10272                if (bp != null) {
10273                    // If the defining package is signed with our cert, it's okay.  This
10274                    // also includes the "updating the same package" case, of course.
10275                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10276                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10277                        Slog.w(TAG, "Package " + pkg.packageName
10278                                + " attempting to redeclare permission " + perm.info.name
10279                                + " already owned by " + bp.sourcePackage);
10280                        res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
10281                        res.origPermission = perm.info.name;
10282                        res.origPackage = bp.sourcePackage;
10283                        return;
10284                    }
10285                }
10286            }
10287
10288            // Check if installing already existing package
10289            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10290                String oldName = mSettings.mRenamedPackages.get(pkgName);
10291                if (pkg.mOriginalPackages != null
10292                        && pkg.mOriginalPackages.contains(oldName)
10293                        && mPackages.containsKey(oldName)) {
10294                    // This package is derived from an original package,
10295                    // and this device has been updating from that original
10296                    // name.  We must continue using the original name, so
10297                    // rename the new package here.
10298                    pkg.setPackageName(oldName);
10299                    pkgName = pkg.packageName;
10300                    replace = true;
10301                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10302                            + oldName + " pkgName=" + pkgName);
10303                } else if (mPackages.containsKey(pkgName)) {
10304                    // This package, under its official name, already exists
10305                    // on the device; we should replace it.
10306                    replace = true;
10307                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10308                }
10309            }
10310            PackageSetting ps = mSettings.mPackages.get(pkgName);
10311            if (ps != null) {
10312                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10313                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10314                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10315                    systemApp = (ps.pkg.applicationInfo.flags &
10316                            ApplicationInfo.FLAG_SYSTEM) != 0;
10317                }
10318                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10319            }
10320        }
10321
10322        if (systemApp && onSd) {
10323            // Disable updates to system apps on sdcard
10324            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
10325            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10326            return;
10327        }
10328
10329        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
10330            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10331            return;
10332        }
10333        // Set application objects path explicitly after the rename
10334        setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
10335        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
10336        if (replace) {
10337            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10338                    installerPackageName, res, args.abiOverride);
10339        } else {
10340            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10341                    installerPackageName, res, args.abiOverride);
10342        }
10343        synchronized (mPackages) {
10344            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10345            if (ps != null) {
10346                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10347            }
10348        }
10349    }
10350
10351    private static boolean isForwardLocked(PackageParser.Package pkg) {
10352        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10353    }
10354
10355
10356    private boolean isForwardLocked(PackageSetting ps) {
10357        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10358    }
10359
10360    private static boolean isExternal(PackageParser.Package pkg) {
10361        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10362    }
10363
10364    private static boolean isExternal(PackageSetting ps) {
10365        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10366    }
10367
10368    private static boolean isSystemApp(PackageParser.Package pkg) {
10369        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10370    }
10371
10372    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10373        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10374    }
10375
10376    private static boolean isSystemApp(ApplicationInfo info) {
10377        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10378    }
10379
10380    private static boolean isSystemApp(PackageSetting ps) {
10381        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10382    }
10383
10384    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10385        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10386    }
10387
10388    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10389        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10390    }
10391
10392    private int packageFlagsToInstallFlags(PackageSetting ps) {
10393        int installFlags = 0;
10394        if (isExternal(ps)) {
10395            installFlags |= PackageManager.INSTALL_EXTERNAL;
10396        }
10397        if (isForwardLocked(ps)) {
10398            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10399        }
10400        return installFlags;
10401    }
10402
10403    private void deleteTempPackageFiles() {
10404        final FilenameFilter filter = new FilenameFilter() {
10405            public boolean accept(File dir, String name) {
10406                return name.startsWith("vmdl") && name.endsWith(".tmp");
10407            }
10408        };
10409        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
10410        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
10411    }
10412
10413    private static final void deleteTempPackageFilesInDirectory(File directory,
10414            FilenameFilter filter) {
10415        final String[] tmpFilesList = directory.list(filter);
10416        if (tmpFilesList == null) {
10417            return;
10418        }
10419        for (int i = 0; i < tmpFilesList.length; i++) {
10420            final File tmpFile = new File(directory, tmpFilesList[i]);
10421            tmpFile.delete();
10422        }
10423    }
10424
10425    private File createTempPackageFile(File installDir) {
10426        File tmpPackageFile;
10427        try {
10428            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
10429        } catch (IOException e) {
10430            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
10431            return null;
10432        }
10433        try {
10434            FileUtils.setPermissions(
10435                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
10436                    -1, -1);
10437            if (!SELinux.restorecon(tmpPackageFile)) {
10438                return null;
10439            }
10440        } catch (IOException e) {
10441            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
10442            return null;
10443        }
10444        return tmpPackageFile;
10445    }
10446
10447    @Override
10448    public void deletePackageAsUser(final String packageName,
10449                                    final IPackageDeleteObserver observer,
10450                                    final int userId, final int flags) {
10451        mContext.enforceCallingOrSelfPermission(
10452                android.Manifest.permission.DELETE_PACKAGES, null);
10453        final int uid = Binder.getCallingUid();
10454        if (UserHandle.getUserId(uid) != userId) {
10455            mContext.enforceCallingPermission(
10456                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10457                    "deletePackage for user " + userId);
10458        }
10459        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10460            try {
10461                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10462            } catch (RemoteException re) {
10463            }
10464            return;
10465        }
10466
10467        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10468        // Queue up an async operation since the package deletion may take a little while.
10469        mHandler.post(new Runnable() {
10470            public void run() {
10471                mHandler.removeCallbacks(this);
10472                final int returnCode = deletePackageX(packageName, userId, flags);
10473                if (observer != null) {
10474                    try {
10475                        observer.packageDeleted(packageName, returnCode);
10476                    } catch (RemoteException e) {
10477                        Log.i(TAG, "Observer no longer exists.");
10478                    } //end catch
10479                } //end if
10480            } //end run
10481        });
10482    }
10483
10484    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10485        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10486                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10487        try {
10488            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10489                    || dpm.isDeviceOwner(packageName))) {
10490                return true;
10491            }
10492        } catch (RemoteException e) {
10493        }
10494        return false;
10495    }
10496
10497    /**
10498     *  This method is an internal method that could be get invoked either
10499     *  to delete an installed package or to clean up a failed installation.
10500     *  After deleting an installed package, a broadcast is sent to notify any
10501     *  listeners that the package has been installed. For cleaning up a failed
10502     *  installation, the broadcast is not necessary since the package's
10503     *  installation wouldn't have sent the initial broadcast either
10504     *  The key steps in deleting a package are
10505     *  deleting the package information in internal structures like mPackages,
10506     *  deleting the packages base directories through installd
10507     *  updating mSettings to reflect current status
10508     *  persisting settings for later use
10509     *  sending a broadcast if necessary
10510     */
10511    private int deletePackageX(String packageName, int userId, int flags) {
10512        final PackageRemovedInfo info = new PackageRemovedInfo();
10513        final boolean res;
10514
10515        if (isPackageDeviceAdmin(packageName, userId)) {
10516            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10517            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10518        }
10519
10520        boolean removedForAllUsers = false;
10521        boolean systemUpdate = false;
10522
10523        // for the uninstall-updates case and restricted profiles, remember the per-
10524        // userhandle installed state
10525        int[] allUsers;
10526        boolean[] perUserInstalled;
10527        synchronized (mPackages) {
10528            PackageSetting ps = mSettings.mPackages.get(packageName);
10529            allUsers = sUserManager.getUserIds();
10530            perUserInstalled = new boolean[allUsers.length];
10531            for (int i = 0; i < allUsers.length; i++) {
10532                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10533            }
10534        }
10535
10536        synchronized (mInstallLock) {
10537            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10538            res = deletePackageLI(packageName,
10539                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10540                            ? UserHandle.ALL : new UserHandle(userId),
10541                    true, allUsers, perUserInstalled,
10542                    flags | REMOVE_CHATTY, info, true);
10543            systemUpdate = info.isRemovedPackageSystemUpdate;
10544            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10545                removedForAllUsers = true;
10546            }
10547            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10548                    + " removedForAllUsers=" + removedForAllUsers);
10549        }
10550
10551        if (res) {
10552            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10553
10554            // If the removed package was a system update, the old system package
10555            // was re-enabled; we need to broadcast this information
10556            if (systemUpdate) {
10557                Bundle extras = new Bundle(1);
10558                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10559                        ? info.removedAppId : info.uid);
10560                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10561
10562                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10563                        extras, null, null, null);
10564                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10565                        extras, null, null, null);
10566                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10567                        null, packageName, null, null);
10568            }
10569        }
10570        // Force a gc here.
10571        Runtime.getRuntime().gc();
10572        // Delete the resources here after sending the broadcast to let
10573        // other processes clean up before deleting resources.
10574        if (info.args != null) {
10575            synchronized (mInstallLock) {
10576                info.args.doPostDeleteLI(true);
10577            }
10578        }
10579
10580        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10581    }
10582
10583    static class PackageRemovedInfo {
10584        String removedPackage;
10585        int uid = -1;
10586        int removedAppId = -1;
10587        int[] removedUsers = null;
10588        boolean isRemovedPackageSystemUpdate = false;
10589        // Clean up resources deleted packages.
10590        InstallArgs args = null;
10591
10592        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10593            Bundle extras = new Bundle(1);
10594            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10595            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10596            if (replacing) {
10597                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10598            }
10599            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10600            if (removedPackage != null) {
10601                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10602                        extras, null, null, removedUsers);
10603                if (fullRemove && !replacing) {
10604                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10605                            extras, null, null, removedUsers);
10606                }
10607            }
10608            if (removedAppId >= 0) {
10609                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10610                        removedUsers);
10611            }
10612        }
10613    }
10614
10615    /*
10616     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10617     * flag is not set, the data directory is removed as well.
10618     * make sure this flag is set for partially installed apps. If not its meaningless to
10619     * delete a partially installed application.
10620     */
10621    private void removePackageDataLI(PackageSetting ps,
10622            int[] allUserHandles, boolean[] perUserInstalled,
10623            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10624        String packageName = ps.name;
10625        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10626        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10627        // Retrieve object to delete permissions for shared user later on
10628        final PackageSetting deletedPs;
10629        // reader
10630        synchronized (mPackages) {
10631            deletedPs = mSettings.mPackages.get(packageName);
10632            if (outInfo != null) {
10633                outInfo.removedPackage = packageName;
10634                outInfo.removedUsers = deletedPs != null
10635                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10636                        : null;
10637            }
10638        }
10639        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10640            removeDataDirsLI(packageName);
10641            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10642        }
10643        // writer
10644        synchronized (mPackages) {
10645            if (deletedPs != null) {
10646                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10647                    if (outInfo != null) {
10648                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10649                    }
10650                    if (deletedPs != null) {
10651                        updatePermissionsLPw(deletedPs.name, null, 0);
10652                        if (deletedPs.sharedUser != null) {
10653                            // remove permissions associated with package
10654                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10655                        }
10656                    }
10657                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10658                }
10659                // make sure to preserve per-user disabled state if this removal was just
10660                // a downgrade of a system app to the factory package
10661                if (allUserHandles != null && perUserInstalled != null) {
10662                    if (DEBUG_REMOVE) {
10663                        Slog.d(TAG, "Propagating install state across downgrade");
10664                    }
10665                    for (int i = 0; i < allUserHandles.length; i++) {
10666                        if (DEBUG_REMOVE) {
10667                            Slog.d(TAG, "    user " + allUserHandles[i]
10668                                    + " => " + perUserInstalled[i]);
10669                        }
10670                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10671                    }
10672                }
10673            }
10674            // can downgrade to reader
10675            if (writeSettings) {
10676                // Save settings now
10677                mSettings.writeLPr();
10678            }
10679        }
10680        if (outInfo != null) {
10681            // A user ID was deleted here. Go through all users and remove it
10682            // from KeyStore.
10683            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10684        }
10685    }
10686
10687    static boolean locationIsPrivileged(File path) {
10688        try {
10689            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10690                    .getCanonicalPath();
10691            return path.getCanonicalPath().startsWith(privilegedAppDir);
10692        } catch (IOException e) {
10693            Slog.e(TAG, "Unable to access code path " + path);
10694        }
10695        return false;
10696    }
10697
10698    /*
10699     * Tries to delete system package.
10700     */
10701    private boolean deleteSystemPackageLI(PackageSetting newPs,
10702            int[] allUserHandles, boolean[] perUserInstalled,
10703            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10704        final boolean applyUserRestrictions
10705                = (allUserHandles != null) && (perUserInstalled != null);
10706        PackageSetting disabledPs = null;
10707        // Confirm if the system package has been updated
10708        // An updated system app can be deleted. This will also have to restore
10709        // the system pkg from system partition
10710        // reader
10711        synchronized (mPackages) {
10712            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10713        }
10714        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10715                + " disabledPs=" + disabledPs);
10716        if (disabledPs == null) {
10717            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10718            return false;
10719        } else if (DEBUG_REMOVE) {
10720            Slog.d(TAG, "Deleting system pkg from data partition");
10721        }
10722        if (DEBUG_REMOVE) {
10723            if (applyUserRestrictions) {
10724                Slog.d(TAG, "Remembering install states:");
10725                for (int i = 0; i < allUserHandles.length; i++) {
10726                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10727                }
10728            }
10729        }
10730        // Delete the updated package
10731        outInfo.isRemovedPackageSystemUpdate = true;
10732        if (disabledPs.versionCode < newPs.versionCode) {
10733            // Delete data for downgrades
10734            flags &= ~PackageManager.DELETE_KEEP_DATA;
10735        } else {
10736            // Preserve data by setting flag
10737            flags |= PackageManager.DELETE_KEEP_DATA;
10738        }
10739        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10740                allUserHandles, perUserInstalled, outInfo, writeSettings);
10741        if (!ret) {
10742            return false;
10743        }
10744        // writer
10745        synchronized (mPackages) {
10746            // Reinstate the old system package
10747            mSettings.enableSystemPackageLPw(newPs.name);
10748            // Remove any native libraries from the upgraded package.
10749            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10750        }
10751        // Install the system package
10752        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10753        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10754        if (locationIsPrivileged(disabledPs.codePath)) {
10755            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10756        }
10757        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10758                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null);
10759
10760        if (newPkg == null) {
10761            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10762                    + " with error:" + mLastScanError);
10763            return false;
10764        }
10765        // writer
10766        synchronized (mPackages) {
10767            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10768            setInternalAppNativeLibraryPath(newPkg, ps);
10769            updatePermissionsLPw(newPkg.packageName, newPkg,
10770                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10771            if (applyUserRestrictions) {
10772                if (DEBUG_REMOVE) {
10773                    Slog.d(TAG, "Propagating install state across reinstall");
10774                }
10775                for (int i = 0; i < allUserHandles.length; i++) {
10776                    if (DEBUG_REMOVE) {
10777                        Slog.d(TAG, "    user " + allUserHandles[i]
10778                                + " => " + perUserInstalled[i]);
10779                    }
10780                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10781                }
10782                // Regardless of writeSettings we need to ensure that this restriction
10783                // state propagation is persisted
10784                mSettings.writeAllUsersPackageRestrictionsLPr();
10785            }
10786            // can downgrade to reader here
10787            if (writeSettings) {
10788                mSettings.writeLPr();
10789            }
10790        }
10791        return true;
10792    }
10793
10794    private boolean deleteInstalledPackageLI(PackageSetting ps,
10795            boolean deleteCodeAndResources, int flags,
10796            int[] allUserHandles, boolean[] perUserInstalled,
10797            PackageRemovedInfo outInfo, boolean writeSettings) {
10798        if (outInfo != null) {
10799            outInfo.uid = ps.appId;
10800        }
10801
10802        // Delete package data from internal structures and also remove data if flag is set
10803        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10804
10805        // Delete application code and resources
10806        if (deleteCodeAndResources && (outInfo != null)) {
10807            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
10808                    ps.resourcePathString, ps.nativeLibraryPathString,
10809                    getAppInstructionSetFromSettings(ps));
10810        }
10811        return true;
10812    }
10813
10814    /*
10815     * This method handles package deletion in general
10816     */
10817    private boolean deletePackageLI(String packageName, UserHandle user,
10818            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10819            int flags, PackageRemovedInfo outInfo,
10820            boolean writeSettings) {
10821        if (packageName == null) {
10822            Slog.w(TAG, "Attempt to delete null packageName.");
10823            return false;
10824        }
10825        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10826        PackageSetting ps;
10827        boolean dataOnly = false;
10828        int removeUser = -1;
10829        int appId = -1;
10830        synchronized (mPackages) {
10831            ps = mSettings.mPackages.get(packageName);
10832            if (ps == null) {
10833                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10834                return false;
10835            }
10836            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10837                    && user.getIdentifier() != UserHandle.USER_ALL) {
10838                // The caller is asking that the package only be deleted for a single
10839                // user.  To do this, we just mark its uninstalled state and delete
10840                // its data.  If this is a system app, we only allow this to happen if
10841                // they have set the special DELETE_SYSTEM_APP which requests different
10842                // semantics than normal for uninstalling system apps.
10843                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10844                ps.setUserState(user.getIdentifier(),
10845                        COMPONENT_ENABLED_STATE_DEFAULT,
10846                        false, //installed
10847                        true,  //stopped
10848                        true,  //notLaunched
10849                        false, //blocked
10850                        null, null, null);
10851                if (!isSystemApp(ps)) {
10852                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10853                        // Other user still have this package installed, so all
10854                        // we need to do is clear this user's data and save that
10855                        // it is uninstalled.
10856                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10857                        removeUser = user.getIdentifier();
10858                        appId = ps.appId;
10859                        mSettings.writePackageRestrictionsLPr(removeUser);
10860                    } else {
10861                        // We need to set it back to 'installed' so the uninstall
10862                        // broadcasts will be sent correctly.
10863                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10864                        ps.setInstalled(true, user.getIdentifier());
10865                    }
10866                } else {
10867                    // This is a system app, so we assume that the
10868                    // other users still have this package installed, so all
10869                    // we need to do is clear this user's data and save that
10870                    // it is uninstalled.
10871                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10872                    removeUser = user.getIdentifier();
10873                    appId = ps.appId;
10874                    mSettings.writePackageRestrictionsLPr(removeUser);
10875                }
10876            }
10877        }
10878
10879        if (removeUser >= 0) {
10880            // From above, we determined that we are deleting this only
10881            // for a single user.  Continue the work here.
10882            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10883            if (outInfo != null) {
10884                outInfo.removedPackage = packageName;
10885                outInfo.removedAppId = appId;
10886                outInfo.removedUsers = new int[] {removeUser};
10887            }
10888            mInstaller.clearUserData(packageName, removeUser);
10889            removeKeystoreDataIfNeeded(removeUser, appId);
10890            schedulePackageCleaning(packageName, removeUser, false);
10891            return true;
10892        }
10893
10894        if (dataOnly) {
10895            // Delete application data first
10896            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10897            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10898            return true;
10899        }
10900
10901        boolean ret = false;
10902        mSettings.mKeySetManager.removeAppKeySetData(packageName);
10903        if (isSystemApp(ps)) {
10904            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10905            // When an updated system application is deleted we delete the existing resources as well and
10906            // fall back to existing code in system partition
10907            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10908                    flags, outInfo, writeSettings);
10909        } else {
10910            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10911            // Kill application pre-emptively especially for apps on sd.
10912            killApplication(packageName, ps.appId, "uninstall pkg");
10913            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10914                    allUserHandles, perUserInstalled,
10915                    outInfo, writeSettings);
10916        }
10917
10918        return ret;
10919    }
10920
10921    private final class ClearStorageConnection implements ServiceConnection {
10922        IMediaContainerService mContainerService;
10923
10924        @Override
10925        public void onServiceConnected(ComponentName name, IBinder service) {
10926            synchronized (this) {
10927                mContainerService = IMediaContainerService.Stub.asInterface(service);
10928                notifyAll();
10929            }
10930        }
10931
10932        @Override
10933        public void onServiceDisconnected(ComponentName name) {
10934        }
10935    }
10936
10937    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10938        final boolean mounted;
10939        if (Environment.isExternalStorageEmulated()) {
10940            mounted = true;
10941        } else {
10942            final String status = Environment.getExternalStorageState();
10943
10944            mounted = status.equals(Environment.MEDIA_MOUNTED)
10945                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10946        }
10947
10948        if (!mounted) {
10949            return;
10950        }
10951
10952        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10953        int[] users;
10954        if (userId == UserHandle.USER_ALL) {
10955            users = sUserManager.getUserIds();
10956        } else {
10957            users = new int[] { userId };
10958        }
10959        final ClearStorageConnection conn = new ClearStorageConnection();
10960        if (mContext.bindServiceAsUser(
10961                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10962            try {
10963                for (int curUser : users) {
10964                    long timeout = SystemClock.uptimeMillis() + 5000;
10965                    synchronized (conn) {
10966                        long now = SystemClock.uptimeMillis();
10967                        while (conn.mContainerService == null && now < timeout) {
10968                            try {
10969                                conn.wait(timeout - now);
10970                            } catch (InterruptedException e) {
10971                            }
10972                        }
10973                    }
10974                    if (conn.mContainerService == null) {
10975                        return;
10976                    }
10977
10978                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10979                    clearDirectory(conn.mContainerService,
10980                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10981                    if (allData) {
10982                        clearDirectory(conn.mContainerService,
10983                                userEnv.buildExternalStorageAppDataDirs(packageName));
10984                        clearDirectory(conn.mContainerService,
10985                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10986                    }
10987                }
10988            } finally {
10989                mContext.unbindService(conn);
10990            }
10991        }
10992    }
10993
10994    @Override
10995    public void clearApplicationUserData(final String packageName,
10996            final IPackageDataObserver observer, final int userId) {
10997        mContext.enforceCallingOrSelfPermission(
10998                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10999        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11000        // Queue up an async operation since the package deletion may take a little while.
11001        mHandler.post(new Runnable() {
11002            public void run() {
11003                mHandler.removeCallbacks(this);
11004                final boolean succeeded;
11005                synchronized (mInstallLock) {
11006                    succeeded = clearApplicationUserDataLI(packageName, userId);
11007                }
11008                clearExternalStorageDataSync(packageName, userId, true);
11009                if (succeeded) {
11010                    // invoke DeviceStorageMonitor's update method to clear any notifications
11011                    DeviceStorageMonitorInternal
11012                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11013                    if (dsm != null) {
11014                        dsm.checkMemory();
11015                    }
11016                }
11017                if(observer != null) {
11018                    try {
11019                        observer.onRemoveCompleted(packageName, succeeded);
11020                    } catch (RemoteException e) {
11021                        Log.i(TAG, "Observer no longer exists.");
11022                    }
11023                } //end if observer
11024            } //end run
11025        });
11026    }
11027
11028    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11029        if (packageName == null) {
11030            Slog.w(TAG, "Attempt to delete null packageName.");
11031            return false;
11032        }
11033        PackageParser.Package p;
11034        boolean dataOnly = false;
11035        final int appId;
11036        synchronized (mPackages) {
11037            p = mPackages.get(packageName);
11038            if (p == null) {
11039                dataOnly = true;
11040                PackageSetting ps = mSettings.mPackages.get(packageName);
11041                if ((ps == null) || (ps.pkg == null)) {
11042                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11043                    return false;
11044                }
11045                p = ps.pkg;
11046            }
11047            if (!dataOnly) {
11048                // need to check this only for fully installed applications
11049                if (p == null) {
11050                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11051                    return false;
11052                }
11053                final ApplicationInfo applicationInfo = p.applicationInfo;
11054                if (applicationInfo == null) {
11055                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11056                    return false;
11057                }
11058            }
11059            if (p != null && p.applicationInfo != null) {
11060                appId = p.applicationInfo.uid;
11061            } else {
11062                appId = -1;
11063            }
11064        }
11065        int retCode = mInstaller.clearUserData(packageName, userId);
11066        if (retCode < 0) {
11067            Slog.w(TAG, "Couldn't remove cache files for package: "
11068                    + packageName);
11069            return false;
11070        }
11071        removeKeystoreDataIfNeeded(userId, appId);
11072        return true;
11073    }
11074
11075    /**
11076     * Remove entries from the keystore daemon. Will only remove it if the
11077     * {@code appId} is valid.
11078     */
11079    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11080        if (appId < 0) {
11081            return;
11082        }
11083
11084        final KeyStore keyStore = KeyStore.getInstance();
11085        if (keyStore != null) {
11086            if (userId == UserHandle.USER_ALL) {
11087                for (final int individual : sUserManager.getUserIds()) {
11088                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11089                }
11090            } else {
11091                keyStore.clearUid(UserHandle.getUid(userId, appId));
11092            }
11093        } else {
11094            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11095        }
11096    }
11097
11098    @Override
11099    public void deleteApplicationCacheFiles(final String packageName,
11100            final IPackageDataObserver observer) {
11101        mContext.enforceCallingOrSelfPermission(
11102                android.Manifest.permission.DELETE_CACHE_FILES, null);
11103        // Queue up an async operation since the package deletion may take a little while.
11104        final int userId = UserHandle.getCallingUserId();
11105        mHandler.post(new Runnable() {
11106            public void run() {
11107                mHandler.removeCallbacks(this);
11108                final boolean succeded;
11109                synchronized (mInstallLock) {
11110                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11111                }
11112                clearExternalStorageDataSync(packageName, userId, false);
11113                if(observer != null) {
11114                    try {
11115                        observer.onRemoveCompleted(packageName, succeded);
11116                    } catch (RemoteException e) {
11117                        Log.i(TAG, "Observer no longer exists.");
11118                    }
11119                } //end if observer
11120            } //end run
11121        });
11122    }
11123
11124    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11125        if (packageName == null) {
11126            Slog.w(TAG, "Attempt to delete null packageName.");
11127            return false;
11128        }
11129        PackageParser.Package p;
11130        synchronized (mPackages) {
11131            p = mPackages.get(packageName);
11132        }
11133        if (p == null) {
11134            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11135            return false;
11136        }
11137        final ApplicationInfo applicationInfo = p.applicationInfo;
11138        if (applicationInfo == null) {
11139            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11140            return false;
11141        }
11142        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11143        if (retCode < 0) {
11144            Slog.w(TAG, "Couldn't remove cache files for package: "
11145                       + packageName + " u" + userId);
11146            return false;
11147        }
11148        return true;
11149    }
11150
11151    @Override
11152    public void getPackageSizeInfo(final String packageName, int userHandle,
11153            final IPackageStatsObserver observer) {
11154        mContext.enforceCallingOrSelfPermission(
11155                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11156        if (packageName == null) {
11157            throw new IllegalArgumentException("Attempt to get size of null packageName");
11158        }
11159
11160        PackageStats stats = new PackageStats(packageName, userHandle);
11161
11162        /*
11163         * Queue up an async operation since the package measurement may take a
11164         * little while.
11165         */
11166        Message msg = mHandler.obtainMessage(INIT_COPY);
11167        msg.obj = new MeasureParams(stats, observer);
11168        mHandler.sendMessage(msg);
11169    }
11170
11171    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11172            PackageStats pStats) {
11173        if (packageName == null) {
11174            Slog.w(TAG, "Attempt to get size of null packageName.");
11175            return false;
11176        }
11177        PackageParser.Package p;
11178        boolean dataOnly = false;
11179        String libDirPath = null;
11180        String asecPath = null;
11181        PackageSetting ps = null;
11182        synchronized (mPackages) {
11183            p = mPackages.get(packageName);
11184            ps = mSettings.mPackages.get(packageName);
11185            if(p == null) {
11186                dataOnly = true;
11187                if((ps == null) || (ps.pkg == null)) {
11188                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11189                    return false;
11190                }
11191                p = ps.pkg;
11192            }
11193            if (ps != null) {
11194                libDirPath = ps.nativeLibraryPathString;
11195            }
11196            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11197                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
11198                if (secureContainerId != null) {
11199                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11200                }
11201            }
11202        }
11203        String publicSrcDir = null;
11204        if(!dataOnly) {
11205            final ApplicationInfo applicationInfo = p.applicationInfo;
11206            if (applicationInfo == null) {
11207                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11208                return false;
11209            }
11210            if (isForwardLocked(p)) {
11211                publicSrcDir = applicationInfo.publicSourceDir;
11212            }
11213        }
11214        int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath,
11215                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
11216                pStats);
11217        if (res < 0) {
11218            return false;
11219        }
11220
11221        // Fix-up for forward-locked applications in ASEC containers.
11222        if (!isExternal(p)) {
11223            pStats.codeSize += pStats.externalCodeSize;
11224            pStats.externalCodeSize = 0L;
11225        }
11226
11227        return true;
11228    }
11229
11230
11231    @Override
11232    public void addPackageToPreferred(String packageName) {
11233        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11234    }
11235
11236    @Override
11237    public void removePackageFromPreferred(String packageName) {
11238        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11239    }
11240
11241    @Override
11242    public List<PackageInfo> getPreferredPackages(int flags) {
11243        return new ArrayList<PackageInfo>();
11244    }
11245
11246    private int getUidTargetSdkVersionLockedLPr(int uid) {
11247        Object obj = mSettings.getUserIdLPr(uid);
11248        if (obj instanceof SharedUserSetting) {
11249            final SharedUserSetting sus = (SharedUserSetting) obj;
11250            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11251            final Iterator<PackageSetting> it = sus.packages.iterator();
11252            while (it.hasNext()) {
11253                final PackageSetting ps = it.next();
11254                if (ps.pkg != null) {
11255                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11256                    if (v < vers) vers = v;
11257                }
11258            }
11259            return vers;
11260        } else if (obj instanceof PackageSetting) {
11261            final PackageSetting ps = (PackageSetting) obj;
11262            if (ps.pkg != null) {
11263                return ps.pkg.applicationInfo.targetSdkVersion;
11264            }
11265        }
11266        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11267    }
11268
11269    @Override
11270    public void addPreferredActivity(IntentFilter filter, int match,
11271            ComponentName[] set, ComponentName activity, int userId) {
11272        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11273    }
11274
11275    private void addPreferredActivityInternal(IntentFilter filter, int match,
11276            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11277        // writer
11278        int callingUid = Binder.getCallingUid();
11279        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11280        if (filter.countActions() == 0) {
11281            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11282            return;
11283        }
11284        synchronized (mPackages) {
11285            if (mContext.checkCallingOrSelfPermission(
11286                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11287                    != PackageManager.PERMISSION_GRANTED) {
11288                if (getUidTargetSdkVersionLockedLPr(callingUid)
11289                        < Build.VERSION_CODES.FROYO) {
11290                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11291                            + callingUid);
11292                    return;
11293                }
11294                mContext.enforceCallingOrSelfPermission(
11295                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11296            }
11297
11298            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11299            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11300            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11301                    new PreferredActivity(filter, match, set, activity, always));
11302            mSettings.writePackageRestrictionsLPr(userId);
11303        }
11304    }
11305
11306    @Override
11307    public void replacePreferredActivity(IntentFilter filter, int match,
11308            ComponentName[] set, ComponentName activity) {
11309        if (filter.countActions() != 1) {
11310            throw new IllegalArgumentException(
11311                    "replacePreferredActivity expects filter to have only 1 action.");
11312        }
11313        if (filter.countDataAuthorities() != 0
11314                || filter.countDataPaths() != 0
11315                || filter.countDataSchemes() > 1
11316                || filter.countDataTypes() != 0) {
11317            throw new IllegalArgumentException(
11318                    "replacePreferredActivity expects filter to have no data authorities, " +
11319                    "paths, or types; and at most one scheme.");
11320        }
11321        synchronized (mPackages) {
11322            if (mContext.checkCallingOrSelfPermission(
11323                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11324                    != PackageManager.PERMISSION_GRANTED) {
11325                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11326                        < Build.VERSION_CODES.FROYO) {
11327                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11328                            + Binder.getCallingUid());
11329                    return;
11330                }
11331                mContext.enforceCallingOrSelfPermission(
11332                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11333            }
11334
11335            final int callingUserId = UserHandle.getCallingUserId();
11336            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11337            if (pir != null) {
11338                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11339                if (filter.countDataSchemes() == 1) {
11340                    Uri.Builder builder = new Uri.Builder();
11341                    builder.scheme(filter.getDataScheme(0));
11342                    intent.setData(builder.build());
11343                }
11344                List<PreferredActivity> matches = pir.queryIntent(
11345                        intent, null, true, callingUserId);
11346                if (DEBUG_PREFERRED) {
11347                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11348                }
11349                for (int i = 0; i < matches.size(); i++) {
11350                    PreferredActivity pa = matches.get(i);
11351                    if (DEBUG_PREFERRED) {
11352                        Slog.i(TAG, "Removing preferred activity "
11353                                + pa.mPref.mComponent + ":");
11354                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11355                    }
11356                    pir.removeFilter(pa);
11357                }
11358            }
11359            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11360        }
11361    }
11362
11363    @Override
11364    public void clearPackagePreferredActivities(String packageName) {
11365        final int uid = Binder.getCallingUid();
11366        // writer
11367        synchronized (mPackages) {
11368            PackageParser.Package pkg = mPackages.get(packageName);
11369            if (pkg == null || pkg.applicationInfo.uid != uid) {
11370                if (mContext.checkCallingOrSelfPermission(
11371                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11372                        != PackageManager.PERMISSION_GRANTED) {
11373                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11374                            < Build.VERSION_CODES.FROYO) {
11375                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11376                                + Binder.getCallingUid());
11377                        return;
11378                    }
11379                    mContext.enforceCallingOrSelfPermission(
11380                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11381                }
11382            }
11383
11384            int user = UserHandle.getCallingUserId();
11385            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11386                mSettings.writePackageRestrictionsLPr(user);
11387                scheduleWriteSettingsLocked();
11388            }
11389        }
11390    }
11391
11392    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11393    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11394        ArrayList<PreferredActivity> removed = null;
11395        boolean changed = false;
11396        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11397            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11398            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11399            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11400                continue;
11401            }
11402            Iterator<PreferredActivity> it = pir.filterIterator();
11403            while (it.hasNext()) {
11404                PreferredActivity pa = it.next();
11405                // Mark entry for removal only if it matches the package name
11406                // and the entry is of type "always".
11407                if (packageName == null ||
11408                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11409                                && pa.mPref.mAlways)) {
11410                    if (removed == null) {
11411                        removed = new ArrayList<PreferredActivity>();
11412                    }
11413                    removed.add(pa);
11414                }
11415            }
11416            if (removed != null) {
11417                for (int j=0; j<removed.size(); j++) {
11418                    PreferredActivity pa = removed.get(j);
11419                    pir.removeFilter(pa);
11420                }
11421                changed = true;
11422            }
11423        }
11424        return changed;
11425    }
11426
11427    @Override
11428    public void resetPreferredActivities(int userId) {
11429        mContext.enforceCallingOrSelfPermission(
11430                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11431        // writer
11432        synchronized (mPackages) {
11433            int user = UserHandle.getCallingUserId();
11434            clearPackagePreferredActivitiesLPw(null, user);
11435            mSettings.readDefaultPreferredAppsLPw(this, user);
11436            mSettings.writePackageRestrictionsLPr(user);
11437            scheduleWriteSettingsLocked();
11438        }
11439    }
11440
11441    @Override
11442    public int getPreferredActivities(List<IntentFilter> outFilters,
11443            List<ComponentName> outActivities, String packageName) {
11444
11445        int num = 0;
11446        final int userId = UserHandle.getCallingUserId();
11447        // reader
11448        synchronized (mPackages) {
11449            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11450            if (pir != null) {
11451                final Iterator<PreferredActivity> it = pir.filterIterator();
11452                while (it.hasNext()) {
11453                    final PreferredActivity pa = it.next();
11454                    if (packageName == null
11455                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11456                                    && pa.mPref.mAlways)) {
11457                        if (outFilters != null) {
11458                            outFilters.add(new IntentFilter(pa));
11459                        }
11460                        if (outActivities != null) {
11461                            outActivities.add(pa.mPref.mComponent);
11462                        }
11463                    }
11464                }
11465            }
11466        }
11467
11468        return num;
11469    }
11470
11471    @Override
11472    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11473            int userId) {
11474        int callingUid = Binder.getCallingUid();
11475        if (callingUid != Process.SYSTEM_UID) {
11476            throw new SecurityException(
11477                    "addPersistentPreferredActivity can only be run by the system");
11478        }
11479        if (filter.countActions() == 0) {
11480            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11481            return;
11482        }
11483        synchronized (mPackages) {
11484            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11485                    " :");
11486            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11487            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11488                    new PersistentPreferredActivity(filter, activity));
11489            mSettings.writePackageRestrictionsLPr(userId);
11490        }
11491    }
11492
11493    @Override
11494    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11495        int callingUid = Binder.getCallingUid();
11496        if (callingUid != Process.SYSTEM_UID) {
11497            throw new SecurityException(
11498                    "clearPackagePersistentPreferredActivities can only be run by the system");
11499        }
11500        ArrayList<PersistentPreferredActivity> removed = null;
11501        boolean changed = false;
11502        synchronized (mPackages) {
11503            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11504                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11505                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11506                        .valueAt(i);
11507                if (userId != thisUserId) {
11508                    continue;
11509                }
11510                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11511                while (it.hasNext()) {
11512                    PersistentPreferredActivity ppa = it.next();
11513                    // Mark entry for removal only if it matches the package name.
11514                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11515                        if (removed == null) {
11516                            removed = new ArrayList<PersistentPreferredActivity>();
11517                        }
11518                        removed.add(ppa);
11519                    }
11520                }
11521                if (removed != null) {
11522                    for (int j=0; j<removed.size(); j++) {
11523                        PersistentPreferredActivity ppa = removed.get(j);
11524                        ppir.removeFilter(ppa);
11525                    }
11526                    changed = true;
11527                }
11528            }
11529
11530            if (changed) {
11531                mSettings.writePackageRestrictionsLPr(userId);
11532            }
11533        }
11534    }
11535
11536    @Override
11537    public void addCrossProfileIntentFilter(IntentFilter filter, boolean removable,
11538            int sourceUserId, int targetUserId) {
11539        mContext.enforceCallingOrSelfPermission(
11540                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11541        if (filter.countActions() == 0) {
11542            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11543            return;
11544        }
11545        synchronized (mPackages) {
11546            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(
11547                    new CrossProfileIntentFilter(filter, removable, targetUserId));
11548            mSettings.writePackageRestrictionsLPr(sourceUserId);
11549        }
11550    }
11551
11552    @Override
11553    public void clearCrossProfileIntentFilters(int sourceUserId) {
11554        mContext.enforceCallingOrSelfPermission(
11555                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11556        synchronized (mPackages) {
11557            CrossProfileIntentResolver cpir =
11558                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11559            HashSet<CrossProfileIntentFilter> set =
11560                    new HashSet<CrossProfileIntentFilter>(cpir.filterSet());
11561            for (CrossProfileIntentFilter cpif : set) {
11562                if (cpif.isRemovable()) cpir.removeFilter(cpif);
11563            }
11564            mSettings.writePackageRestrictionsLPr(sourceUserId);
11565        }
11566    }
11567
11568    @Override
11569    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11570        Intent intent = new Intent(Intent.ACTION_MAIN);
11571        intent.addCategory(Intent.CATEGORY_HOME);
11572
11573        final int callingUserId = UserHandle.getCallingUserId();
11574        List<ResolveInfo> list = queryIntentActivities(intent, null,
11575                PackageManager.GET_META_DATA, callingUserId);
11576        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11577                true, false, false, callingUserId);
11578
11579        allHomeCandidates.clear();
11580        if (list != null) {
11581            for (ResolveInfo ri : list) {
11582                allHomeCandidates.add(ri);
11583            }
11584        }
11585        return (preferred == null || preferred.activityInfo == null)
11586                ? null
11587                : new ComponentName(preferred.activityInfo.packageName,
11588                        preferred.activityInfo.name);
11589    }
11590
11591    @Override
11592    public void setApplicationEnabledSetting(String appPackageName,
11593            int newState, int flags, int userId, String callingPackage) {
11594        if (!sUserManager.exists(userId)) return;
11595        if (callingPackage == null) {
11596            callingPackage = Integer.toString(Binder.getCallingUid());
11597        }
11598        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11599    }
11600
11601    @Override
11602    public void setComponentEnabledSetting(ComponentName componentName,
11603            int newState, int flags, int userId) {
11604        if (!sUserManager.exists(userId)) return;
11605        setEnabledSetting(componentName.getPackageName(),
11606                componentName.getClassName(), newState, flags, userId, null);
11607    }
11608
11609    private void setEnabledSetting(final String packageName, String className, int newState,
11610            final int flags, int userId, String callingPackage) {
11611        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11612              || newState == COMPONENT_ENABLED_STATE_ENABLED
11613              || newState == COMPONENT_ENABLED_STATE_DISABLED
11614              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11615              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11616            throw new IllegalArgumentException("Invalid new component state: "
11617                    + newState);
11618        }
11619        PackageSetting pkgSetting;
11620        final int uid = Binder.getCallingUid();
11621        final int permission = mContext.checkCallingOrSelfPermission(
11622                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11623        enforceCrossUserPermission(uid, userId, false, "set enabled");
11624        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11625        boolean sendNow = false;
11626        boolean isApp = (className == null);
11627        String componentName = isApp ? packageName : className;
11628        int packageUid = -1;
11629        ArrayList<String> components;
11630
11631        // writer
11632        synchronized (mPackages) {
11633            pkgSetting = mSettings.mPackages.get(packageName);
11634            if (pkgSetting == null) {
11635                if (className == null) {
11636                    throw new IllegalArgumentException(
11637                            "Unknown package: " + packageName);
11638                }
11639                throw new IllegalArgumentException(
11640                        "Unknown component: " + packageName
11641                        + "/" + className);
11642            }
11643            // Allow root and verify that userId is not being specified by a different user
11644            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11645                throw new SecurityException(
11646                        "Permission Denial: attempt to change component state from pid="
11647                        + Binder.getCallingPid()
11648                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11649            }
11650            if (className == null) {
11651                // We're dealing with an application/package level state change
11652                if (pkgSetting.getEnabled(userId) == newState) {
11653                    // Nothing to do
11654                    return;
11655                }
11656                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11657                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11658                    // Don't care about who enables an app.
11659                    callingPackage = null;
11660                }
11661                pkgSetting.setEnabled(newState, userId, callingPackage);
11662                // pkgSetting.pkg.mSetEnabled = newState;
11663            } else {
11664                // We're dealing with a component level state change
11665                // First, verify that this is a valid class name.
11666                PackageParser.Package pkg = pkgSetting.pkg;
11667                if (pkg == null || !pkg.hasComponentClassName(className)) {
11668                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11669                        throw new IllegalArgumentException("Component class " + className
11670                                + " does not exist in " + packageName);
11671                    } else {
11672                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11673                                + className + " does not exist in " + packageName);
11674                    }
11675                }
11676                switch (newState) {
11677                case COMPONENT_ENABLED_STATE_ENABLED:
11678                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11679                        return;
11680                    }
11681                    break;
11682                case COMPONENT_ENABLED_STATE_DISABLED:
11683                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11684                        return;
11685                    }
11686                    break;
11687                case COMPONENT_ENABLED_STATE_DEFAULT:
11688                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11689                        return;
11690                    }
11691                    break;
11692                default:
11693                    Slog.e(TAG, "Invalid new component state: " + newState);
11694                    return;
11695                }
11696            }
11697            mSettings.writePackageRestrictionsLPr(userId);
11698            components = mPendingBroadcasts.get(userId, packageName);
11699            final boolean newPackage = components == null;
11700            if (newPackage) {
11701                components = new ArrayList<String>();
11702            }
11703            if (!components.contains(componentName)) {
11704                components.add(componentName);
11705            }
11706            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11707                sendNow = true;
11708                // Purge entry from pending broadcast list if another one exists already
11709                // since we are sending one right away.
11710                mPendingBroadcasts.remove(userId, packageName);
11711            } else {
11712                if (newPackage) {
11713                    mPendingBroadcasts.put(userId, packageName, components);
11714                }
11715                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11716                    // Schedule a message
11717                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11718                }
11719            }
11720        }
11721
11722        long callingId = Binder.clearCallingIdentity();
11723        try {
11724            if (sendNow) {
11725                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11726                sendPackageChangedBroadcast(packageName,
11727                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11728            }
11729        } finally {
11730            Binder.restoreCallingIdentity(callingId);
11731        }
11732    }
11733
11734    private void sendPackageChangedBroadcast(String packageName,
11735            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11736        if (DEBUG_INSTALL)
11737            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11738                    + componentNames);
11739        Bundle extras = new Bundle(4);
11740        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11741        String nameList[] = new String[componentNames.size()];
11742        componentNames.toArray(nameList);
11743        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11744        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11745        extras.putInt(Intent.EXTRA_UID, packageUid);
11746        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11747                new int[] {UserHandle.getUserId(packageUid)});
11748    }
11749
11750    @Override
11751    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11752        if (!sUserManager.exists(userId)) return;
11753        final int uid = Binder.getCallingUid();
11754        final int permission = mContext.checkCallingOrSelfPermission(
11755                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11756        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11757        enforceCrossUserPermission(uid, userId, true, "stop package");
11758        // writer
11759        synchronized (mPackages) {
11760            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11761                    uid, userId)) {
11762                scheduleWritePackageRestrictionsLocked(userId);
11763            }
11764        }
11765    }
11766
11767    @Override
11768    public String getInstallerPackageName(String packageName) {
11769        // reader
11770        synchronized (mPackages) {
11771            return mSettings.getInstallerPackageNameLPr(packageName);
11772        }
11773    }
11774
11775    @Override
11776    public int getApplicationEnabledSetting(String packageName, int userId) {
11777        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11778        int uid = Binder.getCallingUid();
11779        enforceCrossUserPermission(uid, userId, false, "get enabled");
11780        // reader
11781        synchronized (mPackages) {
11782            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11783        }
11784    }
11785
11786    @Override
11787    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11788        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11789        int uid = Binder.getCallingUid();
11790        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11791        // reader
11792        synchronized (mPackages) {
11793            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11794        }
11795    }
11796
11797    @Override
11798    public void enterSafeMode() {
11799        enforceSystemOrRoot("Only the system can request entering safe mode");
11800
11801        if (!mSystemReady) {
11802            mSafeMode = true;
11803        }
11804    }
11805
11806    @Override
11807    public void systemReady() {
11808        mSystemReady = true;
11809
11810        // Read the compatibilty setting when the system is ready.
11811        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11812                mContext.getContentResolver(),
11813                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11814        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11815        if (DEBUG_SETTINGS) {
11816            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11817        }
11818
11819        synchronized (mPackages) {
11820            // Verify that all of the preferred activity components actually
11821            // exist.  It is possible for applications to be updated and at
11822            // that point remove a previously declared activity component that
11823            // had been set as a preferred activity.  We try to clean this up
11824            // the next time we encounter that preferred activity, but it is
11825            // possible for the user flow to never be able to return to that
11826            // situation so here we do a sanity check to make sure we haven't
11827            // left any junk around.
11828            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11829            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11830                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11831                removed.clear();
11832                for (PreferredActivity pa : pir.filterSet()) {
11833                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11834                        removed.add(pa);
11835                    }
11836                }
11837                if (removed.size() > 0) {
11838                    for (int r=0; r<removed.size(); r++) {
11839                        PreferredActivity pa = removed.get(r);
11840                        Slog.w(TAG, "Removing dangling preferred activity: "
11841                                + pa.mPref.mComponent);
11842                        pir.removeFilter(pa);
11843                    }
11844                    mSettings.writePackageRestrictionsLPr(
11845                            mSettings.mPreferredActivities.keyAt(i));
11846                }
11847            }
11848        }
11849        sUserManager.systemReady();
11850    }
11851
11852    @Override
11853    public boolean isSafeMode() {
11854        return mSafeMode;
11855    }
11856
11857    @Override
11858    public boolean hasSystemUidErrors() {
11859        return mHasSystemUidErrors;
11860    }
11861
11862    static String arrayToString(int[] array) {
11863        StringBuffer buf = new StringBuffer(128);
11864        buf.append('[');
11865        if (array != null) {
11866            for (int i=0; i<array.length; i++) {
11867                if (i > 0) buf.append(", ");
11868                buf.append(array[i]);
11869            }
11870        }
11871        buf.append(']');
11872        return buf.toString();
11873    }
11874
11875    static class DumpState {
11876        public static final int DUMP_LIBS = 1 << 0;
11877
11878        public static final int DUMP_FEATURES = 1 << 1;
11879
11880        public static final int DUMP_RESOLVERS = 1 << 2;
11881
11882        public static final int DUMP_PERMISSIONS = 1 << 3;
11883
11884        public static final int DUMP_PACKAGES = 1 << 4;
11885
11886        public static final int DUMP_SHARED_USERS = 1 << 5;
11887
11888        public static final int DUMP_MESSAGES = 1 << 6;
11889
11890        public static final int DUMP_PROVIDERS = 1 << 7;
11891
11892        public static final int DUMP_VERIFIERS = 1 << 8;
11893
11894        public static final int DUMP_PREFERRED = 1 << 9;
11895
11896        public static final int DUMP_PREFERRED_XML = 1 << 10;
11897
11898        public static final int DUMP_KEYSETS = 1 << 11;
11899
11900        public static final int DUMP_VERSION = 1 << 12;
11901
11902        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11903
11904        private int mTypes;
11905
11906        private int mOptions;
11907
11908        private boolean mTitlePrinted;
11909
11910        private SharedUserSetting mSharedUser;
11911
11912        public boolean isDumping(int type) {
11913            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11914                return true;
11915            }
11916
11917            return (mTypes & type) != 0;
11918        }
11919
11920        public void setDump(int type) {
11921            mTypes |= type;
11922        }
11923
11924        public boolean isOptionEnabled(int option) {
11925            return (mOptions & option) != 0;
11926        }
11927
11928        public void setOptionEnabled(int option) {
11929            mOptions |= option;
11930        }
11931
11932        public boolean onTitlePrinted() {
11933            final boolean printed = mTitlePrinted;
11934            mTitlePrinted = true;
11935            return printed;
11936        }
11937
11938        public boolean getTitlePrinted() {
11939            return mTitlePrinted;
11940        }
11941
11942        public void setTitlePrinted(boolean enabled) {
11943            mTitlePrinted = enabled;
11944        }
11945
11946        public SharedUserSetting getSharedUser() {
11947            return mSharedUser;
11948        }
11949
11950        public void setSharedUser(SharedUserSetting user) {
11951            mSharedUser = user;
11952        }
11953    }
11954
11955    @Override
11956    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11957        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
11958                != PackageManager.PERMISSION_GRANTED) {
11959            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11960                    + Binder.getCallingPid()
11961                    + ", uid=" + Binder.getCallingUid()
11962                    + " without permission "
11963                    + android.Manifest.permission.DUMP);
11964            return;
11965        }
11966
11967        DumpState dumpState = new DumpState();
11968        boolean fullPreferred = false;
11969        boolean checkin = false;
11970
11971        String packageName = null;
11972
11973        int opti = 0;
11974        while (opti < args.length) {
11975            String opt = args[opti];
11976            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11977                break;
11978            }
11979            opti++;
11980            if ("-a".equals(opt)) {
11981                // Right now we only know how to print all.
11982            } else if ("-h".equals(opt)) {
11983                pw.println("Package manager dump options:");
11984                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
11985                pw.println("    --checkin: dump for a checkin");
11986                pw.println("    -f: print details of intent filters");
11987                pw.println("    -h: print this help");
11988                pw.println("  cmd may be one of:");
11989                pw.println("    l[ibraries]: list known shared libraries");
11990                pw.println("    f[ibraries]: list device features");
11991                pw.println("    k[eysets]: print known keysets");
11992                pw.println("    r[esolvers]: dump intent resolvers");
11993                pw.println("    perm[issions]: dump permissions");
11994                pw.println("    pref[erred]: print preferred package settings");
11995                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
11996                pw.println("    prov[iders]: dump content providers");
11997                pw.println("    p[ackages]: dump installed packages");
11998                pw.println("    s[hared-users]: dump shared user IDs");
11999                pw.println("    m[essages]: print collected runtime messages");
12000                pw.println("    v[erifiers]: print package verifier info");
12001                pw.println("    version: print database version info");
12002                pw.println("    write: write current settings now");
12003                pw.println("    <package.name>: info about given package");
12004                return;
12005            } else if ("--checkin".equals(opt)) {
12006                checkin = true;
12007            } else if ("-f".equals(opt)) {
12008                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12009            } else {
12010                pw.println("Unknown argument: " + opt + "; use -h for help");
12011            }
12012        }
12013
12014        // Is the caller requesting to dump a particular piece of data?
12015        if (opti < args.length) {
12016            String cmd = args[opti];
12017            opti++;
12018            // Is this a package name?
12019            if ("android".equals(cmd) || cmd.contains(".")) {
12020                packageName = cmd;
12021                // When dumping a single package, we always dump all of its
12022                // filter information since the amount of data will be reasonable.
12023                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12024            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12025                dumpState.setDump(DumpState.DUMP_LIBS);
12026            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12027                dumpState.setDump(DumpState.DUMP_FEATURES);
12028            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12029                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12030            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12031                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12032            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12033                dumpState.setDump(DumpState.DUMP_PREFERRED);
12034            } else if ("preferred-xml".equals(cmd)) {
12035                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12036                if (opti < args.length && "--full".equals(args[opti])) {
12037                    fullPreferred = true;
12038                    opti++;
12039                }
12040            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12041                dumpState.setDump(DumpState.DUMP_PACKAGES);
12042            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12043                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12044            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12045                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12046            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12047                dumpState.setDump(DumpState.DUMP_MESSAGES);
12048            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12049                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12050            } else if ("version".equals(cmd)) {
12051                dumpState.setDump(DumpState.DUMP_VERSION);
12052            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12053                dumpState.setDump(DumpState.DUMP_KEYSETS);
12054            } else if ("write".equals(cmd)) {
12055                synchronized (mPackages) {
12056                    mSettings.writeLPr();
12057                    pw.println("Settings written.");
12058                    return;
12059                }
12060            }
12061        }
12062
12063        if (checkin) {
12064            pw.println("vers,1");
12065        }
12066
12067        // reader
12068        synchronized (mPackages) {
12069            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12070                if (!checkin) {
12071                    if (dumpState.onTitlePrinted())
12072                        pw.println();
12073                    pw.println("Database versions:");
12074                    pw.print("  SDK Version:");
12075                    pw.print(" internal=");
12076                    pw.print(mSettings.mInternalSdkPlatform);
12077                    pw.print(" external=");
12078                    pw.println(mSettings.mExternalSdkPlatform);
12079                    pw.print("  DB Version:");
12080                    pw.print(" internal=");
12081                    pw.print(mSettings.mInternalDatabaseVersion);
12082                    pw.print(" external=");
12083                    pw.println(mSettings.mExternalDatabaseVersion);
12084                }
12085            }
12086
12087            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12088                if (!checkin) {
12089                    if (dumpState.onTitlePrinted())
12090                        pw.println();
12091                    pw.println("Verifiers:");
12092                    pw.print("  Required: ");
12093                    pw.print(mRequiredVerifierPackage);
12094                    pw.print(" (uid=");
12095                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12096                    pw.println(")");
12097                } else if (mRequiredVerifierPackage != null) {
12098                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12099                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12100                }
12101            }
12102
12103            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12104                boolean printedHeader = false;
12105                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12106                while (it.hasNext()) {
12107                    String name = it.next();
12108                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12109                    if (!checkin) {
12110                        if (!printedHeader) {
12111                            if (dumpState.onTitlePrinted())
12112                                pw.println();
12113                            pw.println("Libraries:");
12114                            printedHeader = true;
12115                        }
12116                        pw.print("  ");
12117                    } else {
12118                        pw.print("lib,");
12119                    }
12120                    pw.print(name);
12121                    if (!checkin) {
12122                        pw.print(" -> ");
12123                    }
12124                    if (ent.path != null) {
12125                        if (!checkin) {
12126                            pw.print("(jar) ");
12127                            pw.print(ent.path);
12128                        } else {
12129                            pw.print(",jar,");
12130                            pw.print(ent.path);
12131                        }
12132                    } else {
12133                        if (!checkin) {
12134                            pw.print("(apk) ");
12135                            pw.print(ent.apk);
12136                        } else {
12137                            pw.print(",apk,");
12138                            pw.print(ent.apk);
12139                        }
12140                    }
12141                    pw.println();
12142                }
12143            }
12144
12145            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12146                if (dumpState.onTitlePrinted())
12147                    pw.println();
12148                if (!checkin) {
12149                    pw.println("Features:");
12150                }
12151                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12152                while (it.hasNext()) {
12153                    String name = it.next();
12154                    if (!checkin) {
12155                        pw.print("  ");
12156                    } else {
12157                        pw.print("feat,");
12158                    }
12159                    pw.println(name);
12160                }
12161            }
12162
12163            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12164                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12165                        : "Activity Resolver Table:", "  ", packageName,
12166                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12167                    dumpState.setTitlePrinted(true);
12168                }
12169                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12170                        : "Receiver Resolver Table:", "  ", packageName,
12171                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12172                    dumpState.setTitlePrinted(true);
12173                }
12174                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12175                        : "Service Resolver Table:", "  ", packageName,
12176                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12177                    dumpState.setTitlePrinted(true);
12178                }
12179                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12180                        : "Provider Resolver Table:", "  ", packageName,
12181                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12182                    dumpState.setTitlePrinted(true);
12183                }
12184            }
12185
12186            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12187                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12188                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12189                    int user = mSettings.mPreferredActivities.keyAt(i);
12190                    if (pir.dump(pw,
12191                            dumpState.getTitlePrinted()
12192                                ? "\nPreferred Activities User " + user + ":"
12193                                : "Preferred Activities User " + user + ":", "  ",
12194                            packageName, true)) {
12195                        dumpState.setTitlePrinted(true);
12196                    }
12197                }
12198            }
12199
12200            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12201                pw.flush();
12202                FileOutputStream fout = new FileOutputStream(fd);
12203                BufferedOutputStream str = new BufferedOutputStream(fout);
12204                XmlSerializer serializer = new FastXmlSerializer();
12205                try {
12206                    serializer.setOutput(str, "utf-8");
12207                    serializer.startDocument(null, true);
12208                    serializer.setFeature(
12209                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12210                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12211                    serializer.endDocument();
12212                    serializer.flush();
12213                } catch (IllegalArgumentException e) {
12214                    pw.println("Failed writing: " + e);
12215                } catch (IllegalStateException e) {
12216                    pw.println("Failed writing: " + e);
12217                } catch (IOException e) {
12218                    pw.println("Failed writing: " + e);
12219                }
12220            }
12221
12222            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12223                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12224            }
12225
12226            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12227                boolean printedSomething = false;
12228                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12229                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12230                        continue;
12231                    }
12232                    if (!printedSomething) {
12233                        if (dumpState.onTitlePrinted())
12234                            pw.println();
12235                        pw.println("Registered ContentProviders:");
12236                        printedSomething = true;
12237                    }
12238                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12239                    pw.print("    "); pw.println(p.toString());
12240                }
12241                printedSomething = false;
12242                for (Map.Entry<String, PackageParser.Provider> entry :
12243                        mProvidersByAuthority.entrySet()) {
12244                    PackageParser.Provider p = entry.getValue();
12245                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12246                        continue;
12247                    }
12248                    if (!printedSomething) {
12249                        if (dumpState.onTitlePrinted())
12250                            pw.println();
12251                        pw.println("ContentProvider Authorities:");
12252                        printedSomething = true;
12253                    }
12254                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12255                    pw.print("    "); pw.println(p.toString());
12256                    if (p.info != null && p.info.applicationInfo != null) {
12257                        final String appInfo = p.info.applicationInfo.toString();
12258                        pw.print("      applicationInfo="); pw.println(appInfo);
12259                    }
12260                }
12261            }
12262
12263            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12264                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
12265            }
12266
12267            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12268                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12269            }
12270
12271            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12272                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12273            }
12274
12275            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12276                if (dumpState.onTitlePrinted())
12277                    pw.println();
12278                mSettings.dumpReadMessagesLPr(pw, dumpState);
12279
12280                pw.println();
12281                pw.println("Package warning messages:");
12282                final File fname = getSettingsProblemFile();
12283                FileInputStream in = null;
12284                try {
12285                    in = new FileInputStream(fname);
12286                    final int avail = in.available();
12287                    final byte[] data = new byte[avail];
12288                    in.read(data);
12289                    pw.print(new String(data));
12290                } catch (FileNotFoundException e) {
12291                } catch (IOException e) {
12292                } finally {
12293                    if (in != null) {
12294                        try {
12295                            in.close();
12296                        } catch (IOException e) {
12297                        }
12298                    }
12299                }
12300            }
12301        }
12302    }
12303
12304    // ------- apps on sdcard specific code -------
12305    static final boolean DEBUG_SD_INSTALL = false;
12306
12307    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12308
12309    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12310
12311    private boolean mMediaMounted = false;
12312
12313    private String getEncryptKey() {
12314        try {
12315            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12316                    SD_ENCRYPTION_KEYSTORE_NAME);
12317            if (sdEncKey == null) {
12318                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12319                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12320                if (sdEncKey == null) {
12321                    Slog.e(TAG, "Failed to create encryption keys");
12322                    return null;
12323                }
12324            }
12325            return sdEncKey;
12326        } catch (NoSuchAlgorithmException nsae) {
12327            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12328            return null;
12329        } catch (IOException ioe) {
12330            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12331            return null;
12332        }
12333
12334    }
12335
12336    /* package */static String getTempContainerId() {
12337        int tmpIdx = 1;
12338        String list[] = PackageHelper.getSecureContainerList();
12339        if (list != null) {
12340            for (final String name : list) {
12341                // Ignore null and non-temporary container entries
12342                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12343                    continue;
12344                }
12345
12346                String subStr = name.substring(mTempContainerPrefix.length());
12347                try {
12348                    int cid = Integer.parseInt(subStr);
12349                    if (cid >= tmpIdx) {
12350                        tmpIdx = cid + 1;
12351                    }
12352                } catch (NumberFormatException e) {
12353                }
12354            }
12355        }
12356        return mTempContainerPrefix + tmpIdx;
12357    }
12358
12359    /*
12360     * Update media status on PackageManager.
12361     */
12362    @Override
12363    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12364        int callingUid = Binder.getCallingUid();
12365        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12366            throw new SecurityException("Media status can only be updated by the system");
12367        }
12368        // reader; this apparently protects mMediaMounted, but should probably
12369        // be a different lock in that case.
12370        synchronized (mPackages) {
12371            Log.i(TAG, "Updating external media status from "
12372                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12373                    + (mediaStatus ? "mounted" : "unmounted"));
12374            if (DEBUG_SD_INSTALL)
12375                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12376                        + ", mMediaMounted=" + mMediaMounted);
12377            if (mediaStatus == mMediaMounted) {
12378                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12379                        : 0, -1);
12380                mHandler.sendMessage(msg);
12381                return;
12382            }
12383            mMediaMounted = mediaStatus;
12384        }
12385        // Queue up an async operation since the package installation may take a
12386        // little while.
12387        mHandler.post(new Runnable() {
12388            public void run() {
12389                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12390            }
12391        });
12392    }
12393
12394    /**
12395     * Called by MountService when the initial ASECs to scan are available.
12396     * Should block until all the ASEC containers are finished being scanned.
12397     */
12398    public void scanAvailableAsecs() {
12399        updateExternalMediaStatusInner(true, false, false);
12400        if (mShouldRestoreconData) {
12401            SELinuxMMAC.setRestoreconDone();
12402            mShouldRestoreconData = false;
12403        }
12404    }
12405
12406    /*
12407     * Collect information of applications on external media, map them against
12408     * existing containers and update information based on current mount status.
12409     * Please note that we always have to report status if reportStatus has been
12410     * set to true especially when unloading packages.
12411     */
12412    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12413            boolean externalStorage) {
12414        // Collection of uids
12415        int uidArr[] = null;
12416        // Collection of stale containers
12417        HashSet<String> removeCids = new HashSet<String>();
12418        // Collection of packages on external media with valid containers.
12419        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12420        // Get list of secure containers.
12421        final String list[] = PackageHelper.getSecureContainerList();
12422        if (list == null || list.length == 0) {
12423            Log.i(TAG, "No secure containers on sdcard");
12424        } else {
12425            // Process list of secure containers and categorize them
12426            // as active or stale based on their package internal state.
12427            int uidList[] = new int[list.length];
12428            int num = 0;
12429            // reader
12430            synchronized (mPackages) {
12431                for (String cid : list) {
12432                    if (DEBUG_SD_INSTALL)
12433                        Log.i(TAG, "Processing container " + cid);
12434                    String pkgName = getAsecPackageName(cid);
12435                    if (pkgName == null) {
12436                        if (DEBUG_SD_INSTALL)
12437                            Log.i(TAG, "Container : " + cid + " stale");
12438                        removeCids.add(cid);
12439                        continue;
12440                    }
12441                    if (DEBUG_SD_INSTALL)
12442                        Log.i(TAG, "Looking for pkg : " + pkgName);
12443
12444                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12445                    if (ps == null) {
12446                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12447                        removeCids.add(cid);
12448                        continue;
12449                    }
12450
12451                    /*
12452                     * Skip packages that are not external if we're unmounting
12453                     * external storage.
12454                     */
12455                    if (externalStorage && !isMounted && !isExternal(ps)) {
12456                        continue;
12457                    }
12458
12459                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12460                            getAppInstructionSetFromSettings(ps),
12461                            isForwardLocked(ps));
12462                    // The package status is changed only if the code path
12463                    // matches between settings and the container id.
12464                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12465                        if (DEBUG_SD_INSTALL) {
12466                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12467                                    + " at code path: " + ps.codePathString);
12468                        }
12469
12470                        // We do have a valid package installed on sdcard
12471                        processCids.put(args, ps.codePathString);
12472                        final int uid = ps.appId;
12473                        if (uid != -1) {
12474                            uidList[num++] = uid;
12475                        }
12476                    } else {
12477                        Log.i(TAG, "Deleting stale container for " + cid);
12478                        removeCids.add(cid);
12479                    }
12480                }
12481            }
12482
12483            if (num > 0) {
12484                // Sort uid list
12485                Arrays.sort(uidList, 0, num);
12486                // Throw away duplicates
12487                uidArr = new int[num];
12488                uidArr[0] = uidList[0];
12489                int di = 0;
12490                for (int i = 1; i < num; i++) {
12491                    if (uidList[i - 1] != uidList[i]) {
12492                        uidArr[di++] = uidList[i];
12493                    }
12494                }
12495            }
12496        }
12497        // Process packages with valid entries.
12498        if (isMounted) {
12499            if (DEBUG_SD_INSTALL)
12500                Log.i(TAG, "Loading packages");
12501            loadMediaPackages(processCids, uidArr, removeCids);
12502            startCleaningPackages();
12503        } else {
12504            if (DEBUG_SD_INSTALL)
12505                Log.i(TAG, "Unloading packages");
12506            unloadMediaPackages(processCids, uidArr, reportStatus);
12507        }
12508    }
12509
12510   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12511           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12512        int size = pkgList.size();
12513        if (size > 0) {
12514            // Send broadcasts here
12515            Bundle extras = new Bundle();
12516            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12517                    .toArray(new String[size]));
12518            if (uidArr != null) {
12519                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12520            }
12521            if (replacing) {
12522                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12523            }
12524            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12525                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12526            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12527        }
12528    }
12529
12530   /*
12531     * Look at potentially valid container ids from processCids If package
12532     * information doesn't match the one on record or package scanning fails,
12533     * the cid is added to list of removeCids. We currently don't delete stale
12534     * containers.
12535     */
12536   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12537            HashSet<String> removeCids) {
12538        ArrayList<String> pkgList = new ArrayList<String>();
12539        Set<AsecInstallArgs> keys = processCids.keySet();
12540        boolean doGc = false;
12541        for (AsecInstallArgs args : keys) {
12542            String codePath = processCids.get(args);
12543            if (DEBUG_SD_INSTALL)
12544                Log.i(TAG, "Loading container : " + args.cid);
12545            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12546            try {
12547                // Make sure there are no container errors first.
12548                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12549                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12550                            + " when installing from sdcard");
12551                    continue;
12552                }
12553                // Check code path here.
12554                if (codePath == null || !codePath.equals(args.getCodePath())) {
12555                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12556                            + " does not match one in settings " + codePath);
12557                    continue;
12558                }
12559                // Parse package
12560                int parseFlags = mDefParseFlags;
12561                if (args.isExternal()) {
12562                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12563                }
12564                if (args.isFwdLocked()) {
12565                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12566                }
12567
12568                doGc = true;
12569                synchronized (mInstallLock) {
12570                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
12571                            0, 0, null, null);
12572                    // Scan the package
12573                    if (pkg != null) {
12574                        /*
12575                         * TODO why is the lock being held? doPostInstall is
12576                         * called in other places without the lock. This needs
12577                         * to be straightened out.
12578                         */
12579                        // writer
12580                        synchronized (mPackages) {
12581                            retCode = PackageManager.INSTALL_SUCCEEDED;
12582                            pkgList.add(pkg.packageName);
12583                            // Post process args
12584                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12585                                    pkg.applicationInfo.uid);
12586                        }
12587                    } else {
12588                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12589                    }
12590                }
12591
12592            } finally {
12593                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12594                    // Don't destroy container here. Wait till gc clears things
12595                    // up.
12596                    removeCids.add(args.cid);
12597                }
12598            }
12599        }
12600        // writer
12601        synchronized (mPackages) {
12602            // If the platform SDK has changed since the last time we booted,
12603            // we need to re-grant app permission to catch any new ones that
12604            // appear. This is really a hack, and means that apps can in some
12605            // cases get permissions that the user didn't initially explicitly
12606            // allow... it would be nice to have some better way to handle
12607            // this situation.
12608            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12609            if (regrantPermissions)
12610                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12611                        + mSdkVersion + "; regranting permissions for external storage");
12612            mSettings.mExternalSdkPlatform = mSdkVersion;
12613
12614            // Make sure group IDs have been assigned, and any permission
12615            // changes in other apps are accounted for
12616            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12617                    | (regrantPermissions
12618                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12619                            : 0));
12620
12621            mSettings.updateExternalDatabaseVersion();
12622
12623            // can downgrade to reader
12624            // Persist settings
12625            mSettings.writeLPr();
12626        }
12627        // Send a broadcast to let everyone know we are done processing
12628        if (pkgList.size() > 0) {
12629            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12630        }
12631        // Force gc to avoid any stale parser references that we might have.
12632        if (doGc) {
12633            Runtime.getRuntime().gc();
12634        }
12635        // List stale containers and destroy stale temporary containers.
12636        if (removeCids != null) {
12637            for (String cid : removeCids) {
12638                if (cid.startsWith(mTempContainerPrefix)) {
12639                    Log.i(TAG, "Destroying stale temporary container " + cid);
12640                    PackageHelper.destroySdDir(cid);
12641                } else {
12642                    Log.w(TAG, "Container " + cid + " is stale");
12643               }
12644           }
12645        }
12646    }
12647
12648   /*
12649     * Utility method to unload a list of specified containers
12650     */
12651    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12652        // Just unmount all valid containers.
12653        for (AsecInstallArgs arg : cidArgs) {
12654            synchronized (mInstallLock) {
12655                arg.doPostDeleteLI(false);
12656           }
12657       }
12658   }
12659
12660    /*
12661     * Unload packages mounted on external media. This involves deleting package
12662     * data from internal structures, sending broadcasts about diabled packages,
12663     * gc'ing to free up references, unmounting all secure containers
12664     * corresponding to packages on external media, and posting a
12665     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12666     * that we always have to post this message if status has been requested no
12667     * matter what.
12668     */
12669    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12670            final boolean reportStatus) {
12671        if (DEBUG_SD_INSTALL)
12672            Log.i(TAG, "unloading media packages");
12673        ArrayList<String> pkgList = new ArrayList<String>();
12674        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12675        final Set<AsecInstallArgs> keys = processCids.keySet();
12676        for (AsecInstallArgs args : keys) {
12677            String pkgName = args.getPackageName();
12678            if (DEBUG_SD_INSTALL)
12679                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12680            // Delete package internally
12681            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12682            synchronized (mInstallLock) {
12683                boolean res = deletePackageLI(pkgName, null, false, null, null,
12684                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12685                if (res) {
12686                    pkgList.add(pkgName);
12687                } else {
12688                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12689                    failedList.add(args);
12690                }
12691            }
12692        }
12693
12694        // reader
12695        synchronized (mPackages) {
12696            // We didn't update the settings after removing each package;
12697            // write them now for all packages.
12698            mSettings.writeLPr();
12699        }
12700
12701        // We have to absolutely send UPDATED_MEDIA_STATUS only
12702        // after confirming that all the receivers processed the ordered
12703        // broadcast when packages get disabled, force a gc to clean things up.
12704        // and unload all the containers.
12705        if (pkgList.size() > 0) {
12706            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12707                    new IIntentReceiver.Stub() {
12708                public void performReceive(Intent intent, int resultCode, String data,
12709                        Bundle extras, boolean ordered, boolean sticky,
12710                        int sendingUser) throws RemoteException {
12711                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12712                            reportStatus ? 1 : 0, 1, keys);
12713                    mHandler.sendMessage(msg);
12714                }
12715            });
12716        } else {
12717            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12718                    keys);
12719            mHandler.sendMessage(msg);
12720        }
12721    }
12722
12723    /** Binder call */
12724    @Override
12725    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12726            final int flags) {
12727        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12728        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12729        int returnCode = PackageManager.MOVE_SUCCEEDED;
12730        int currFlags = 0;
12731        int newFlags = 0;
12732        // reader
12733        synchronized (mPackages) {
12734            PackageParser.Package pkg = mPackages.get(packageName);
12735            if (pkg == null) {
12736                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12737            } else {
12738                // Disable moving fwd locked apps and system packages
12739                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12740                    Slog.w(TAG, "Cannot move system application");
12741                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12742                } else if (pkg.mOperationPending) {
12743                    Slog.w(TAG, "Attempt to move package which has pending operations");
12744                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12745                } else {
12746                    // Find install location first
12747                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12748                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12749                        Slog.w(TAG, "Ambigous flags specified for move location.");
12750                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12751                    } else {
12752                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12753                                : PackageManager.INSTALL_INTERNAL;
12754                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12755                                : PackageManager.INSTALL_INTERNAL;
12756
12757                        if (newFlags == currFlags) {
12758                            Slog.w(TAG, "No move required. Trying to move to same location");
12759                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12760                        } else {
12761                            if (isForwardLocked(pkg)) {
12762                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12763                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12764                            }
12765                        }
12766                    }
12767                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12768                        pkg.mOperationPending = true;
12769                    }
12770                }
12771            }
12772
12773            /*
12774             * TODO this next block probably shouldn't be inside the lock. We
12775             * can't guarantee these won't change after this is fired off
12776             * anyway.
12777             */
12778            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12779                processPendingMove(new MoveParams(null, observer, 0, packageName, null,
12780                        null, -1, user),
12781                        returnCode);
12782            } else {
12783                Message msg = mHandler.obtainMessage(INIT_COPY);
12784                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
12785                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
12786                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir,
12787                        instructionSet);
12788                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12789                        pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user);
12790                msg.obj = mp;
12791                mHandler.sendMessage(msg);
12792            }
12793        }
12794    }
12795
12796    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12797        // Queue up an async operation since the package deletion may take a
12798        // little while.
12799        mHandler.post(new Runnable() {
12800            public void run() {
12801                // TODO fix this; this does nothing.
12802                mHandler.removeCallbacks(this);
12803                int returnCode = currentStatus;
12804                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12805                    int uidArr[] = null;
12806                    ArrayList<String> pkgList = null;
12807                    synchronized (mPackages) {
12808                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12809                        if (pkg == null) {
12810                            Slog.w(TAG, " Package " + mp.packageName
12811                                    + " doesn't exist. Aborting move");
12812                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12813                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
12814                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12815                                    + mp.srcArgs.getCodePath() + " to "
12816                                    + pkg.applicationInfo.sourceDir
12817                                    + " Aborting move and returning error");
12818                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12819                        } else {
12820                            uidArr = new int[] {
12821                                pkg.applicationInfo.uid
12822                            };
12823                            pkgList = new ArrayList<String>();
12824                            pkgList.add(mp.packageName);
12825                        }
12826                    }
12827                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12828                        // Send resources unavailable broadcast
12829                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12830                        // Update package code and resource paths
12831                        synchronized (mInstallLock) {
12832                            synchronized (mPackages) {
12833                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12834                                // Recheck for package again.
12835                                if (pkg == null) {
12836                                    Slog.w(TAG, " Package " + mp.packageName
12837                                            + " doesn't exist. Aborting move");
12838                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12839                                } else if (!mp.srcArgs.getCodePath().equals(
12840                                        pkg.applicationInfo.sourceDir)) {
12841                                    Slog.w(TAG, "Package " + mp.packageName
12842                                            + " code path changed from " + mp.srcArgs.getCodePath()
12843                                            + " to " + pkg.applicationInfo.sourceDir
12844                                            + " Aborting move and returning error");
12845                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12846                                } else {
12847                                    final String oldCodePath = pkg.mPath;
12848                                    final String newCodePath = mp.targetArgs.getCodePath();
12849                                    final String newResPath = mp.targetArgs.getResourcePath();
12850                                    final String newNativePath = mp.targetArgs
12851                                            .getNativeLibraryPath();
12852
12853                                    final File newNativeDir = new File(newNativePath);
12854
12855                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12856                                        // NOTE: We do not report any errors from the APK scan and library
12857                                        // copy at this point.
12858                                        NativeLibraryHelper.ApkHandle handle =
12859                                                new NativeLibraryHelper.ApkHandle(newCodePath);
12860                                        final int abi = NativeLibraryHelper.findSupportedAbi(
12861                                                handle, Build.SUPPORTED_ABIS);
12862                                        if (abi >= 0) {
12863                                            NativeLibraryHelper.copyNativeBinariesIfNeededLI(
12864                                                    handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
12865                                        }
12866                                        handle.close();
12867                                    }
12868                                    final int[] users = sUserManager.getUserIds();
12869                                    for (int user : users) {
12870                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
12871                                                newNativePath, user) < 0) {
12872                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12873                                        }
12874                                    }
12875
12876                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12877                                        pkg.mPath = newCodePath;
12878                                        // Move dex files around
12879                                        if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
12880                                            // Moving of dex files failed. Set
12881                                            // error code and abort move.
12882                                            pkg.mPath = pkg.mScanPath;
12883                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12884                                        }
12885                                    }
12886
12887                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12888                                        pkg.mScanPath = newCodePath;
12889                                        pkg.applicationInfo.sourceDir = newCodePath;
12890                                        pkg.applicationInfo.publicSourceDir = newResPath;
12891                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
12892                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
12893                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
12894                                        ps.codePathString = ps.codePath.getPath();
12895                                        ps.resourcePath = new File(
12896                                                pkg.applicationInfo.publicSourceDir);
12897                                        ps.resourcePathString = ps.resourcePath.getPath();
12898                                        ps.nativeLibraryPathString = newNativePath;
12899                                        // Set the application info flag
12900                                        // correctly.
12901                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
12902                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12903                                        } else {
12904                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12905                                        }
12906                                        ps.setFlags(pkg.applicationInfo.flags);
12907                                        mAppDirs.remove(oldCodePath);
12908                                        mAppDirs.put(newCodePath, pkg);
12909                                        // Persist settings
12910                                        mSettings.writeLPr();
12911                                    }
12912                                }
12913                            }
12914                        }
12915                        // Send resources available broadcast
12916                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12917                    }
12918                }
12919                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12920                    // Clean up failed installation
12921                    if (mp.targetArgs != null) {
12922                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
12923                                -1);
12924                    }
12925                } else {
12926                    // Force a gc to clear things up.
12927                    Runtime.getRuntime().gc();
12928                    // Delete older code
12929                    synchronized (mInstallLock) {
12930                        mp.srcArgs.doPostDeleteLI(true);
12931                    }
12932                }
12933
12934                // Allow more operations on this file if we didn't fail because
12935                // an operation was already pending for this package.
12936                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
12937                    synchronized (mPackages) {
12938                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12939                        if (pkg != null) {
12940                            pkg.mOperationPending = false;
12941                       }
12942                   }
12943                }
12944
12945                IPackageMoveObserver observer = mp.observer;
12946                if (observer != null) {
12947                    try {
12948                        observer.packageMoved(mp.packageName, returnCode);
12949                    } catch (RemoteException e) {
12950                        Log.i(TAG, "Observer no longer exists.");
12951                    }
12952                }
12953            }
12954        });
12955    }
12956
12957    @Override
12958    public boolean setInstallLocation(int loc) {
12959        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12960                null);
12961        if (getInstallLocation() == loc) {
12962            return true;
12963        }
12964        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12965                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12966            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12967                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12968            return true;
12969        }
12970        return false;
12971   }
12972
12973    @Override
12974    public int getInstallLocation() {
12975        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12976                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12977                PackageHelper.APP_INSTALL_AUTO);
12978    }
12979
12980    /** Called by UserManagerService */
12981    void cleanUpUserLILPw(int userHandle) {
12982        mDirtyUsers.remove(userHandle);
12983        mSettings.removeUserLPr(userHandle);
12984        mPendingBroadcasts.remove(userHandle);
12985        if (mInstaller != null) {
12986            // Technically, we shouldn't be doing this with the package lock
12987            // held.  However, this is very rare, and there is already so much
12988            // other disk I/O going on, that we'll let it slide for now.
12989            mInstaller.removeUserDataDirs(userHandle);
12990        }
12991    }
12992
12993    /** Called by UserManagerService */
12994    void createNewUserLILPw(int userHandle, File path) {
12995        if (mInstaller != null) {
12996            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12997        }
12998    }
12999
13000    @Override
13001    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13002        mContext.enforceCallingOrSelfPermission(
13003                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13004                "Only package verification agents can read the verifier device identity");
13005
13006        synchronized (mPackages) {
13007            return mSettings.getVerifierDeviceIdentityLPw();
13008        }
13009    }
13010
13011    @Override
13012    public void setPermissionEnforced(String permission, boolean enforced) {
13013        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13014        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13015            synchronized (mPackages) {
13016                if (mSettings.mReadExternalStorageEnforced == null
13017                        || mSettings.mReadExternalStorageEnforced != enforced) {
13018                    mSettings.mReadExternalStorageEnforced = enforced;
13019                    mSettings.writeLPr();
13020                }
13021            }
13022            // kill any non-foreground processes so we restart them and
13023            // grant/revoke the GID.
13024            final IActivityManager am = ActivityManagerNative.getDefault();
13025            if (am != null) {
13026                final long token = Binder.clearCallingIdentity();
13027                try {
13028                    am.killProcessesBelowForeground("setPermissionEnforcement");
13029                } catch (RemoteException e) {
13030                } finally {
13031                    Binder.restoreCallingIdentity(token);
13032                }
13033            }
13034        } else {
13035            throw new IllegalArgumentException("No selective enforcement for " + permission);
13036        }
13037    }
13038
13039    @Override
13040    @Deprecated
13041    public boolean isPermissionEnforced(String permission) {
13042        return true;
13043    }
13044
13045    @Override
13046    public boolean isStorageLow() {
13047        final long token = Binder.clearCallingIdentity();
13048        try {
13049            final DeviceStorageMonitorInternal
13050                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13051            if (dsm != null) {
13052                return dsm.isMemoryLow();
13053            } else {
13054                return false;
13055            }
13056        } finally {
13057            Binder.restoreCallingIdentity(token);
13058        }
13059    }
13060
13061    @Override
13062    public IPackageInstaller getPackageInstaller() {
13063        return mInstallerService;
13064    }
13065}
13066