PackageManagerService.java revision 34f6084bc21b07ae9112be6e7a8f50c49828ac9c
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.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.os.Process.PACKAGE_INFO_GID;
27import static android.os.Process.SYSTEM_UID;
28import static android.system.OsConstants.S_IRGRP;
29import static android.system.OsConstants.S_IROTH;
30import static android.system.OsConstants.S_IRWXU;
31import static android.system.OsConstants.S_IXGRP;
32import static android.system.OsConstants.S_IXOTH;
33import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
34import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
35import static com.android.internal.util.ArrayUtils.appendInt;
36import static com.android.internal.util.ArrayUtils.removeInt;
37
38import com.android.internal.R;
39import com.android.internal.app.IMediaContainerService;
40import com.android.internal.app.ResolverActivity;
41import com.android.internal.content.NativeLibraryHelper;
42import com.android.internal.content.PackageHelper;
43import com.android.internal.util.FastPrintWriter;
44import com.android.internal.util.FastXmlSerializer;
45import com.android.internal.util.XmlUtils;
46import com.android.server.EventLogTags;
47import com.android.server.IntentResolver;
48import com.android.server.LocalServices;
49import com.android.server.ServiceThread;
50import com.android.server.Watchdog;
51import com.android.server.pm.Settings.DatabaseVersion;
52import com.android.server.storage.DeviceStorageMonitorInternal;
53import com.android.server.storage.DeviceStorageMonitorInternal;
54
55import org.xmlpull.v1.XmlPullParser;
56import org.xmlpull.v1.XmlPullParserException;
57import org.xmlpull.v1.XmlSerializer;
58
59import android.app.ActivityManager;
60import android.app.ActivityManagerNative;
61import android.app.IActivityManager;
62import android.app.admin.IDevicePolicyManager;
63import android.app.backup.IBackupManager;
64import android.content.BroadcastReceiver;
65import android.content.ComponentName;
66import android.content.Context;
67import android.content.IIntentReceiver;
68import android.content.Intent;
69import android.content.IntentFilter;
70import android.content.IntentSender;
71import android.content.IntentSender.SendIntentException;
72import android.content.ServiceConnection;
73import android.content.pm.ActivityInfo;
74import android.content.pm.ApplicationInfo;
75import android.content.pm.ContainerEncryptionParams;
76import android.content.pm.FeatureInfo;
77import android.content.pm.IPackageDataObserver;
78import android.content.pm.IPackageDeleteObserver;
79import android.content.pm.IPackageInstallObserver;
80import android.content.pm.IPackageInstallObserver2;
81import android.content.pm.IPackageManager;
82import android.content.pm.IPackageMoveObserver;
83import android.content.pm.IPackageStatsObserver;
84import android.content.pm.InstrumentationInfo;
85import android.content.pm.ManifestDigest;
86import android.content.pm.PackageCleanItem;
87import android.content.pm.PackageInfo;
88import android.content.pm.PackageInfoLite;
89import android.content.pm.PackageManager;
90import android.content.pm.PackageParser.ActivityIntentInfo;
91import android.content.pm.PackageParser;
92import android.content.pm.PackageStats;
93import android.content.pm.PackageUserState;
94import android.content.pm.ParceledListSlice;
95import android.content.pm.PermissionGroupInfo;
96import android.content.pm.PermissionInfo;
97import android.content.pm.ProviderInfo;
98import android.content.pm.ResolveInfo;
99import android.content.pm.ServiceInfo;
100import android.content.pm.Signature;
101import android.content.pm.VerificationParams;
102import android.content.pm.VerifierDeviceIdentity;
103import android.content.pm.VerifierInfo;
104import android.content.res.Resources;
105import android.hardware.display.DisplayManager;
106import android.net.Uri;
107import android.os.Binder;
108import android.os.Build;
109import android.os.Bundle;
110import android.os.Environment;
111import android.os.Environment.UserEnvironment;
112import android.os.FileObserver;
113import android.os.FileUtils;
114import android.os.Handler;
115import android.os.IBinder;
116import android.os.Looper;
117import android.os.Message;
118import android.os.Parcel;
119import android.os.ParcelFileDescriptor;
120import android.os.Process;
121import android.os.RemoteException;
122import android.os.SELinux;
123import android.os.ServiceManager;
124import android.os.SystemClock;
125import android.os.SystemProperties;
126import android.os.UserHandle;
127import android.os.UserManager;
128import android.security.KeyStore;
129import android.security.SystemKeyStore;
130import android.system.ErrnoException;
131import android.system.Os;
132import android.system.StructStat;
133import android.text.TextUtils;
134import android.util.AtomicFile;
135import android.util.DisplayMetrics;
136import android.util.EventLog;
137import android.util.Log;
138import android.util.LogPrinter;
139import android.util.PrintStreamPrinter;
140import android.util.Slog;
141import android.util.SparseArray;
142import android.util.Xml;
143import android.view.Display;
144
145import java.io.BufferedInputStream;
146import java.io.BufferedOutputStream;
147import java.io.File;
148import java.io.FileDescriptor;
149import java.io.FileInputStream;
150import java.io.FileNotFoundException;
151import java.io.FileOutputStream;
152import java.io.FileReader;
153import java.io.FilenameFilter;
154import java.io.IOException;
155import java.io.InputStream;
156import java.io.PrintWriter;
157import java.nio.charset.StandardCharsets;
158import java.security.NoSuchAlgorithmException;
159import java.security.PublicKey;
160import java.security.cert.CertificateEncodingException;
161import java.security.cert.CertificateException;
162import java.text.SimpleDateFormat;
163import java.util.ArrayList;
164import java.util.Arrays;
165import java.util.Collection;
166import java.util.Collections;
167import java.util.Comparator;
168import java.util.Date;
169import java.util.HashMap;
170import java.util.HashSet;
171import java.util.Iterator;
172import java.util.List;
173import java.util.Map;
174import java.util.Set;
175import java.util.concurrent.atomic.AtomicBoolean;
176import java.util.concurrent.atomic.AtomicLong;
177
178import dalvik.system.DexFile;
179import dalvik.system.StaleDexCacheError;
180import dalvik.system.VMRuntime;
181import libcore.io.IoUtils;
182
183/**
184 * Keep track of all those .apks everywhere.
185 *
186 * This is very central to the platform's security; please run the unit
187 * tests whenever making modifications here:
188 *
189mmm frameworks/base/tests/AndroidTests
190adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
191adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
192 *
193 * {@hide}
194 */
195public class PackageManagerService extends IPackageManager.Stub {
196    static final String TAG = "PackageManager";
197    static final boolean DEBUG_SETTINGS = false;
198    static final boolean DEBUG_PREFERRED = false;
199    static final boolean DEBUG_UPGRADE = false;
200    private static final boolean DEBUG_INSTALL = false;
201    private static final boolean DEBUG_REMOVE = false;
202    private static final boolean DEBUG_BROADCASTS = false;
203    private static final boolean DEBUG_SHOW_INFO = false;
204    private static final boolean DEBUG_PACKAGE_INFO = false;
205    private static final boolean DEBUG_INTENT_MATCHING = false;
206    private static final boolean DEBUG_PACKAGE_SCANNING = false;
207    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
208    private static final boolean DEBUG_VERIFY = false;
209    private static final boolean DEBUG_DEXOPT = false;
210
211    private static final int RADIO_UID = Process.PHONE_UID;
212    private static final int LOG_UID = Process.LOG_UID;
213    private static final int NFC_UID = Process.NFC_UID;
214    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
215    private static final int SHELL_UID = Process.SHELL_UID;
216
217    // Cap the size of permission trees that 3rd party apps can define
218    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
219
220    private static final int REMOVE_EVENTS =
221        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
222    private static final int ADD_EVENTS =
223        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
224
225    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
226    // Suffix used during package installation when copying/moving
227    // package apks to install directory.
228    private static final String INSTALL_PACKAGE_SUFFIX = "-";
229
230    static final int SCAN_MONITOR = 1<<0;
231    static final int SCAN_NO_DEX = 1<<1;
232    static final int SCAN_FORCE_DEX = 1<<2;
233    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
234    static final int SCAN_NEW_INSTALL = 1<<4;
235    static final int SCAN_NO_PATHS = 1<<5;
236    static final int SCAN_UPDATE_TIME = 1<<6;
237    static final int SCAN_DEFER_DEX = 1<<7;
238    static final int SCAN_BOOTING = 1<<8;
239    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
240    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
241
242    static final int REMOVE_CHATTY = 1<<16;
243
244    /**
245     * Timeout (in milliseconds) after which the watchdog should declare that
246     * our handler thread is wedged.  The usual default for such things is one
247     * minute but we sometimes do very lengthy I/O operations on this thread,
248     * such as installing multi-gigabyte applications, so ours needs to be longer.
249     */
250    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
251
252    /**
253     * Whether verification is enabled by default.
254     */
255    private static final boolean DEFAULT_VERIFY_ENABLE = true;
256
257    /**
258     * The default maximum time to wait for the verification agent to return in
259     * milliseconds.
260     */
261    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
262
263    /**
264     * The default response for package verification timeout.
265     *
266     * This can be either PackageManager.VERIFICATION_ALLOW or
267     * PackageManager.VERIFICATION_REJECT.
268     */
269    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
270
271    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
272
273    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
274            DEFAULT_CONTAINER_PACKAGE,
275            "com.android.defcontainer.DefaultContainerService");
276
277    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
278
279    private static final String LIB_DIR_NAME = "lib";
280    private static final String LIB64_DIR_NAME = "lib64";
281
282    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
283
284    static final String mTempContainerPrefix = "smdl2tmp";
285
286    private static String sPreferredInstructionSet;
287
288    final ServiceThread mHandlerThread;
289
290    private static final String IDMAP_PREFIX = "/data/resource-cache/";
291    private static final String IDMAP_SUFFIX = "@idmap";
292
293    final PackageHandler mHandler;
294
295    final int mSdkVersion = Build.VERSION.SDK_INT;
296
297    final Context mContext;
298    final boolean mFactoryTest;
299    final boolean mOnlyCore;
300    final DisplayMetrics mMetrics;
301    final int mDefParseFlags;
302    final String[] mSeparateProcesses;
303
304    // This is where all application persistent data goes.
305    final File mAppDataDir;
306
307    // This is where all application persistent data goes for secondary users.
308    final File mUserAppDataDir;
309
310    /** The location for ASEC container files on internal storage. */
311    final String mAsecInternalPath;
312
313    // This is the object monitoring the framework dir.
314    final FileObserver mFrameworkInstallObserver;
315
316    // This is the object monitoring the system app dir.
317    final FileObserver mSystemInstallObserver;
318
319    // This is the object monitoring the privileged system app dir.
320    final FileObserver mPrivilegedInstallObserver;
321
322    // This is the object monitoring the vendor app dir.
323    final FileObserver mVendorInstallObserver;
324
325    // This is the object monitoring the vendor overlay package dir.
326    final FileObserver mVendorOverlayInstallObserver;
327
328    // This is the object monitoring the OEM app dir.
329    final FileObserver mOemInstallObserver;
330
331    // This is the object monitoring mAppInstallDir.
332    final FileObserver mAppInstallObserver;
333
334    // This is the object monitoring mDrmAppPrivateInstallDir.
335    final FileObserver mDrmAppInstallObserver;
336
337    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
338    // LOCK HELD.  Can be called with mInstallLock held.
339    final Installer mInstaller;
340
341    final File mAppInstallDir;
342
343    /**
344     * Directory to which applications installed internally have native
345     * libraries copied.
346     */
347    private File mAppLibInstallDir;
348
349    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
350    // apps.
351    final File mDrmAppPrivateInstallDir;
352
353    // ----------------------------------------------------------------
354
355    // Lock for state used when installing and doing other long running
356    // operations.  Methods that must be called with this lock held have
357    // the suffix "LI".
358    final Object mInstallLock = new Object();
359
360    // These are the directories in the 3rd party applications installed dir
361    // that we have currently loaded packages from.  Keys are the application's
362    // installed zip file (absolute codePath), and values are Package.
363    final HashMap<String, PackageParser.Package> mAppDirs =
364            new HashMap<String, PackageParser.Package>();
365
366    // Information for the parser to write more useful error messages.
367    int mLastScanError;
368
369    // ----------------------------------------------------------------
370
371    // Keys are String (package name), values are Package.  This also serves
372    // as the lock for the global state.  Methods that must be called with
373    // this lock held have the prefix "LP".
374    final HashMap<String, PackageParser.Package> mPackages =
375            new HashMap<String, PackageParser.Package>();
376
377    // Tracks available target package names -> overlay package paths.
378    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
379        new HashMap<String, HashMap<String, PackageParser.Package>>();
380
381    final Settings mSettings;
382    boolean mRestoredSettings;
383
384    // Group-ids that are given to all packages as read from etc/permissions/*.xml.
385    int[] mGlobalGids;
386
387    // These are the built-in uid -> permission mappings that were read from the
388    // etc/permissions.xml file.
389    final SparseArray<HashSet<String>> mSystemPermissions =
390            new SparseArray<HashSet<String>>();
391
392    static final class SharedLibraryEntry {
393        final String path;
394        final String apk;
395
396        SharedLibraryEntry(String _path, String _apk) {
397            path = _path;
398            apk = _apk;
399        }
400    }
401
402    // These are the built-in shared libraries that were read from the
403    // etc/permissions.xml file.
404    final HashMap<String, SharedLibraryEntry> mSharedLibraries
405            = new HashMap<String, SharedLibraryEntry>();
406
407    // Temporary for building the final shared libraries for an .apk.
408    String[] mTmpSharedLibraries = null;
409
410    // These are the features this devices supports that were read from the
411    // etc/permissions.xml file.
412    final HashMap<String, FeatureInfo> mAvailableFeatures =
413            new HashMap<String, FeatureInfo>();
414
415    // If mac_permissions.xml was found for seinfo labeling.
416    boolean mFoundPolicyFile;
417
418    // If a recursive restorecon of /data/data/<pkg> is needed.
419    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
420
421    // All available activities, for your resolving pleasure.
422    final ActivityIntentResolver mActivities =
423            new ActivityIntentResolver();
424
425    // All available receivers, for your resolving pleasure.
426    final ActivityIntentResolver mReceivers =
427            new ActivityIntentResolver();
428
429    // All available services, for your resolving pleasure.
430    final ServiceIntentResolver mServices = new ServiceIntentResolver();
431
432    // All available providers, for your resolving pleasure.
433    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
434
435    // Mapping from provider base names (first directory in content URI codePath)
436    // to the provider information.
437    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
438            new HashMap<String, PackageParser.Provider>();
439
440    // Mapping from instrumentation class names to info about them.
441    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
442            new HashMap<ComponentName, PackageParser.Instrumentation>();
443
444    // Mapping from permission names to info about them.
445    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
446            new HashMap<String, PackageParser.PermissionGroup>();
447
448    // Packages whose data we have transfered into another package, thus
449    // should no longer exist.
450    final HashSet<String> mTransferedPackages = new HashSet<String>();
451
452    // Broadcast actions that are only available to the system.
453    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
454
455    /** List of packages waiting for verification. */
456    final SparseArray<PackageVerificationState> mPendingVerification
457            = new SparseArray<PackageVerificationState>();
458
459    HashSet<PackageParser.Package> mDeferredDexOpt = null;
460
461    /** Token for keys in mPendingVerification. */
462    private int mPendingVerificationToken = 0;
463
464    boolean mSystemReady;
465    boolean mSafeMode;
466    boolean mHasSystemUidErrors;
467
468    ApplicationInfo mAndroidApplication;
469    final ActivityInfo mResolveActivity = new ActivityInfo();
470    final ResolveInfo mResolveInfo = new ResolveInfo();
471    ComponentName mResolveComponentName;
472    PackageParser.Package mPlatformPackage;
473    ComponentName mCustomResolverComponentName;
474
475    boolean mResolverReplaced = false;
476
477    // Set of pending broadcasts for aggregating enable/disable of components.
478    static class PendingPackageBroadcasts {
479        // for each user id, a map of <package name -> components within that package>
480        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
481
482        public PendingPackageBroadcasts() {
483            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
484        }
485
486        public ArrayList<String> get(int userId, String packageName) {
487            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
488            return packages.get(packageName);
489        }
490
491        public void put(int userId, String packageName, ArrayList<String> components) {
492            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
493            packages.put(packageName, components);
494        }
495
496        public void remove(int userId, String packageName) {
497            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
498            if (packages != null) {
499                packages.remove(packageName);
500            }
501        }
502
503        public void remove(int userId) {
504            mUidMap.remove(userId);
505        }
506
507        public int userIdCount() {
508            return mUidMap.size();
509        }
510
511        public int userIdAt(int n) {
512            return mUidMap.keyAt(n);
513        }
514
515        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
516            return mUidMap.get(userId);
517        }
518
519        public int size() {
520            // total number of pending broadcast entries across all userIds
521            int num = 0;
522            for (int i = 0; i< mUidMap.size(); i++) {
523                num += mUidMap.valueAt(i).size();
524            }
525            return num;
526        }
527
528        public void clear() {
529            mUidMap.clear();
530        }
531
532        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
533            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
534            if (map == null) {
535                map = new HashMap<String, ArrayList<String>>();
536                mUidMap.put(userId, map);
537            }
538            return map;
539        }
540    }
541    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
542
543    // Service Connection to remote media container service to copy
544    // package uri's from external media onto secure containers
545    // or internal storage.
546    private IMediaContainerService mContainerService = null;
547
548    static final int SEND_PENDING_BROADCAST = 1;
549    static final int MCS_BOUND = 3;
550    static final int END_COPY = 4;
551    static final int INIT_COPY = 5;
552    static final int MCS_UNBIND = 6;
553    static final int START_CLEANING_PACKAGE = 7;
554    static final int FIND_INSTALL_LOC = 8;
555    static final int POST_INSTALL = 9;
556    static final int MCS_RECONNECT = 10;
557    static final int MCS_GIVE_UP = 11;
558    static final int UPDATED_MEDIA_STATUS = 12;
559    static final int WRITE_SETTINGS = 13;
560    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
561    static final int PACKAGE_VERIFIED = 15;
562    static final int CHECK_PENDING_VERIFICATION = 16;
563
564    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
565
566    // Delay time in millisecs
567    static final int BROADCAST_DELAY = 10 * 1000;
568
569    static UserManagerService sUserManager;
570
571    // Stores a list of users whose package restrictions file needs to be updated
572    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
573
574    final private DefaultContainerConnection mDefContainerConn =
575            new DefaultContainerConnection();
576    class DefaultContainerConnection implements ServiceConnection {
577        public void onServiceConnected(ComponentName name, IBinder service) {
578            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
579            IMediaContainerService imcs =
580                IMediaContainerService.Stub.asInterface(service);
581            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
582        }
583
584        public void onServiceDisconnected(ComponentName name) {
585            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
586        }
587    };
588
589    // Recordkeeping of restore-after-install operations that are currently in flight
590    // between the Package Manager and the Backup Manager
591    class PostInstallData {
592        public InstallArgs args;
593        public PackageInstalledInfo res;
594
595        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
596            args = _a;
597            res = _r;
598        }
599    };
600    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
601    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
602
603    private final String mRequiredVerifierPackage;
604
605    private final PackageUsage mPackageUsage = new PackageUsage();
606
607    private class PackageUsage {
608        private static final int WRITE_INTERVAL
609            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
610
611        private final Object mFileLock = new Object();
612        private final AtomicLong mLastWritten = new AtomicLong(0);
613        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
614
615        private boolean mIsFirstBoot = false;
616
617        boolean isFirstBoot() {
618            return mIsFirstBoot;
619        }
620
621        void write(boolean force) {
622            if (force) {
623                writeInternal();
624                return;
625            }
626            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
627                && !DEBUG_DEXOPT) {
628                return;
629            }
630            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
631                new Thread("PackageUsage_DiskWriter") {
632                    @Override
633                    public void run() {
634                        try {
635                            writeInternal();
636                        } finally {
637                            mBackgroundWriteRunning.set(false);
638                        }
639                    }
640                }.start();
641            }
642        }
643
644        private void writeInternal() {
645            synchronized (mPackages) {
646                synchronized (mFileLock) {
647                    AtomicFile file = getFile();
648                    FileOutputStream f = null;
649                    try {
650                        f = file.startWrite();
651                        BufferedOutputStream out = new BufferedOutputStream(f);
652                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
653                        StringBuilder sb = new StringBuilder();
654                        for (PackageParser.Package pkg : mPackages.values()) {
655                            if (pkg.mLastPackageUsageTimeInMills == 0) {
656                                continue;
657                            }
658                            sb.setLength(0);
659                            sb.append(pkg.packageName);
660                            sb.append(' ');
661                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
662                            sb.append('\n');
663                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
664                        }
665                        out.flush();
666                        file.finishWrite(f);
667                    } catch (IOException e) {
668                        if (f != null) {
669                            file.failWrite(f);
670                        }
671                        Log.e(TAG, "Failed to write package usage times", e);
672                    }
673                }
674            }
675            mLastWritten.set(SystemClock.elapsedRealtime());
676        }
677
678        void readLP() {
679            synchronized (mFileLock) {
680                AtomicFile file = getFile();
681                BufferedInputStream in = null;
682                try {
683                    in = new BufferedInputStream(file.openRead());
684                    StringBuffer sb = new StringBuffer();
685                    while (true) {
686                        String packageName = readToken(in, sb, ' ');
687                        if (packageName == null) {
688                            break;
689                        }
690                        String timeInMillisString = readToken(in, sb, '\n');
691                        if (timeInMillisString == null) {
692                            throw new IOException("Failed to find last usage time for package "
693                                                  + packageName);
694                        }
695                        PackageParser.Package pkg = mPackages.get(packageName);
696                        if (pkg == null) {
697                            continue;
698                        }
699                        long timeInMillis;
700                        try {
701                            timeInMillis = Long.parseLong(timeInMillisString.toString());
702                        } catch (NumberFormatException e) {
703                            throw new IOException("Failed to parse " + timeInMillisString
704                                                  + " as a long.", e);
705                        }
706                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
707                    }
708                } catch (FileNotFoundException expected) {
709                    mIsFirstBoot = true;
710                } catch (IOException e) {
711                    Log.w(TAG, "Failed to read package usage times", e);
712                } finally {
713                    IoUtils.closeQuietly(in);
714                }
715            }
716            mLastWritten.set(SystemClock.elapsedRealtime());
717        }
718
719        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
720                throws IOException {
721            sb.setLength(0);
722            while (true) {
723                int ch = in.read();
724                if (ch == -1) {
725                    if (sb.length() == 0) {
726                        return null;
727                    }
728                    throw new IOException("Unexpected EOF");
729                }
730                if (ch == endOfToken) {
731                    return sb.toString();
732                }
733                sb.append((char)ch);
734            }
735        }
736
737        private AtomicFile getFile() {
738            File dataDir = Environment.getDataDirectory();
739            File systemDir = new File(dataDir, "system");
740            File fname = new File(systemDir, "package-usage.list");
741            return new AtomicFile(fname);
742        }
743    }
744
745    class PackageHandler extends Handler {
746        private boolean mBound = false;
747        final ArrayList<HandlerParams> mPendingInstalls =
748            new ArrayList<HandlerParams>();
749
750        private boolean connectToService() {
751            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
752                    " DefaultContainerService");
753            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
754            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
755            if (mContext.bindServiceAsUser(service, mDefContainerConn,
756                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
757                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
758                mBound = true;
759                return true;
760            }
761            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
762            return false;
763        }
764
765        private void disconnectService() {
766            mContainerService = null;
767            mBound = false;
768            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
769            mContext.unbindService(mDefContainerConn);
770            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
771        }
772
773        PackageHandler(Looper looper) {
774            super(looper);
775        }
776
777        public void handleMessage(Message msg) {
778            try {
779                doHandleMessage(msg);
780            } finally {
781                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
782            }
783        }
784
785        void doHandleMessage(Message msg) {
786            switch (msg.what) {
787                case INIT_COPY: {
788                    HandlerParams params = (HandlerParams) msg.obj;
789                    int idx = mPendingInstalls.size();
790                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
791                    // If a bind was already initiated we dont really
792                    // need to do anything. The pending install
793                    // will be processed later on.
794                    if (!mBound) {
795                        // If this is the only one pending we might
796                        // have to bind to the service again.
797                        if (!connectToService()) {
798                            Slog.e(TAG, "Failed to bind to media container service");
799                            params.serviceError();
800                            return;
801                        } else {
802                            // Once we bind to the service, the first
803                            // pending request will be processed.
804                            mPendingInstalls.add(idx, params);
805                        }
806                    } else {
807                        mPendingInstalls.add(idx, params);
808                        // Already bound to the service. Just make
809                        // sure we trigger off processing the first request.
810                        if (idx == 0) {
811                            mHandler.sendEmptyMessage(MCS_BOUND);
812                        }
813                    }
814                    break;
815                }
816                case MCS_BOUND: {
817                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
818                    if (msg.obj != null) {
819                        mContainerService = (IMediaContainerService) msg.obj;
820                    }
821                    if (mContainerService == null) {
822                        // Something seriously wrong. Bail out
823                        Slog.e(TAG, "Cannot bind to media container service");
824                        for (HandlerParams params : mPendingInstalls) {
825                            // Indicate service bind error
826                            params.serviceError();
827                        }
828                        mPendingInstalls.clear();
829                    } else if (mPendingInstalls.size() > 0) {
830                        HandlerParams params = mPendingInstalls.get(0);
831                        if (params != null) {
832                            if (params.startCopy()) {
833                                // We are done...  look for more work or to
834                                // go idle.
835                                if (DEBUG_SD_INSTALL) Log.i(TAG,
836                                        "Checking for more work or unbind...");
837                                // Delete pending install
838                                if (mPendingInstalls.size() > 0) {
839                                    mPendingInstalls.remove(0);
840                                }
841                                if (mPendingInstalls.size() == 0) {
842                                    if (mBound) {
843                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
844                                                "Posting delayed MCS_UNBIND");
845                                        removeMessages(MCS_UNBIND);
846                                        Message ubmsg = obtainMessage(MCS_UNBIND);
847                                        // Unbind after a little delay, to avoid
848                                        // continual thrashing.
849                                        sendMessageDelayed(ubmsg, 10000);
850                                    }
851                                } else {
852                                    // There are more pending requests in queue.
853                                    // Just post MCS_BOUND message to trigger processing
854                                    // of next pending install.
855                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
856                                            "Posting MCS_BOUND for next work");
857                                    mHandler.sendEmptyMessage(MCS_BOUND);
858                                }
859                            }
860                        }
861                    } else {
862                        // Should never happen ideally.
863                        Slog.w(TAG, "Empty queue");
864                    }
865                    break;
866                }
867                case MCS_RECONNECT: {
868                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
869                    if (mPendingInstalls.size() > 0) {
870                        if (mBound) {
871                            disconnectService();
872                        }
873                        if (!connectToService()) {
874                            Slog.e(TAG, "Failed to bind to media container service");
875                            for (HandlerParams params : mPendingInstalls) {
876                                // Indicate service bind error
877                                params.serviceError();
878                            }
879                            mPendingInstalls.clear();
880                        }
881                    }
882                    break;
883                }
884                case MCS_UNBIND: {
885                    // If there is no actual work left, then time to unbind.
886                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
887
888                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
889                        if (mBound) {
890                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
891
892                            disconnectService();
893                        }
894                    } else if (mPendingInstalls.size() > 0) {
895                        // There are more pending requests in queue.
896                        // Just post MCS_BOUND message to trigger processing
897                        // of next pending install.
898                        mHandler.sendEmptyMessage(MCS_BOUND);
899                    }
900
901                    break;
902                }
903                case MCS_GIVE_UP: {
904                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
905                    mPendingInstalls.remove(0);
906                    break;
907                }
908                case SEND_PENDING_BROADCAST: {
909                    String packages[];
910                    ArrayList<String> components[];
911                    int size = 0;
912                    int uids[];
913                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
914                    synchronized (mPackages) {
915                        if (mPendingBroadcasts == null) {
916                            return;
917                        }
918                        size = mPendingBroadcasts.size();
919                        if (size <= 0) {
920                            // Nothing to be done. Just return
921                            return;
922                        }
923                        packages = new String[size];
924                        components = new ArrayList[size];
925                        uids = new int[size];
926                        int i = 0;  // filling out the above arrays
927
928                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
929                            int packageUserId = mPendingBroadcasts.userIdAt(n);
930                            Iterator<Map.Entry<String, ArrayList<String>>> it
931                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
932                                            .entrySet().iterator();
933                            while (it.hasNext() && i < size) {
934                                Map.Entry<String, ArrayList<String>> ent = it.next();
935                                packages[i] = ent.getKey();
936                                components[i] = ent.getValue();
937                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
938                                uids[i] = (ps != null)
939                                        ? UserHandle.getUid(packageUserId, ps.appId)
940                                        : -1;
941                                i++;
942                            }
943                        }
944                        size = i;
945                        mPendingBroadcasts.clear();
946                    }
947                    // Send broadcasts
948                    for (int i = 0; i < size; i++) {
949                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
950                    }
951                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
952                    break;
953                }
954                case START_CLEANING_PACKAGE: {
955                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
956                    final String packageName = (String)msg.obj;
957                    final int userId = msg.arg1;
958                    final boolean andCode = msg.arg2 != 0;
959                    synchronized (mPackages) {
960                        if (userId == UserHandle.USER_ALL) {
961                            int[] users = sUserManager.getUserIds();
962                            for (int user : users) {
963                                mSettings.addPackageToCleanLPw(
964                                        new PackageCleanItem(user, packageName, andCode));
965                            }
966                        } else {
967                            mSettings.addPackageToCleanLPw(
968                                    new PackageCleanItem(userId, packageName, andCode));
969                        }
970                    }
971                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
972                    startCleaningPackages();
973                } break;
974                case POST_INSTALL: {
975                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
976                    PostInstallData data = mRunningInstalls.get(msg.arg1);
977                    mRunningInstalls.delete(msg.arg1);
978                    boolean deleteOld = false;
979
980                    if (data != null) {
981                        InstallArgs args = data.args;
982                        PackageInstalledInfo res = data.res;
983
984                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
985                            res.removedInfo.sendBroadcast(false, true, false);
986                            Bundle extras = new Bundle(1);
987                            extras.putInt(Intent.EXTRA_UID, res.uid);
988                            // Determine the set of users who are adding this
989                            // package for the first time vs. those who are seeing
990                            // an update.
991                            int[] firstUsers;
992                            int[] updateUsers = new int[0];
993                            if (res.origUsers == null || res.origUsers.length == 0) {
994                                firstUsers = res.newUsers;
995                            } else {
996                                firstUsers = new int[0];
997                                for (int i=0; i<res.newUsers.length; i++) {
998                                    int user = res.newUsers[i];
999                                    boolean isNew = true;
1000                                    for (int j=0; j<res.origUsers.length; j++) {
1001                                        if (res.origUsers[j] == user) {
1002                                            isNew = false;
1003                                            break;
1004                                        }
1005                                    }
1006                                    if (isNew) {
1007                                        int[] newFirst = new int[firstUsers.length+1];
1008                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1009                                                firstUsers.length);
1010                                        newFirst[firstUsers.length] = user;
1011                                        firstUsers = newFirst;
1012                                    } else {
1013                                        int[] newUpdate = new int[updateUsers.length+1];
1014                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1015                                                updateUsers.length);
1016                                        newUpdate[updateUsers.length] = user;
1017                                        updateUsers = newUpdate;
1018                                    }
1019                                }
1020                            }
1021                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1022                                    res.pkg.applicationInfo.packageName,
1023                                    extras, null, null, firstUsers);
1024                            final boolean update = res.removedInfo.removedPackage != null;
1025                            if (update) {
1026                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1027                            }
1028                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1029                                    res.pkg.applicationInfo.packageName,
1030                                    extras, null, null, updateUsers);
1031                            if (update) {
1032                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1033                                        res.pkg.applicationInfo.packageName,
1034                                        extras, null, null, updateUsers);
1035                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1036                                        null, null,
1037                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1038
1039                                // treat asec-hosted packages like removable media on upgrade
1040                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1041                                    if (DEBUG_INSTALL) {
1042                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1043                                                + " is ASEC-hosted -> AVAILABLE");
1044                                    }
1045                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1046                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1047                                    pkgList.add(res.pkg.applicationInfo.packageName);
1048                                    sendResourcesChangedBroadcast(true, true,
1049                                            pkgList,uidArray, null);
1050                                }
1051                            }
1052                            if (res.removedInfo.args != null) {
1053                                // Remove the replaced package's older resources safely now
1054                                deleteOld = true;
1055                            }
1056
1057                            // Log current value of "unknown sources" setting
1058                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1059                                getUnknownSourcesSettings());
1060                        }
1061                        // Force a gc to clear up things
1062                        Runtime.getRuntime().gc();
1063                        // We delete after a gc for applications  on sdcard.
1064                        if (deleteOld) {
1065                            synchronized (mInstallLock) {
1066                                res.removedInfo.args.doPostDeleteLI(true);
1067                            }
1068                        }
1069                        if (args.observer != null) {
1070                            try {
1071                                args.observer.packageInstalled(res.name, res.returnCode);
1072                            } catch (RemoteException e) {
1073                                Slog.i(TAG, "Observer no longer exists.");
1074                            }
1075                        }
1076                        if (args.observer2 != null) {
1077                            try {
1078                                Bundle extras = extrasForInstallResult(res);
1079                                args.observer2.packageInstalled(res.name, extras, res.returnCode);
1080                            } catch (RemoteException e) {
1081                                Slog.i(TAG, "Observer no longer exists.");
1082                            }
1083                        }
1084                    } else {
1085                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1086                    }
1087                } break;
1088                case UPDATED_MEDIA_STATUS: {
1089                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1090                    boolean reportStatus = msg.arg1 == 1;
1091                    boolean doGc = msg.arg2 == 1;
1092                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1093                    if (doGc) {
1094                        // Force a gc to clear up stale containers.
1095                        Runtime.getRuntime().gc();
1096                    }
1097                    if (msg.obj != null) {
1098                        @SuppressWarnings("unchecked")
1099                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1100                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1101                        // Unload containers
1102                        unloadAllContainers(args);
1103                    }
1104                    if (reportStatus) {
1105                        try {
1106                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1107                            PackageHelper.getMountService().finishMediaUpdate();
1108                        } catch (RemoteException e) {
1109                            Log.e(TAG, "MountService not running?");
1110                        }
1111                    }
1112                } break;
1113                case WRITE_SETTINGS: {
1114                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1115                    synchronized (mPackages) {
1116                        removeMessages(WRITE_SETTINGS);
1117                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1118                        mSettings.writeLPr();
1119                        mDirtyUsers.clear();
1120                    }
1121                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1122                } break;
1123                case WRITE_PACKAGE_RESTRICTIONS: {
1124                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1125                    synchronized (mPackages) {
1126                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1127                        for (int userId : mDirtyUsers) {
1128                            mSettings.writePackageRestrictionsLPr(userId);
1129                        }
1130                        mDirtyUsers.clear();
1131                    }
1132                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1133                } break;
1134                case CHECK_PENDING_VERIFICATION: {
1135                    final int verificationId = msg.arg1;
1136                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1137
1138                    if ((state != null) && !state.timeoutExtended()) {
1139                        final InstallArgs args = state.getInstallArgs();
1140                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
1141                        mPendingVerification.remove(verificationId);
1142
1143                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1144
1145                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1146                            Slog.i(TAG, "Continuing with installation of "
1147                                    + args.packageURI.toString());
1148                            state.setVerifierResponse(Binder.getCallingUid(),
1149                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1150                            broadcastPackageVerified(verificationId, args.packageURI,
1151                                    PackageManager.VERIFICATION_ALLOW,
1152                                    state.getInstallArgs().getUser());
1153                            try {
1154                                ret = args.copyApk(mContainerService, true);
1155                            } catch (RemoteException e) {
1156                                Slog.e(TAG, "Could not contact the ContainerService");
1157                            }
1158                        } else {
1159                            broadcastPackageVerified(verificationId, args.packageURI,
1160                                    PackageManager.VERIFICATION_REJECT,
1161                                    state.getInstallArgs().getUser());
1162                        }
1163
1164                        processPendingInstall(args, ret);
1165                        mHandler.sendEmptyMessage(MCS_UNBIND);
1166                    }
1167                    break;
1168                }
1169                case PACKAGE_VERIFIED: {
1170                    final int verificationId = msg.arg1;
1171
1172                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1173                    if (state == null) {
1174                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1175                        break;
1176                    }
1177
1178                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1179
1180                    state.setVerifierResponse(response.callerUid, response.code);
1181
1182                    if (state.isVerificationComplete()) {
1183                        mPendingVerification.remove(verificationId);
1184
1185                        final InstallArgs args = state.getInstallArgs();
1186
1187                        int ret;
1188                        if (state.isInstallAllowed()) {
1189                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1190                            broadcastPackageVerified(verificationId, args.packageURI,
1191                                    response.code, state.getInstallArgs().getUser());
1192                            try {
1193                                ret = args.copyApk(mContainerService, true);
1194                            } catch (RemoteException e) {
1195                                Slog.e(TAG, "Could not contact the ContainerService");
1196                            }
1197                        } else {
1198                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1199                        }
1200
1201                        processPendingInstall(args, ret);
1202
1203                        mHandler.sendEmptyMessage(MCS_UNBIND);
1204                    }
1205
1206                    break;
1207                }
1208            }
1209        }
1210    }
1211
1212    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1213        Bundle extras = null;
1214        switch (res.returnCode) {
1215            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1216                extras = new Bundle();
1217                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1218                        res.origPermission);
1219                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1220                        res.origPackage);
1221                break;
1222            }
1223        }
1224        return extras;
1225    }
1226
1227    void scheduleWriteSettingsLocked() {
1228        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1229            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1230        }
1231    }
1232
1233    void scheduleWritePackageRestrictionsLocked(int userId) {
1234        if (!sUserManager.exists(userId)) return;
1235        mDirtyUsers.add(userId);
1236        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1237            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1238        }
1239    }
1240
1241    public static final IPackageManager main(Context context, Installer installer,
1242            boolean factoryTest, boolean onlyCore) {
1243        PackageManagerService m = new PackageManagerService(context, installer,
1244                factoryTest, onlyCore);
1245        ServiceManager.addService("package", m);
1246        return m;
1247    }
1248
1249    static String[] splitString(String str, char sep) {
1250        int count = 1;
1251        int i = 0;
1252        while ((i=str.indexOf(sep, i)) >= 0) {
1253            count++;
1254            i++;
1255        }
1256
1257        String[] res = new String[count];
1258        i=0;
1259        count = 0;
1260        int lastI=0;
1261        while ((i=str.indexOf(sep, i)) >= 0) {
1262            res[count] = str.substring(lastI, i);
1263            count++;
1264            i++;
1265            lastI = i;
1266        }
1267        res[count] = str.substring(lastI, str.length());
1268        return res;
1269    }
1270
1271    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1272        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1273                Context.DISPLAY_SERVICE);
1274        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1275    }
1276
1277    public PackageManagerService(Context context, Installer installer,
1278            boolean factoryTest, boolean onlyCore) {
1279        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1280                SystemClock.uptimeMillis());
1281
1282        if (mSdkVersion <= 0) {
1283            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1284        }
1285
1286        mContext = context;
1287        mFactoryTest = factoryTest;
1288        mOnlyCore = onlyCore;
1289        mMetrics = new DisplayMetrics();
1290        mSettings = new Settings(context);
1291        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1292                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1293        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1294                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1295        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1296                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1297        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1298                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1299        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1300                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1301        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1302                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1303
1304        String separateProcesses = SystemProperties.get("debug.separate_processes");
1305        if (separateProcesses != null && separateProcesses.length() > 0) {
1306            if ("*".equals(separateProcesses)) {
1307                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1308                mSeparateProcesses = null;
1309                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1310            } else {
1311                mDefParseFlags = 0;
1312                mSeparateProcesses = separateProcesses.split(",");
1313                Slog.w(TAG, "Running with debug.separate_processes: "
1314                        + separateProcesses);
1315            }
1316        } else {
1317            mDefParseFlags = 0;
1318            mSeparateProcesses = null;
1319        }
1320
1321        mInstaller = installer;
1322
1323        getDefaultDisplayMetrics(context, mMetrics);
1324
1325        synchronized (mInstallLock) {
1326        // writer
1327        synchronized (mPackages) {
1328            mHandlerThread = new ServiceThread(TAG,
1329                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1330            mHandlerThread.start();
1331            mHandler = new PackageHandler(mHandlerThread.getLooper());
1332            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1333
1334            File dataDir = Environment.getDataDirectory();
1335            mAppDataDir = new File(dataDir, "data");
1336            mAppInstallDir = new File(dataDir, "app");
1337            mAppLibInstallDir = new File(dataDir, "app-lib");
1338            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1339            mUserAppDataDir = new File(dataDir, "user");
1340            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1341
1342            sUserManager = new UserManagerService(context, this,
1343                    mInstallLock, mPackages);
1344
1345            // Read permissions and features from system
1346            readPermissions(Environment.buildPath(
1347                    Environment.getRootDirectory(), "etc", "permissions"), false);
1348            // Only read features from OEM
1349            readPermissions(Environment.buildPath(
1350                    Environment.getOemDirectory(), "etc", "permissions"), true);
1351
1352            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1353
1354            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1355                    mSdkVersion, mOnlyCore);
1356
1357            String customResolverActivity = Resources.getSystem().getString(
1358                    R.string.config_customResolverActivity);
1359            if (TextUtils.isEmpty(customResolverActivity)) {
1360                customResolverActivity = null;
1361            } else {
1362                mCustomResolverComponentName = ComponentName.unflattenFromString(
1363                        customResolverActivity);
1364            }
1365
1366            long startTime = SystemClock.uptimeMillis();
1367
1368            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1369                    startTime);
1370
1371            // Set flag to monitor and not change apk file paths when
1372            // scanning install directories.
1373            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1374
1375            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1376
1377            /**
1378             * Add everything in the in the boot class path to the
1379             * list of process files because dexopt will have been run
1380             * if necessary during zygote startup.
1381             */
1382            String bootClassPath = System.getProperty("java.boot.class.path");
1383            if (bootClassPath != null) {
1384                String[] paths = splitString(bootClassPath, ':');
1385                for (int i=0; i<paths.length; i++) {
1386                    alreadyDexOpted.add(paths[i]);
1387                }
1388            } else {
1389                Slog.w(TAG, "No BOOTCLASSPATH found!");
1390            }
1391
1392            boolean didDexOptLibraryOrTool = false;
1393
1394            final List<String> instructionSets = getAllInstructionSets();
1395
1396            /**
1397             * Ensure all external libraries have had dexopt run on them.
1398             */
1399            if (mSharedLibraries.size() > 0) {
1400                // NOTE: For now, we're compiling these system "shared libraries"
1401                // (and framework jars) into all available architectures. It's possible
1402                // to compile them only when we come across an app that uses them (there's
1403                // already logic for that in scanPackageLI) but that adds some complexity.
1404                for (String instructionSet : instructionSets) {
1405                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1406                        final String lib = libEntry.path;
1407                        if (lib == null) {
1408                            continue;
1409                        }
1410
1411                        try {
1412                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1413                                alreadyDexOpted.add(lib);
1414
1415                                // The list of "shared libraries" we have at this point is
1416                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1417                                didDexOptLibraryOrTool = true;
1418                            }
1419                        } catch (FileNotFoundException e) {
1420                            Slog.w(TAG, "Library not found: " + lib);
1421                        } catch (IOException e) {
1422                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1423                                    + e.getMessage());
1424                        }
1425                    }
1426                }
1427            }
1428
1429            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1430
1431            // Gross hack for now: we know this file doesn't contain any
1432            // code, so don't dexopt it to avoid the resulting log spew.
1433            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1434
1435            // Gross hack for now: we know this file is only part of
1436            // the boot class path for art, so don't dexopt it to
1437            // avoid the resulting log spew.
1438            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1439
1440            /**
1441             * And there are a number of commands implemented in Java, which
1442             * we currently need to do the dexopt on so that they can be
1443             * run from a non-root shell.
1444             */
1445            String[] frameworkFiles = frameworkDir.list();
1446            if (frameworkFiles != null) {
1447                // TODO: We could compile these only for the most preferred ABI. We should
1448                // first double check that the dex files for these commands are not referenced
1449                // by other system apps.
1450                for (String instructionSet : instructionSets) {
1451                    for (int i=0; i<frameworkFiles.length; i++) {
1452                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1453                        String path = libPath.getPath();
1454                        // Skip the file if we already did it.
1455                        if (alreadyDexOpted.contains(path)) {
1456                            continue;
1457                        }
1458                        // Skip the file if it is not a type we want to dexopt.
1459                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1460                            continue;
1461                        }
1462                        try {
1463                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1464                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1465                                didDexOptLibraryOrTool = true;
1466                            }
1467                        } catch (FileNotFoundException e) {
1468                            Slog.w(TAG, "Jar not found: " + path);
1469                        } catch (IOException e) {
1470                            Slog.w(TAG, "Exception reading jar: " + path, e);
1471                        }
1472                    }
1473                }
1474            }
1475
1476            if (didDexOptLibraryOrTool) {
1477                pruneDexFiles(new File(dataDir, "dalvik-cache"));
1478            }
1479
1480            // Collect vendor overlay packages.
1481            // (Do this before scanning any apps.)
1482            // For security and version matching reason, only consider
1483            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1484            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1485            mVendorOverlayInstallObserver = new AppDirObserver(
1486                vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1487            mVendorOverlayInstallObserver.startWatching();
1488            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1489                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1490
1491            // Find base frameworks (resource packages without code).
1492            mFrameworkInstallObserver = new AppDirObserver(
1493                frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1494            mFrameworkInstallObserver.startWatching();
1495            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1496                    | PackageParser.PARSE_IS_SYSTEM_DIR
1497                    | PackageParser.PARSE_IS_PRIVILEGED,
1498                    scanMode | SCAN_NO_DEX, 0);
1499
1500            // Collected privileged system packages.
1501            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1502            mPrivilegedInstallObserver = new AppDirObserver(
1503                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1504            mPrivilegedInstallObserver.startWatching();
1505                scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1506                        | PackageParser.PARSE_IS_SYSTEM_DIR
1507                        | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1508
1509            // Collect ordinary system packages.
1510            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1511            mSystemInstallObserver = new AppDirObserver(
1512                systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1513            mSystemInstallObserver.startWatching();
1514            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1515                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1516
1517            // Collect all vendor packages.
1518            File vendorAppDir = new File("/vendor/app");
1519            try {
1520                vendorAppDir = vendorAppDir.getCanonicalFile();
1521            } catch (IOException e) {
1522                // failed to look up canonical path, continue with original one
1523            }
1524            mVendorInstallObserver = new AppDirObserver(
1525                vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1526            mVendorInstallObserver.startWatching();
1527            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1528                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1529
1530            // Collect all OEM packages.
1531            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1532            mOemInstallObserver = new AppDirObserver(
1533                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1534            mOemInstallObserver.startWatching();
1535            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1536                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1537
1538            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1539            mInstaller.moveFiles();
1540
1541            // Prune any system packages that no longer exist.
1542            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1543            if (!mOnlyCore) {
1544                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1545                while (psit.hasNext()) {
1546                    PackageSetting ps = psit.next();
1547
1548                    /*
1549                     * If this is not a system app, it can't be a
1550                     * disable system app.
1551                     */
1552                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1553                        continue;
1554                    }
1555
1556                    /*
1557                     * If the package is scanned, it's not erased.
1558                     */
1559                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1560                    if (scannedPkg != null) {
1561                        /*
1562                         * If the system app is both scanned and in the
1563                         * disabled packages list, then it must have been
1564                         * added via OTA. Remove it from the currently
1565                         * scanned package so the previously user-installed
1566                         * application can be scanned.
1567                         */
1568                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1569                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1570                                    + "; removing system app");
1571                            removePackageLI(ps, true);
1572                        }
1573
1574                        continue;
1575                    }
1576
1577                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1578                        psit.remove();
1579                        String msg = "System package " + ps.name
1580                                + " no longer exists; wiping its data";
1581                        reportSettingsProblem(Log.WARN, msg);
1582                        removeDataDirsLI(ps.name);
1583                    } else {
1584                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1585                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1586                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1587                        }
1588                    }
1589                }
1590            }
1591
1592            //look for any incomplete package installations
1593            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1594            //clean up list
1595            for(int i = 0; i < deletePkgsList.size(); i++) {
1596                //clean up here
1597                cleanupInstallFailedPackage(deletePkgsList.get(i));
1598            }
1599            //delete tmp files
1600            deleteTempPackageFiles();
1601
1602            // Remove any shared userIDs that have no associated packages
1603            mSettings.pruneSharedUsersLPw();
1604
1605            if (!mOnlyCore) {
1606                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1607                        SystemClock.uptimeMillis());
1608                mAppInstallObserver = new AppDirObserver(
1609                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1610                mAppInstallObserver.startWatching();
1611                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1612
1613                mDrmAppInstallObserver = new AppDirObserver(
1614                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1615                mDrmAppInstallObserver.startWatching();
1616                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1617                        scanMode, 0);
1618
1619                /**
1620                 * Remove disable package settings for any updated system
1621                 * apps that were removed via an OTA. If they're not a
1622                 * previously-updated app, remove them completely.
1623                 * Otherwise, just revoke their system-level permissions.
1624                 */
1625                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1626                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1627                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1628
1629                    String msg;
1630                    if (deletedPkg == null) {
1631                        msg = "Updated system package " + deletedAppName
1632                                + " no longer exists; wiping its data";
1633                        removeDataDirsLI(deletedAppName);
1634                    } else {
1635                        msg = "Updated system app + " + deletedAppName
1636                                + " no longer present; removing system privileges for "
1637                                + deletedAppName;
1638
1639                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1640
1641                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1642                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1643                    }
1644                    reportSettingsProblem(Log.WARN, msg);
1645                }
1646            } else {
1647                mAppInstallObserver = null;
1648                mDrmAppInstallObserver = null;
1649            }
1650
1651            // Now that we know all of the shared libraries, update all clients to have
1652            // the correct library paths.
1653            updateAllSharedLibrariesLPw();
1654
1655            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1656                adjustCpuAbisForSharedUserLPw(setting.packages, true /* do dexopt */,
1657                        false /* force dexopt */, false /* defer dexopt */);
1658            }
1659
1660            // Now that we know all the packages we are keeping,
1661            // read and update their last usage times.
1662            mPackageUsage.readLP();
1663
1664            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1665                    SystemClock.uptimeMillis());
1666            Slog.i(TAG, "Time to scan packages: "
1667                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1668                    + " seconds");
1669
1670            // If the platform SDK has changed since the last time we booted,
1671            // we need to re-grant app permission to catch any new ones that
1672            // appear.  This is really a hack, and means that apps can in some
1673            // cases get permissions that the user didn't initially explicitly
1674            // allow...  it would be nice to have some better way to handle
1675            // this situation.
1676            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1677                    != mSdkVersion;
1678            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1679                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1680                    + "; regranting permissions for internal storage");
1681            mSettings.mInternalSdkPlatform = mSdkVersion;
1682
1683            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1684                    | (regrantPermissions
1685                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1686                            : 0));
1687
1688            // If this is the first boot, and it is a normal boot, then
1689            // we need to initialize the default preferred apps.
1690            if (!mRestoredSettings && !onlyCore) {
1691                mSettings.readDefaultPreferredAppsLPw(this, 0);
1692            }
1693
1694            // All the changes are done during package scanning.
1695            mSettings.updateInternalDatabaseVersion();
1696
1697            // can downgrade to reader
1698            mSettings.writeLPr();
1699
1700            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1701                    SystemClock.uptimeMillis());
1702
1703            // Now after opening every single application zip, make sure they
1704            // are all flushed.  Not really needed, but keeps things nice and
1705            // tidy.
1706            Runtime.getRuntime().gc();
1707
1708            mRequiredVerifierPackage = getRequiredVerifierLPr();
1709        } // synchronized (mPackages)
1710        } // synchronized (mInstallLock)
1711    }
1712
1713    private static void pruneDexFiles(File cacheDir) {
1714        // If we had to do a dexopt of one of the previous
1715        // things, then something on the system has changed.
1716        // Consider this significant, and wipe away all other
1717        // existing dexopt files to ensure we don't leave any
1718        // dangling around.
1719        //
1720        // Additionally, delete all dex files from the root directory
1721        // since there shouldn't be any there anyway.
1722        //
1723        // Note: This isn't as good an indicator as it used to be. It
1724        // used to include the boot classpath but at some point
1725        // DexFile.isDexOptNeeded started returning false for the boot
1726        // class path files in all cases. It is very possible in a
1727        // small maintenance release update that the library and tool
1728        // jars may be unchanged but APK could be removed resulting in
1729        // unused dalvik-cache files.
1730        File[] files = cacheDir.listFiles();
1731        if (files != null) {
1732            for (File file : files) {
1733                if (!file.isDirectory()) {
1734                    Slog.i(TAG, "Pruning dalvik file: " + file.getAbsolutePath());
1735                    file.delete();
1736                } else {
1737                    File[] subDirList = file.listFiles();
1738                    if (subDirList != null) {
1739                        for (File subDirFile : subDirList) {
1740                            final String fn = subDirFile.getName();
1741                            if (fn.startsWith("data@app@") || fn.startsWith("data@app-private@")) {
1742                                Slog.i(TAG, "Pruning dalvik file: " + fn);
1743                                subDirFile.delete();
1744                            }
1745                        }
1746                    }
1747                }
1748            }
1749        }
1750    }
1751
1752    @Override
1753    public boolean isFirstBoot() {
1754        return !mRestoredSettings || mPackageUsage.isFirstBoot();
1755    }
1756
1757    @Override
1758    public boolean isOnlyCoreApps() {
1759        return mOnlyCore;
1760    }
1761
1762    private String getRequiredVerifierLPr() {
1763        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1764        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1765                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1766
1767        String requiredVerifier = null;
1768
1769        final int N = receivers.size();
1770        for (int i = 0; i < N; i++) {
1771            final ResolveInfo info = receivers.get(i);
1772
1773            if (info.activityInfo == null) {
1774                continue;
1775            }
1776
1777            final String packageName = info.activityInfo.packageName;
1778
1779            final PackageSetting ps = mSettings.mPackages.get(packageName);
1780            if (ps == null) {
1781                continue;
1782            }
1783
1784            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1785            if (!gp.grantedPermissions
1786                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1787                continue;
1788            }
1789
1790            if (requiredVerifier != null) {
1791                throw new RuntimeException("There can be only one required verifier");
1792            }
1793
1794            requiredVerifier = packageName;
1795        }
1796
1797        return requiredVerifier;
1798    }
1799
1800    @Override
1801    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1802            throws RemoteException {
1803        try {
1804            return super.onTransact(code, data, reply, flags);
1805        } catch (RuntimeException e) {
1806            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1807                Slog.wtf(TAG, "Package Manager Crash", e);
1808            }
1809            throw e;
1810        }
1811    }
1812
1813    void cleanupInstallFailedPackage(PackageSetting ps) {
1814        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1815        removeDataDirsLI(ps.name);
1816        if (ps.codePath != null) {
1817            if (!ps.codePath.delete()) {
1818                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1819            }
1820        }
1821        if (ps.resourcePath != null) {
1822            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1823                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1824            }
1825        }
1826        mSettings.removePackageLPw(ps.name);
1827    }
1828
1829    void readPermissions(File libraryDir, boolean onlyFeatures) {
1830        // Read permissions from .../etc/permission directory.
1831        if (!libraryDir.exists() || !libraryDir.isDirectory()) {
1832            Slog.w(TAG, "No directory " + libraryDir + ", skipping");
1833            return;
1834        }
1835        if (!libraryDir.canRead()) {
1836            Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
1837            return;
1838        }
1839
1840        // Iterate over the files in the directory and scan .xml files
1841        for (File f : libraryDir.listFiles()) {
1842            // We'll read platform.xml last
1843            if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1844                continue;
1845            }
1846
1847            if (!f.getPath().endsWith(".xml")) {
1848                Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
1849                continue;
1850            }
1851            if (!f.canRead()) {
1852                Slog.w(TAG, "Permissions library file " + f + " cannot be read");
1853                continue;
1854            }
1855
1856            readPermissionsFromXml(f, onlyFeatures);
1857        }
1858
1859        // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1860        final File permFile = new File(Environment.getRootDirectory(),
1861                "etc/permissions/platform.xml");
1862        readPermissionsFromXml(permFile, onlyFeatures);
1863    }
1864
1865    private void readPermissionsFromXml(File permFile, boolean onlyFeatures) {
1866        FileReader permReader = null;
1867        try {
1868            permReader = new FileReader(permFile);
1869        } catch (FileNotFoundException e) {
1870            Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
1871            return;
1872        }
1873
1874        try {
1875            XmlPullParser parser = Xml.newPullParser();
1876            parser.setInput(permReader);
1877
1878            XmlUtils.beginDocument(parser, "permissions");
1879
1880            while (true) {
1881                XmlUtils.nextElement(parser);
1882                if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1883                    break;
1884                }
1885
1886                String name = parser.getName();
1887                if ("group".equals(name) && !onlyFeatures) {
1888                    String gidStr = parser.getAttributeValue(null, "gid");
1889                    if (gidStr != null) {
1890                        int gid = Process.getGidForName(gidStr);
1891                        mGlobalGids = appendInt(mGlobalGids, gid);
1892                    } else {
1893                        Slog.w(TAG, "<group> without gid at "
1894                                + parser.getPositionDescription());
1895                    }
1896
1897                    XmlUtils.skipCurrentTag(parser);
1898                    continue;
1899                } else if ("permission".equals(name) && !onlyFeatures) {
1900                    String perm = parser.getAttributeValue(null, "name");
1901                    if (perm == null) {
1902                        Slog.w(TAG, "<permission> without name at "
1903                                + parser.getPositionDescription());
1904                        XmlUtils.skipCurrentTag(parser);
1905                        continue;
1906                    }
1907                    perm = perm.intern();
1908                    readPermission(parser, perm);
1909
1910                } else if ("assign-permission".equals(name) && !onlyFeatures) {
1911                    String perm = parser.getAttributeValue(null, "name");
1912                    if (perm == null) {
1913                        Slog.w(TAG, "<assign-permission> without name at "
1914                                + parser.getPositionDescription());
1915                        XmlUtils.skipCurrentTag(parser);
1916                        continue;
1917                    }
1918                    String uidStr = parser.getAttributeValue(null, "uid");
1919                    if (uidStr == null) {
1920                        Slog.w(TAG, "<assign-permission> without uid at "
1921                                + parser.getPositionDescription());
1922                        XmlUtils.skipCurrentTag(parser);
1923                        continue;
1924                    }
1925                    int uid = Process.getUidForName(uidStr);
1926                    if (uid < 0) {
1927                        Slog.w(TAG, "<assign-permission> with unknown uid \""
1928                                + uidStr + "\" at "
1929                                + parser.getPositionDescription());
1930                        XmlUtils.skipCurrentTag(parser);
1931                        continue;
1932                    }
1933                    perm = perm.intern();
1934                    HashSet<String> perms = mSystemPermissions.get(uid);
1935                    if (perms == null) {
1936                        perms = new HashSet<String>();
1937                        mSystemPermissions.put(uid, perms);
1938                    }
1939                    perms.add(perm);
1940                    XmlUtils.skipCurrentTag(parser);
1941
1942                } else if ("library".equals(name) && !onlyFeatures) {
1943                    String lname = parser.getAttributeValue(null, "name");
1944                    String lfile = parser.getAttributeValue(null, "file");
1945                    if (lname == null) {
1946                        Slog.w(TAG, "<library> without name at "
1947                                + parser.getPositionDescription());
1948                    } else if (lfile == null) {
1949                        Slog.w(TAG, "<library> without file at "
1950                                + parser.getPositionDescription());
1951                    } else {
1952                        //Log.i(TAG, "Got library " + lname + " in " + lfile);
1953                        mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null));
1954                    }
1955                    XmlUtils.skipCurrentTag(parser);
1956                    continue;
1957
1958                } else if ("feature".equals(name)) {
1959                    String fname = parser.getAttributeValue(null, "name");
1960                    if (fname == null) {
1961                        Slog.w(TAG, "<feature> without name at "
1962                                + parser.getPositionDescription());
1963                    } else {
1964                        //Log.i(TAG, "Got feature " + fname);
1965                        FeatureInfo fi = new FeatureInfo();
1966                        fi.name = fname;
1967                        mAvailableFeatures.put(fname, fi);
1968                    }
1969                    XmlUtils.skipCurrentTag(parser);
1970                    continue;
1971
1972                } else {
1973                    XmlUtils.skipCurrentTag(parser);
1974                    continue;
1975                }
1976
1977            }
1978            permReader.close();
1979        } catch (XmlPullParserException e) {
1980            Slog.w(TAG, "Got execption parsing permissions.", e);
1981        } catch (IOException e) {
1982            Slog.w(TAG, "Got execption parsing permissions.", e);
1983        }
1984    }
1985
1986    void readPermission(XmlPullParser parser, String name)
1987            throws IOException, XmlPullParserException {
1988
1989        name = name.intern();
1990
1991        BasePermission bp = mSettings.mPermissions.get(name);
1992        if (bp == null) {
1993            bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1994            mSettings.mPermissions.put(name, bp);
1995        }
1996        int outerDepth = parser.getDepth();
1997        int type;
1998        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1999               && (type != XmlPullParser.END_TAG
2000                       || parser.getDepth() > outerDepth)) {
2001            if (type == XmlPullParser.END_TAG
2002                    || type == XmlPullParser.TEXT) {
2003                continue;
2004            }
2005
2006            String tagName = parser.getName();
2007            if ("group".equals(tagName)) {
2008                String gidStr = parser.getAttributeValue(null, "gid");
2009                if (gidStr != null) {
2010                    int gid = Process.getGidForName(gidStr);
2011                    bp.gids = appendInt(bp.gids, gid);
2012                } else {
2013                    Slog.w(TAG, "<group> without gid at "
2014                            + parser.getPositionDescription());
2015                }
2016            }
2017            XmlUtils.skipCurrentTag(parser);
2018        }
2019    }
2020
2021    static int[] appendInts(int[] cur, int[] add) {
2022        if (add == null) return cur;
2023        if (cur == null) return add;
2024        final int N = add.length;
2025        for (int i=0; i<N; i++) {
2026            cur = appendInt(cur, add[i]);
2027        }
2028        return cur;
2029    }
2030
2031    static int[] removeInts(int[] cur, int[] rem) {
2032        if (rem == null) return cur;
2033        if (cur == null) return cur;
2034        final int N = rem.length;
2035        for (int i=0; i<N; i++) {
2036            cur = removeInt(cur, rem[i]);
2037        }
2038        return cur;
2039    }
2040
2041    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2042        if (!sUserManager.exists(userId)) return null;
2043        final PackageSetting ps = (PackageSetting) p.mExtras;
2044        if (ps == null) {
2045            return null;
2046        }
2047        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2048        final PackageUserState state = ps.readUserState(userId);
2049        return PackageParser.generatePackageInfo(p, gp.gids, flags,
2050                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
2051                state, userId);
2052    }
2053
2054    @Override
2055    public boolean isPackageAvailable(String packageName, int userId) {
2056        if (!sUserManager.exists(userId)) return false;
2057        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
2058        synchronized (mPackages) {
2059            PackageParser.Package p = mPackages.get(packageName);
2060            if (p != null) {
2061                final PackageSetting ps = (PackageSetting) p.mExtras;
2062                if (ps != null) {
2063                    final PackageUserState state = ps.readUserState(userId);
2064                    if (state != null) {
2065                        return PackageParser.isAvailable(state);
2066                    }
2067                }
2068            }
2069        }
2070        return false;
2071    }
2072
2073    @Override
2074    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2075        if (!sUserManager.exists(userId)) return null;
2076        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
2077        // reader
2078        synchronized (mPackages) {
2079            PackageParser.Package p = mPackages.get(packageName);
2080            if (DEBUG_PACKAGE_INFO)
2081                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2082            if (p != null) {
2083                return generatePackageInfo(p, flags, userId);
2084            }
2085            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2086                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2087            }
2088        }
2089        return null;
2090    }
2091
2092    @Override
2093    public String[] currentToCanonicalPackageNames(String[] names) {
2094        String[] out = new String[names.length];
2095        // reader
2096        synchronized (mPackages) {
2097            for (int i=names.length-1; i>=0; i--) {
2098                PackageSetting ps = mSettings.mPackages.get(names[i]);
2099                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2100            }
2101        }
2102        return out;
2103    }
2104
2105    @Override
2106    public String[] canonicalToCurrentPackageNames(String[] names) {
2107        String[] out = new String[names.length];
2108        // reader
2109        synchronized (mPackages) {
2110            for (int i=names.length-1; i>=0; i--) {
2111                String cur = mSettings.mRenamedPackages.get(names[i]);
2112                out[i] = cur != null ? cur : names[i];
2113            }
2114        }
2115        return out;
2116    }
2117
2118    @Override
2119    public int getPackageUid(String packageName, int userId) {
2120        if (!sUserManager.exists(userId)) return -1;
2121        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
2122        // reader
2123        synchronized (mPackages) {
2124            PackageParser.Package p = mPackages.get(packageName);
2125            if(p != null) {
2126                return UserHandle.getUid(userId, p.applicationInfo.uid);
2127            }
2128            PackageSetting ps = mSettings.mPackages.get(packageName);
2129            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2130                return -1;
2131            }
2132            p = ps.pkg;
2133            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2134        }
2135    }
2136
2137    @Override
2138    public int[] getPackageGids(String packageName) {
2139        // reader
2140        synchronized (mPackages) {
2141            PackageParser.Package p = mPackages.get(packageName);
2142            if (DEBUG_PACKAGE_INFO)
2143                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2144            if (p != null) {
2145                final PackageSetting ps = (PackageSetting)p.mExtras;
2146                return ps.getGids();
2147            }
2148        }
2149        // stupid thing to indicate an error.
2150        return new int[0];
2151    }
2152
2153    static final PermissionInfo generatePermissionInfo(
2154            BasePermission bp, int flags) {
2155        if (bp.perm != null) {
2156            return PackageParser.generatePermissionInfo(bp.perm, flags);
2157        }
2158        PermissionInfo pi = new PermissionInfo();
2159        pi.name = bp.name;
2160        pi.packageName = bp.sourcePackage;
2161        pi.nonLocalizedLabel = bp.name;
2162        pi.protectionLevel = bp.protectionLevel;
2163        return pi;
2164    }
2165
2166    @Override
2167    public PermissionInfo getPermissionInfo(String name, int flags) {
2168        // reader
2169        synchronized (mPackages) {
2170            final BasePermission p = mSettings.mPermissions.get(name);
2171            if (p != null) {
2172                return generatePermissionInfo(p, flags);
2173            }
2174            return null;
2175        }
2176    }
2177
2178    @Override
2179    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2180        // reader
2181        synchronized (mPackages) {
2182            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2183            for (BasePermission p : mSettings.mPermissions.values()) {
2184                if (group == null) {
2185                    if (p.perm == null || p.perm.info.group == null) {
2186                        out.add(generatePermissionInfo(p, flags));
2187                    }
2188                } else {
2189                    if (p.perm != null && group.equals(p.perm.info.group)) {
2190                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2191                    }
2192                }
2193            }
2194
2195            if (out.size() > 0) {
2196                return out;
2197            }
2198            return mPermissionGroups.containsKey(group) ? out : null;
2199        }
2200    }
2201
2202    @Override
2203    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2204        // reader
2205        synchronized (mPackages) {
2206            return PackageParser.generatePermissionGroupInfo(
2207                    mPermissionGroups.get(name), flags);
2208        }
2209    }
2210
2211    @Override
2212    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2213        // reader
2214        synchronized (mPackages) {
2215            final int N = mPermissionGroups.size();
2216            ArrayList<PermissionGroupInfo> out
2217                    = new ArrayList<PermissionGroupInfo>(N);
2218            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2219                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2220            }
2221            return out;
2222        }
2223    }
2224
2225    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2226            int userId) {
2227        if (!sUserManager.exists(userId)) return null;
2228        PackageSetting ps = mSettings.mPackages.get(packageName);
2229        if (ps != null) {
2230            if (ps.pkg == null) {
2231                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2232                        flags, userId);
2233                if (pInfo != null) {
2234                    return pInfo.applicationInfo;
2235                }
2236                return null;
2237            }
2238            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2239                    ps.readUserState(userId), userId);
2240        }
2241        return null;
2242    }
2243
2244    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2245            int userId) {
2246        if (!sUserManager.exists(userId)) return null;
2247        PackageSetting ps = mSettings.mPackages.get(packageName);
2248        if (ps != null) {
2249            PackageParser.Package pkg = ps.pkg;
2250            if (pkg == null) {
2251                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2252                    return null;
2253                }
2254                pkg = new PackageParser.Package(packageName);
2255                pkg.applicationInfo.packageName = packageName;
2256                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2257                pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
2258                pkg.applicationInfo.sourceDir = ps.codePathString;
2259                pkg.applicationInfo.dataDir =
2260                        getDataPathForPackage(packageName, 0).getPath();
2261                pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
2262                pkg.applicationInfo.cpuAbi = ps.cpuAbiString;
2263            }
2264            return generatePackageInfo(pkg, flags, userId);
2265        }
2266        return null;
2267    }
2268
2269    @Override
2270    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2271        if (!sUserManager.exists(userId)) return null;
2272        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2273        // writer
2274        synchronized (mPackages) {
2275            PackageParser.Package p = mPackages.get(packageName);
2276            if (DEBUG_PACKAGE_INFO) Log.v(
2277                    TAG, "getApplicationInfo " + packageName
2278                    + ": " + p);
2279            if (p != null) {
2280                PackageSetting ps = mSettings.mPackages.get(packageName);
2281                if (ps == null) return null;
2282                // Note: isEnabledLP() does not apply here - always return info
2283                return PackageParser.generateApplicationInfo(
2284                        p, flags, ps.readUserState(userId), userId);
2285            }
2286            if ("android".equals(packageName)||"system".equals(packageName)) {
2287                return mAndroidApplication;
2288            }
2289            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2290                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2291            }
2292        }
2293        return null;
2294    }
2295
2296
2297    @Override
2298    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2299        mContext.enforceCallingOrSelfPermission(
2300                android.Manifest.permission.CLEAR_APP_CACHE, null);
2301        // Queue up an async operation since clearing cache may take a little while.
2302        mHandler.post(new Runnable() {
2303            public void run() {
2304                mHandler.removeCallbacks(this);
2305                int retCode = -1;
2306                synchronized (mInstallLock) {
2307                    retCode = mInstaller.freeCache(freeStorageSize);
2308                    if (retCode < 0) {
2309                        Slog.w(TAG, "Couldn't clear application caches");
2310                    }
2311                }
2312                if (observer != null) {
2313                    try {
2314                        observer.onRemoveCompleted(null, (retCode >= 0));
2315                    } catch (RemoteException e) {
2316                        Slog.w(TAG, "RemoveException when invoking call back");
2317                    }
2318                }
2319            }
2320        });
2321    }
2322
2323    @Override
2324    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2325        mContext.enforceCallingOrSelfPermission(
2326                android.Manifest.permission.CLEAR_APP_CACHE, null);
2327        // Queue up an async operation since clearing cache may take a little while.
2328        mHandler.post(new Runnable() {
2329            public void run() {
2330                mHandler.removeCallbacks(this);
2331                int retCode = -1;
2332                synchronized (mInstallLock) {
2333                    retCode = mInstaller.freeCache(freeStorageSize);
2334                    if (retCode < 0) {
2335                        Slog.w(TAG, "Couldn't clear application caches");
2336                    }
2337                }
2338                if(pi != null) {
2339                    try {
2340                        // Callback via pending intent
2341                        int code = (retCode >= 0) ? 1 : 0;
2342                        pi.sendIntent(null, code, null,
2343                                null, null);
2344                    } catch (SendIntentException e1) {
2345                        Slog.i(TAG, "Failed to send pending intent");
2346                    }
2347                }
2348            }
2349        });
2350    }
2351
2352    @Override
2353    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2354        if (!sUserManager.exists(userId)) return null;
2355        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2356        synchronized (mPackages) {
2357            PackageParser.Activity a = mActivities.mActivities.get(component);
2358
2359            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2360            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2361                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2362                if (ps == null) return null;
2363                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2364                        userId);
2365            }
2366            if (mResolveComponentName.equals(component)) {
2367                return mResolveActivity;
2368            }
2369        }
2370        return null;
2371    }
2372
2373    @Override
2374    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2375            String resolvedType) {
2376        synchronized (mPackages) {
2377            PackageParser.Activity a = mActivities.mActivities.get(component);
2378            if (a == null) {
2379                return false;
2380            }
2381            for (int i=0; i<a.intents.size(); i++) {
2382                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2383                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2384                    return true;
2385                }
2386            }
2387            return false;
2388        }
2389    }
2390
2391    @Override
2392    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2393        if (!sUserManager.exists(userId)) return null;
2394        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2395        synchronized (mPackages) {
2396            PackageParser.Activity a = mReceivers.mActivities.get(component);
2397            if (DEBUG_PACKAGE_INFO) Log.v(
2398                TAG, "getReceiverInfo " + component + ": " + a);
2399            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2400                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2401                if (ps == null) return null;
2402                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2403                        userId);
2404            }
2405        }
2406        return null;
2407    }
2408
2409    @Override
2410    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2411        if (!sUserManager.exists(userId)) return null;
2412        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2413        synchronized (mPackages) {
2414            PackageParser.Service s = mServices.mServices.get(component);
2415            if (DEBUG_PACKAGE_INFO) Log.v(
2416                TAG, "getServiceInfo " + component + ": " + s);
2417            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2418                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2419                if (ps == null) return null;
2420                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2421                        userId);
2422            }
2423        }
2424        return null;
2425    }
2426
2427    @Override
2428    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2429        if (!sUserManager.exists(userId)) return null;
2430        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2431        synchronized (mPackages) {
2432            PackageParser.Provider p = mProviders.mProviders.get(component);
2433            if (DEBUG_PACKAGE_INFO) Log.v(
2434                TAG, "getProviderInfo " + component + ": " + p);
2435            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2436                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2437                if (ps == null) return null;
2438                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2439                        userId);
2440            }
2441        }
2442        return null;
2443    }
2444
2445    @Override
2446    public String[] getSystemSharedLibraryNames() {
2447        Set<String> libSet;
2448        synchronized (mPackages) {
2449            libSet = mSharedLibraries.keySet();
2450            int size = libSet.size();
2451            if (size > 0) {
2452                String[] libs = new String[size];
2453                libSet.toArray(libs);
2454                return libs;
2455            }
2456        }
2457        return null;
2458    }
2459
2460    @Override
2461    public FeatureInfo[] getSystemAvailableFeatures() {
2462        Collection<FeatureInfo> featSet;
2463        synchronized (mPackages) {
2464            featSet = mAvailableFeatures.values();
2465            int size = featSet.size();
2466            if (size > 0) {
2467                FeatureInfo[] features = new FeatureInfo[size+1];
2468                featSet.toArray(features);
2469                FeatureInfo fi = new FeatureInfo();
2470                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2471                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2472                features[size] = fi;
2473                return features;
2474            }
2475        }
2476        return null;
2477    }
2478
2479    @Override
2480    public boolean hasSystemFeature(String name) {
2481        synchronized (mPackages) {
2482            return mAvailableFeatures.containsKey(name);
2483        }
2484    }
2485
2486    private void checkValidCaller(int uid, int userId) {
2487        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2488            return;
2489
2490        throw new SecurityException("Caller uid=" + uid
2491                + " is not privileged to communicate with user=" + userId);
2492    }
2493
2494    @Override
2495    public int checkPermission(String permName, String pkgName) {
2496        synchronized (mPackages) {
2497            PackageParser.Package p = mPackages.get(pkgName);
2498            if (p != null && p.mExtras != null) {
2499                PackageSetting ps = (PackageSetting)p.mExtras;
2500                if (ps.sharedUser != null) {
2501                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2502                        return PackageManager.PERMISSION_GRANTED;
2503                    }
2504                } else if (ps.grantedPermissions.contains(permName)) {
2505                    return PackageManager.PERMISSION_GRANTED;
2506                }
2507            }
2508        }
2509        return PackageManager.PERMISSION_DENIED;
2510    }
2511
2512    @Override
2513    public int checkUidPermission(String permName, int uid) {
2514        synchronized (mPackages) {
2515            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2516            if (obj != null) {
2517                GrantedPermissions gp = (GrantedPermissions)obj;
2518                if (gp.grantedPermissions.contains(permName)) {
2519                    return PackageManager.PERMISSION_GRANTED;
2520                }
2521            } else {
2522                HashSet<String> perms = mSystemPermissions.get(uid);
2523                if (perms != null && perms.contains(permName)) {
2524                    return PackageManager.PERMISSION_GRANTED;
2525                }
2526            }
2527        }
2528        return PackageManager.PERMISSION_DENIED;
2529    }
2530
2531    /**
2532     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2533     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2534     * @param message the message to log on security exception
2535     * @return
2536     */
2537    private void enforceCrossUserPermission(int callingUid, int userId,
2538            boolean requireFullPermission, String message) {
2539        if (userId < 0) {
2540            throw new IllegalArgumentException("Invalid userId " + userId);
2541        }
2542        if (userId == UserHandle.getUserId(callingUid)) return;
2543        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2544            if (requireFullPermission) {
2545                mContext.enforceCallingOrSelfPermission(
2546                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2547            } else {
2548                try {
2549                    mContext.enforceCallingOrSelfPermission(
2550                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2551                } catch (SecurityException se) {
2552                    mContext.enforceCallingOrSelfPermission(
2553                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2554                }
2555            }
2556        }
2557    }
2558
2559    private BasePermission findPermissionTreeLP(String permName) {
2560        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2561            if (permName.startsWith(bp.name) &&
2562                    permName.length() > bp.name.length() &&
2563                    permName.charAt(bp.name.length()) == '.') {
2564                return bp;
2565            }
2566        }
2567        return null;
2568    }
2569
2570    private BasePermission checkPermissionTreeLP(String permName) {
2571        if (permName != null) {
2572            BasePermission bp = findPermissionTreeLP(permName);
2573            if (bp != null) {
2574                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2575                    return bp;
2576                }
2577                throw new SecurityException("Calling uid "
2578                        + Binder.getCallingUid()
2579                        + " is not allowed to add to permission tree "
2580                        + bp.name + " owned by uid " + bp.uid);
2581            }
2582        }
2583        throw new SecurityException("No permission tree found for " + permName);
2584    }
2585
2586    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2587        if (s1 == null) {
2588            return s2 == null;
2589        }
2590        if (s2 == null) {
2591            return false;
2592        }
2593        if (s1.getClass() != s2.getClass()) {
2594            return false;
2595        }
2596        return s1.equals(s2);
2597    }
2598
2599    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2600        if (pi1.icon != pi2.icon) return false;
2601        if (pi1.logo != pi2.logo) return false;
2602        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2603        if (!compareStrings(pi1.name, pi2.name)) return false;
2604        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2605        // We'll take care of setting this one.
2606        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2607        // These are not currently stored in settings.
2608        //if (!compareStrings(pi1.group, pi2.group)) return false;
2609        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2610        //if (pi1.labelRes != pi2.labelRes) return false;
2611        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2612        return true;
2613    }
2614
2615    int permissionInfoFootprint(PermissionInfo info) {
2616        int size = info.name.length();
2617        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2618        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2619        return size;
2620    }
2621
2622    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2623        int size = 0;
2624        for (BasePermission perm : mSettings.mPermissions.values()) {
2625            if (perm.uid == tree.uid) {
2626                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2627            }
2628        }
2629        return size;
2630    }
2631
2632    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2633        // We calculate the max size of permissions defined by this uid and throw
2634        // if that plus the size of 'info' would exceed our stated maximum.
2635        if (tree.uid != Process.SYSTEM_UID) {
2636            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2637            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2638                throw new SecurityException("Permission tree size cap exceeded");
2639            }
2640        }
2641    }
2642
2643    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2644        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2645            throw new SecurityException("Label must be specified in permission");
2646        }
2647        BasePermission tree = checkPermissionTreeLP(info.name);
2648        BasePermission bp = mSettings.mPermissions.get(info.name);
2649        boolean added = bp == null;
2650        boolean changed = true;
2651        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2652        if (added) {
2653            enforcePermissionCapLocked(info, tree);
2654            bp = new BasePermission(info.name, tree.sourcePackage,
2655                    BasePermission.TYPE_DYNAMIC);
2656        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2657            throw new SecurityException(
2658                    "Not allowed to modify non-dynamic permission "
2659                    + info.name);
2660        } else {
2661            if (bp.protectionLevel == fixedLevel
2662                    && bp.perm.owner.equals(tree.perm.owner)
2663                    && bp.uid == tree.uid
2664                    && comparePermissionInfos(bp.perm.info, info)) {
2665                changed = false;
2666            }
2667        }
2668        bp.protectionLevel = fixedLevel;
2669        info = new PermissionInfo(info);
2670        info.protectionLevel = fixedLevel;
2671        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2672        bp.perm.info.packageName = tree.perm.info.packageName;
2673        bp.uid = tree.uid;
2674        if (added) {
2675            mSettings.mPermissions.put(info.name, bp);
2676        }
2677        if (changed) {
2678            if (!async) {
2679                mSettings.writeLPr();
2680            } else {
2681                scheduleWriteSettingsLocked();
2682            }
2683        }
2684        return added;
2685    }
2686
2687    @Override
2688    public boolean addPermission(PermissionInfo info) {
2689        synchronized (mPackages) {
2690            return addPermissionLocked(info, false);
2691        }
2692    }
2693
2694    @Override
2695    public boolean addPermissionAsync(PermissionInfo info) {
2696        synchronized (mPackages) {
2697            return addPermissionLocked(info, true);
2698        }
2699    }
2700
2701    @Override
2702    public void removePermission(String name) {
2703        synchronized (mPackages) {
2704            checkPermissionTreeLP(name);
2705            BasePermission bp = mSettings.mPermissions.get(name);
2706            if (bp != null) {
2707                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2708                    throw new SecurityException(
2709                            "Not allowed to modify non-dynamic permission "
2710                            + name);
2711                }
2712                mSettings.mPermissions.remove(name);
2713                mSettings.writeLPr();
2714            }
2715        }
2716    }
2717
2718    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2719        int index = pkg.requestedPermissions.indexOf(bp.name);
2720        if (index == -1) {
2721            throw new SecurityException("Package " + pkg.packageName
2722                    + " has not requested permission " + bp.name);
2723        }
2724        boolean isNormal =
2725                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2726                        == PermissionInfo.PROTECTION_NORMAL);
2727        boolean isDangerous =
2728                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2729                        == PermissionInfo.PROTECTION_DANGEROUS);
2730        boolean isDevelopment =
2731                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2732
2733        if (!isNormal && !isDangerous && !isDevelopment) {
2734            throw new SecurityException("Permission " + bp.name
2735                    + " is not a changeable permission type");
2736        }
2737
2738        if (isNormal || isDangerous) {
2739            if (pkg.requestedPermissionsRequired.get(index)) {
2740                throw new SecurityException("Can't change " + bp.name
2741                        + ". It is required by the application");
2742            }
2743        }
2744    }
2745
2746    @Override
2747    public void grantPermission(String packageName, String permissionName) {
2748        mContext.enforceCallingOrSelfPermission(
2749                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2750        synchronized (mPackages) {
2751            final PackageParser.Package pkg = mPackages.get(packageName);
2752            if (pkg == null) {
2753                throw new IllegalArgumentException("Unknown package: " + packageName);
2754            }
2755            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2756            if (bp == null) {
2757                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2758            }
2759
2760            checkGrantRevokePermissions(pkg, bp);
2761
2762            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2763            if (ps == null) {
2764                return;
2765            }
2766            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2767            if (gp.grantedPermissions.add(permissionName)) {
2768                if (ps.haveGids) {
2769                    gp.gids = appendInts(gp.gids, bp.gids);
2770                }
2771                mSettings.writeLPr();
2772            }
2773        }
2774    }
2775
2776    @Override
2777    public void revokePermission(String packageName, String permissionName) {
2778        int changedAppId = -1;
2779
2780        synchronized (mPackages) {
2781            final PackageParser.Package pkg = mPackages.get(packageName);
2782            if (pkg == null) {
2783                throw new IllegalArgumentException("Unknown package: " + packageName);
2784            }
2785            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2786                mContext.enforceCallingOrSelfPermission(
2787                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2788            }
2789            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2790            if (bp == null) {
2791                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2792            }
2793
2794            checkGrantRevokePermissions(pkg, bp);
2795
2796            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2797            if (ps == null) {
2798                return;
2799            }
2800            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2801            if (gp.grantedPermissions.remove(permissionName)) {
2802                gp.grantedPermissions.remove(permissionName);
2803                if (ps.haveGids) {
2804                    gp.gids = removeInts(gp.gids, bp.gids);
2805                }
2806                mSettings.writeLPr();
2807                changedAppId = ps.appId;
2808            }
2809        }
2810
2811        if (changedAppId >= 0) {
2812            // We changed the perm on someone, kill its processes.
2813            IActivityManager am = ActivityManagerNative.getDefault();
2814            if (am != null) {
2815                final int callingUserId = UserHandle.getCallingUserId();
2816                final long ident = Binder.clearCallingIdentity();
2817                try {
2818                    //XXX we should only revoke for the calling user's app permissions,
2819                    // but for now we impact all users.
2820                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2821                    //        "revoke " + permissionName);
2822                    int[] users = sUserManager.getUserIds();
2823                    for (int user : users) {
2824                        am.killUid(UserHandle.getUid(user, changedAppId),
2825                                "revoke " + permissionName);
2826                    }
2827                } catch (RemoteException e) {
2828                } finally {
2829                    Binder.restoreCallingIdentity(ident);
2830                }
2831            }
2832        }
2833    }
2834
2835    @Override
2836    public boolean isProtectedBroadcast(String actionName) {
2837        synchronized (mPackages) {
2838            return mProtectedBroadcasts.contains(actionName);
2839        }
2840    }
2841
2842    @Override
2843    public int checkSignatures(String pkg1, String pkg2) {
2844        synchronized (mPackages) {
2845            final PackageParser.Package p1 = mPackages.get(pkg1);
2846            final PackageParser.Package p2 = mPackages.get(pkg2);
2847            if (p1 == null || p1.mExtras == null
2848                    || p2 == null || p2.mExtras == null) {
2849                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2850            }
2851            return compareSignatures(p1.mSignatures, p2.mSignatures);
2852        }
2853    }
2854
2855    @Override
2856    public int checkUidSignatures(int uid1, int uid2) {
2857        // Map to base uids.
2858        uid1 = UserHandle.getAppId(uid1);
2859        uid2 = UserHandle.getAppId(uid2);
2860        // reader
2861        synchronized (mPackages) {
2862            Signature[] s1;
2863            Signature[] s2;
2864            Object obj = mSettings.getUserIdLPr(uid1);
2865            if (obj != null) {
2866                if (obj instanceof SharedUserSetting) {
2867                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2868                } else if (obj instanceof PackageSetting) {
2869                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2870                } else {
2871                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2872                }
2873            } else {
2874                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2875            }
2876            obj = mSettings.getUserIdLPr(uid2);
2877            if (obj != null) {
2878                if (obj instanceof SharedUserSetting) {
2879                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2880                } else if (obj instanceof PackageSetting) {
2881                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2882                } else {
2883                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2884                }
2885            } else {
2886                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2887            }
2888            return compareSignatures(s1, s2);
2889        }
2890    }
2891
2892    /**
2893     * Compares two sets of signatures. Returns:
2894     * <br />
2895     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2896     * <br />
2897     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2898     * <br />
2899     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2900     * <br />
2901     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2902     * <br />
2903     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2904     */
2905    static int compareSignatures(Signature[] s1, Signature[] s2) {
2906        if (s1 == null) {
2907            return s2 == null
2908                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2909                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2910        }
2911
2912        if (s2 == null) {
2913            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2914        }
2915
2916        if (s1.length != s2.length) {
2917            return PackageManager.SIGNATURE_NO_MATCH;
2918        }
2919
2920        // Since both signature sets are of size 1, we can compare without HashSets.
2921        if (s1.length == 1) {
2922            return s1[0].equals(s2[0]) ?
2923                    PackageManager.SIGNATURE_MATCH :
2924                    PackageManager.SIGNATURE_NO_MATCH;
2925        }
2926
2927        HashSet<Signature> set1 = new HashSet<Signature>();
2928        for (Signature sig : s1) {
2929            set1.add(sig);
2930        }
2931        HashSet<Signature> set2 = new HashSet<Signature>();
2932        for (Signature sig : s2) {
2933            set2.add(sig);
2934        }
2935        // Make sure s2 contains all signatures in s1.
2936        if (set1.equals(set2)) {
2937            return PackageManager.SIGNATURE_MATCH;
2938        }
2939        return PackageManager.SIGNATURE_NO_MATCH;
2940    }
2941
2942    /**
2943     * If the database version for this type of package (internal storage or
2944     * external storage) is less than the version where package signatures
2945     * were updated, return true.
2946     */
2947    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2948        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2949                DatabaseVersion.SIGNATURE_END_ENTITY))
2950                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2951                        DatabaseVersion.SIGNATURE_END_ENTITY));
2952    }
2953
2954    /**
2955     * Used for backward compatibility to make sure any packages with
2956     * certificate chains get upgraded to the new style. {@code existingSigs}
2957     * will be in the old format (since they were stored on disk from before the
2958     * system upgrade) and {@code scannedSigs} will be in the newer format.
2959     */
2960    private int compareSignaturesCompat(PackageSignatures existingSigs,
2961            PackageParser.Package scannedPkg) {
2962        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2963            return PackageManager.SIGNATURE_NO_MATCH;
2964        }
2965
2966        HashSet<Signature> existingSet = new HashSet<Signature>();
2967        for (Signature sig : existingSigs.mSignatures) {
2968            existingSet.add(sig);
2969        }
2970        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2971        for (Signature sig : scannedPkg.mSignatures) {
2972            try {
2973                Signature[] chainSignatures = sig.getChainSignatures();
2974                for (Signature chainSig : chainSignatures) {
2975                    scannedCompatSet.add(chainSig);
2976                }
2977            } catch (CertificateEncodingException e) {
2978                scannedCompatSet.add(sig);
2979            }
2980        }
2981        /*
2982         * Make sure the expanded scanned set contains all signatures in the
2983         * existing one.
2984         */
2985        if (scannedCompatSet.equals(existingSet)) {
2986            // Migrate the old signatures to the new scheme.
2987            existingSigs.assignSignatures(scannedPkg.mSignatures);
2988            // The new KeySets will be re-added later in the scanning process.
2989            mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName);
2990            return PackageManager.SIGNATURE_MATCH;
2991        }
2992        return PackageManager.SIGNATURE_NO_MATCH;
2993    }
2994
2995    @Override
2996    public String[] getPackagesForUid(int uid) {
2997        uid = UserHandle.getAppId(uid);
2998        // reader
2999        synchronized (mPackages) {
3000            Object obj = mSettings.getUserIdLPr(uid);
3001            if (obj instanceof SharedUserSetting) {
3002                final SharedUserSetting sus = (SharedUserSetting) obj;
3003                final int N = sus.packages.size();
3004                final String[] res = new String[N];
3005                final Iterator<PackageSetting> it = sus.packages.iterator();
3006                int i = 0;
3007                while (it.hasNext()) {
3008                    res[i++] = it.next().name;
3009                }
3010                return res;
3011            } else if (obj instanceof PackageSetting) {
3012                final PackageSetting ps = (PackageSetting) obj;
3013                return new String[] { ps.name };
3014            }
3015        }
3016        return null;
3017    }
3018
3019    @Override
3020    public String getNameForUid(int uid) {
3021        // reader
3022        synchronized (mPackages) {
3023            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3024            if (obj instanceof SharedUserSetting) {
3025                final SharedUserSetting sus = (SharedUserSetting) obj;
3026                return sus.name + ":" + sus.userId;
3027            } else if (obj instanceof PackageSetting) {
3028                final PackageSetting ps = (PackageSetting) obj;
3029                return ps.name;
3030            }
3031        }
3032        return null;
3033    }
3034
3035    @Override
3036    public int getUidForSharedUser(String sharedUserName) {
3037        if(sharedUserName == null) {
3038            return -1;
3039        }
3040        // reader
3041        synchronized (mPackages) {
3042            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
3043            if (suid == null) {
3044                return -1;
3045            }
3046            return suid.userId;
3047        }
3048    }
3049
3050    @Override
3051    public int getFlagsForUid(int uid) {
3052        synchronized (mPackages) {
3053            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3054            if (obj instanceof SharedUserSetting) {
3055                final SharedUserSetting sus = (SharedUserSetting) obj;
3056                return sus.pkgFlags;
3057            } else if (obj instanceof PackageSetting) {
3058                final PackageSetting ps = (PackageSetting) obj;
3059                return ps.pkgFlags;
3060            }
3061        }
3062        return 0;
3063    }
3064
3065    @Override
3066    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3067            int flags, int userId) {
3068        if (!sUserManager.exists(userId)) return null;
3069        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
3070        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3071        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3072    }
3073
3074    @Override
3075    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3076            IntentFilter filter, int match, ComponentName activity) {
3077        final int userId = UserHandle.getCallingUserId();
3078        if (DEBUG_PREFERRED) {
3079            Log.v(TAG, "setLastChosenActivity intent=" + intent
3080                + " resolvedType=" + resolvedType
3081                + " flags=" + flags
3082                + " filter=" + filter
3083                + " match=" + match
3084                + " activity=" + activity);
3085            filter.dump(new PrintStreamPrinter(System.out), "    ");
3086        }
3087        intent.setComponent(null);
3088        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3089        // Find any earlier preferred or last chosen entries and nuke them
3090        findPreferredActivity(intent, resolvedType,
3091                flags, query, 0, false, true, false, userId);
3092        // Add the new activity as the last chosen for this filter
3093        addPreferredActivityInternal(filter, match, null, activity, false, userId);
3094    }
3095
3096    @Override
3097    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3098        final int userId = UserHandle.getCallingUserId();
3099        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3100        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3101        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3102                false, false, false, userId);
3103    }
3104
3105    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3106            int flags, List<ResolveInfo> query, int userId) {
3107        if (query != null) {
3108            final int N = query.size();
3109            if (N == 1) {
3110                return query.get(0);
3111            } else if (N > 1) {
3112                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3113                // If there is more than one activity with the same priority,
3114                // then let the user decide between them.
3115                ResolveInfo r0 = query.get(0);
3116                ResolveInfo r1 = query.get(1);
3117                if (DEBUG_INTENT_MATCHING || debug) {
3118                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3119                            + r1.activityInfo.name + "=" + r1.priority);
3120                }
3121                // If the first activity has a higher priority, or a different
3122                // default, then it is always desireable to pick it.
3123                if (r0.priority != r1.priority
3124                        || r0.preferredOrder != r1.preferredOrder
3125                        || r0.isDefault != r1.isDefault) {
3126                    return query.get(0);
3127                }
3128                // If we have saved a preference for a preferred activity for
3129                // this Intent, use that.
3130                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3131                        flags, query, r0.priority, true, false, debug, userId);
3132                if (ri != null) {
3133                    return ri;
3134                }
3135                if (userId != 0) {
3136                    ri = new ResolveInfo(mResolveInfo);
3137                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3138                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3139                            ri.activityInfo.applicationInfo);
3140                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3141                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3142                    return ri;
3143                }
3144                return mResolveInfo;
3145            }
3146        }
3147        return null;
3148    }
3149
3150    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3151            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3152        final int N = query.size();
3153        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3154                .get(userId);
3155        // Get the list of persistent preferred activities that handle the intent
3156        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3157        List<PersistentPreferredActivity> pprefs = ppir != null
3158                ? ppir.queryIntent(intent, resolvedType,
3159                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3160                : null;
3161        if (pprefs != null && pprefs.size() > 0) {
3162            final int M = pprefs.size();
3163            for (int i=0; i<M; i++) {
3164                final PersistentPreferredActivity ppa = pprefs.get(i);
3165                if (DEBUG_PREFERRED || debug) {
3166                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3167                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3168                            + "\n  component=" + ppa.mComponent);
3169                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3170                }
3171                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3172                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3173                if (DEBUG_PREFERRED || debug) {
3174                    Slog.v(TAG, "Found persistent preferred activity:");
3175                    if (ai != null) {
3176                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3177                    } else {
3178                        Slog.v(TAG, "  null");
3179                    }
3180                }
3181                if (ai == null) {
3182                    // This previously registered persistent preferred activity
3183                    // component is no longer known. Ignore it and do NOT remove it.
3184                    continue;
3185                }
3186                for (int j=0; j<N; j++) {
3187                    final ResolveInfo ri = query.get(j);
3188                    if (!ri.activityInfo.applicationInfo.packageName
3189                            .equals(ai.applicationInfo.packageName)) {
3190                        continue;
3191                    }
3192                    if (!ri.activityInfo.name.equals(ai.name)) {
3193                        continue;
3194                    }
3195                    //  Found a persistent preference that can handle the intent.
3196                    if (DEBUG_PREFERRED || debug) {
3197                        Slog.v(TAG, "Returning persistent preferred activity: " +
3198                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3199                    }
3200                    return ri;
3201                }
3202            }
3203        }
3204        return null;
3205    }
3206
3207    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3208            List<ResolveInfo> query, int priority, boolean always,
3209            boolean removeMatches, boolean debug, int userId) {
3210        if (!sUserManager.exists(userId)) return null;
3211        // writer
3212        synchronized (mPackages) {
3213            if (intent.getSelector() != null) {
3214                intent = intent.getSelector();
3215            }
3216            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3217
3218            // Try to find a matching persistent preferred activity.
3219            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3220                    debug, userId);
3221
3222            // If a persistent preferred activity matched, use it.
3223            if (pri != null) {
3224                return pri;
3225            }
3226
3227            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3228            // Get the list of preferred activities that handle the intent
3229            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3230            List<PreferredActivity> prefs = pir != null
3231                    ? pir.queryIntent(intent, resolvedType,
3232                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3233                    : null;
3234            if (prefs != null && prefs.size() > 0) {
3235                // First figure out how good the original match set is.
3236                // We will only allow preferred activities that came
3237                // from the same match quality.
3238                int match = 0;
3239
3240                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3241
3242                final int N = query.size();
3243                for (int j=0; j<N; j++) {
3244                    final ResolveInfo ri = query.get(j);
3245                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3246                            + ": 0x" + Integer.toHexString(match));
3247                    if (ri.match > match) {
3248                        match = ri.match;
3249                    }
3250                }
3251
3252                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3253                        + Integer.toHexString(match));
3254
3255                match &= IntentFilter.MATCH_CATEGORY_MASK;
3256                final int M = prefs.size();
3257                for (int i=0; i<M; i++) {
3258                    final PreferredActivity pa = prefs.get(i);
3259                    if (DEBUG_PREFERRED || debug) {
3260                        Slog.v(TAG, "Checking PreferredActivity ds="
3261                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3262                                + "\n  component=" + pa.mPref.mComponent);
3263                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3264                    }
3265                    if (pa.mPref.mMatch != match) {
3266                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3267                                + Integer.toHexString(pa.mPref.mMatch));
3268                        continue;
3269                    }
3270                    // If it's not an "always" type preferred activity and that's what we're
3271                    // looking for, skip it.
3272                    if (always && !pa.mPref.mAlways) {
3273                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3274                        continue;
3275                    }
3276                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3277                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3278                    if (DEBUG_PREFERRED || debug) {
3279                        Slog.v(TAG, "Found preferred activity:");
3280                        if (ai != null) {
3281                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3282                        } else {
3283                            Slog.v(TAG, "  null");
3284                        }
3285                    }
3286                    if (ai == null) {
3287                        // This previously registered preferred activity
3288                        // component is no longer known.  Most likely an update
3289                        // to the app was installed and in the new version this
3290                        // component no longer exists.  Clean it up by removing
3291                        // it from the preferred activities list, and skip it.
3292                        Slog.w(TAG, "Removing dangling preferred activity: "
3293                                + pa.mPref.mComponent);
3294                        pir.removeFilter(pa);
3295                        continue;
3296                    }
3297                    for (int j=0; j<N; j++) {
3298                        final ResolveInfo ri = query.get(j);
3299                        if (!ri.activityInfo.applicationInfo.packageName
3300                                .equals(ai.applicationInfo.packageName)) {
3301                            continue;
3302                        }
3303                        if (!ri.activityInfo.name.equals(ai.name)) {
3304                            continue;
3305                        }
3306
3307                        if (removeMatches) {
3308                            pir.removeFilter(pa);
3309                            if (DEBUG_PREFERRED) {
3310                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3311                            }
3312                            break;
3313                        }
3314
3315                        // Okay we found a previously set preferred or last chosen app.
3316                        // If the result set is different from when this
3317                        // was created, we need to clear it and re-ask the
3318                        // user their preference, if we're looking for an "always" type entry.
3319                        if (always && !pa.mPref.sameSet(query, priority)) {
3320                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3321                                    + intent + " type " + resolvedType);
3322                            if (DEBUG_PREFERRED) {
3323                                Slog.v(TAG, "Removing preferred activity since set changed "
3324                                        + pa.mPref.mComponent);
3325                            }
3326                            pir.removeFilter(pa);
3327                            // Re-add the filter as a "last chosen" entry (!always)
3328                            PreferredActivity lastChosen = new PreferredActivity(
3329                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3330                            pir.addFilter(lastChosen);
3331                            mSettings.writePackageRestrictionsLPr(userId);
3332                            return null;
3333                        }
3334
3335                        // Yay! Either the set matched or we're looking for the last chosen
3336                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3337                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3338                        mSettings.writePackageRestrictionsLPr(userId);
3339                        return ri;
3340                    }
3341                }
3342            }
3343            mSettings.writePackageRestrictionsLPr(userId);
3344        }
3345        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3346        return null;
3347    }
3348
3349    /*
3350     * Returns if intent can be forwarded from the userId from to dest
3351     */
3352    @Override
3353    public boolean canForwardTo(Intent intent, String resolvedType, int userIdFrom, int userIdDest) {
3354        mContext.enforceCallingOrSelfPermission(
3355                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3356        List<ForwardingIntentFilter> matches =
3357                getMatchingForwardingIntentFilters(intent, resolvedType, userIdFrom);
3358        if (matches != null) {
3359            int size = matches.size();
3360            for (int i = 0; i < size; i++) {
3361                if (matches.get(i).getUserIdDest() == userIdDest) return true;
3362            }
3363        }
3364        return false;
3365    }
3366
3367    private List<ForwardingIntentFilter> getMatchingForwardingIntentFilters(Intent intent,
3368            String resolvedType, int userId) {
3369        ForwardingIntentResolver fir = mSettings.mForwardingIntentResolvers.get(userId);
3370        if (fir != null) {
3371            return fir.queryIntent(intent, resolvedType, false, userId);
3372        }
3373        return null;
3374    }
3375
3376    @Override
3377    public List<ResolveInfo> queryIntentActivities(Intent intent,
3378            String resolvedType, int flags, int userId) {
3379        if (!sUserManager.exists(userId)) return Collections.emptyList();
3380        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3381        ComponentName comp = intent.getComponent();
3382        if (comp == null) {
3383            if (intent.getSelector() != null) {
3384                intent = intent.getSelector();
3385                comp = intent.getComponent();
3386            }
3387        }
3388
3389        if (comp != null) {
3390            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3391            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3392            if (ai != null) {
3393                final ResolveInfo ri = new ResolveInfo();
3394                ri.activityInfo = ai;
3395                list.add(ri);
3396            }
3397            return list;
3398        }
3399
3400        // reader
3401        synchronized (mPackages) {
3402            final String pkgName = intent.getPackage();
3403            if (pkgName == null) {
3404                List<ResolveInfo> result =
3405                        mActivities.queryIntent(intent, resolvedType, flags, userId);
3406                // Checking if we can forward the intent to another user
3407                List<ForwardingIntentFilter> fifs =
3408                        getMatchingForwardingIntentFilters(intent, resolvedType, userId);
3409                if (fifs != null) {
3410                    ForwardingIntentFilter forwardingIntentFilterWithResult = null;
3411                    HashSet<Integer> alreadyTriedUserIds = new HashSet<Integer>();
3412                    for (ForwardingIntentFilter fif : fifs) {
3413                        int userIdDest = fif.getUserIdDest();
3414                        // Two {@link ForwardingIntentFilter}s can have the same userIdDest and
3415                        // match the same an intent. For performance reasons, it is better not to
3416                        // run queryIntent twice for the same userId
3417                        if (!alreadyTriedUserIds.contains(userIdDest)) {
3418                            List<ResolveInfo> resultUser = mActivities.queryIntent(intent,
3419                                    resolvedType, flags, userIdDest);
3420                            if (resultUser != null) {
3421                                forwardingIntentFilterWithResult = fif;
3422                                // As soon as there is a match in another user, we add the
3423                                // intentForwarderActivity to the list of ResolveInfo.
3424                                break;
3425                            }
3426                            alreadyTriedUserIds.add(userIdDest);
3427                        }
3428                    }
3429                    if (forwardingIntentFilterWithResult != null) {
3430                        ResolveInfo forwardingResolveInfo = createForwardingResolveInfo(
3431                                forwardingIntentFilterWithResult, userId);
3432                        result.add(forwardingResolveInfo);
3433                    }
3434                }
3435                return result;
3436            }
3437            final PackageParser.Package pkg = mPackages.get(pkgName);
3438            if (pkg != null) {
3439                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3440                        pkg.activities, userId);
3441            }
3442            return new ArrayList<ResolveInfo>();
3443        }
3444    }
3445
3446    private ResolveInfo createForwardingResolveInfo(ForwardingIntentFilter fif, int userIdFrom) {
3447        String className;
3448        int userIdDest = fif.getUserIdDest();
3449        if (userIdDest == UserHandle.USER_OWNER) {
3450            className = FORWARD_INTENT_TO_USER_OWNER;
3451        } else {
3452            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3453        }
3454        ComponentName forwardingActivityComponentName = new ComponentName(
3455                mAndroidApplication.packageName, className);
3456        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3457                userIdFrom);
3458        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3459        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3460        forwardingResolveInfo.priority = 0;
3461        forwardingResolveInfo.preferredOrder = 0;
3462        forwardingResolveInfo.match = 0;
3463        forwardingResolveInfo.isDefault = true;
3464        forwardingResolveInfo.filter = fif;
3465        return forwardingResolveInfo;
3466    }
3467
3468    @Override
3469    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3470            Intent[] specifics, String[] specificTypes, Intent intent,
3471            String resolvedType, int flags, int userId) {
3472        if (!sUserManager.exists(userId)) return Collections.emptyList();
3473        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3474                "query intent activity options");
3475        final String resultsAction = intent.getAction();
3476
3477        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3478                | PackageManager.GET_RESOLVED_FILTER, userId);
3479
3480        if (DEBUG_INTENT_MATCHING) {
3481            Log.v(TAG, "Query " + intent + ": " + results);
3482        }
3483
3484        int specificsPos = 0;
3485        int N;
3486
3487        // todo: note that the algorithm used here is O(N^2).  This
3488        // isn't a problem in our current environment, but if we start running
3489        // into situations where we have more than 5 or 10 matches then this
3490        // should probably be changed to something smarter...
3491
3492        // First we go through and resolve each of the specific items
3493        // that were supplied, taking care of removing any corresponding
3494        // duplicate items in the generic resolve list.
3495        if (specifics != null) {
3496            for (int i=0; i<specifics.length; i++) {
3497                final Intent sintent = specifics[i];
3498                if (sintent == null) {
3499                    continue;
3500                }
3501
3502                if (DEBUG_INTENT_MATCHING) {
3503                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3504                }
3505
3506                String action = sintent.getAction();
3507                if (resultsAction != null && resultsAction.equals(action)) {
3508                    // If this action was explicitly requested, then don't
3509                    // remove things that have it.
3510                    action = null;
3511                }
3512
3513                ResolveInfo ri = null;
3514                ActivityInfo ai = null;
3515
3516                ComponentName comp = sintent.getComponent();
3517                if (comp == null) {
3518                    ri = resolveIntent(
3519                        sintent,
3520                        specificTypes != null ? specificTypes[i] : null,
3521                            flags, userId);
3522                    if (ri == null) {
3523                        continue;
3524                    }
3525                    if (ri == mResolveInfo) {
3526                        // ACK!  Must do something better with this.
3527                    }
3528                    ai = ri.activityInfo;
3529                    comp = new ComponentName(ai.applicationInfo.packageName,
3530                            ai.name);
3531                } else {
3532                    ai = getActivityInfo(comp, flags, userId);
3533                    if (ai == null) {
3534                        continue;
3535                    }
3536                }
3537
3538                // Look for any generic query activities that are duplicates
3539                // of this specific one, and remove them from the results.
3540                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3541                N = results.size();
3542                int j;
3543                for (j=specificsPos; j<N; j++) {
3544                    ResolveInfo sri = results.get(j);
3545                    if ((sri.activityInfo.name.equals(comp.getClassName())
3546                            && sri.activityInfo.applicationInfo.packageName.equals(
3547                                    comp.getPackageName()))
3548                        || (action != null && sri.filter.matchAction(action))) {
3549                        results.remove(j);
3550                        if (DEBUG_INTENT_MATCHING) Log.v(
3551                            TAG, "Removing duplicate item from " + j
3552                            + " due to specific " + specificsPos);
3553                        if (ri == null) {
3554                            ri = sri;
3555                        }
3556                        j--;
3557                        N--;
3558                    }
3559                }
3560
3561                // Add this specific item to its proper place.
3562                if (ri == null) {
3563                    ri = new ResolveInfo();
3564                    ri.activityInfo = ai;
3565                }
3566                results.add(specificsPos, ri);
3567                ri.specificIndex = i;
3568                specificsPos++;
3569            }
3570        }
3571
3572        // Now we go through the remaining generic results and remove any
3573        // duplicate actions that are found here.
3574        N = results.size();
3575        for (int i=specificsPos; i<N-1; i++) {
3576            final ResolveInfo rii = results.get(i);
3577            if (rii.filter == null) {
3578                continue;
3579            }
3580
3581            // Iterate over all of the actions of this result's intent
3582            // filter...  typically this should be just one.
3583            final Iterator<String> it = rii.filter.actionsIterator();
3584            if (it == null) {
3585                continue;
3586            }
3587            while (it.hasNext()) {
3588                final String action = it.next();
3589                if (resultsAction != null && resultsAction.equals(action)) {
3590                    // If this action was explicitly requested, then don't
3591                    // remove things that have it.
3592                    continue;
3593                }
3594                for (int j=i+1; j<N; j++) {
3595                    final ResolveInfo rij = results.get(j);
3596                    if (rij.filter != null && rij.filter.hasAction(action)) {
3597                        results.remove(j);
3598                        if (DEBUG_INTENT_MATCHING) Log.v(
3599                            TAG, "Removing duplicate item from " + j
3600                            + " due to action " + action + " at " + i);
3601                        j--;
3602                        N--;
3603                    }
3604                }
3605            }
3606
3607            // If the caller didn't request filter information, drop it now
3608            // so we don't have to marshall/unmarshall it.
3609            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3610                rii.filter = null;
3611            }
3612        }
3613
3614        // Filter out the caller activity if so requested.
3615        if (caller != null) {
3616            N = results.size();
3617            for (int i=0; i<N; i++) {
3618                ActivityInfo ainfo = results.get(i).activityInfo;
3619                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3620                        && caller.getClassName().equals(ainfo.name)) {
3621                    results.remove(i);
3622                    break;
3623                }
3624            }
3625        }
3626
3627        // If the caller didn't request filter information,
3628        // drop them now so we don't have to
3629        // marshall/unmarshall it.
3630        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3631            N = results.size();
3632            for (int i=0; i<N; i++) {
3633                results.get(i).filter = null;
3634            }
3635        }
3636
3637        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3638        return results;
3639    }
3640
3641    @Override
3642    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3643            int userId) {
3644        if (!sUserManager.exists(userId)) return Collections.emptyList();
3645        ComponentName comp = intent.getComponent();
3646        if (comp == null) {
3647            if (intent.getSelector() != null) {
3648                intent = intent.getSelector();
3649                comp = intent.getComponent();
3650            }
3651        }
3652        if (comp != null) {
3653            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3654            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3655            if (ai != null) {
3656                ResolveInfo ri = new ResolveInfo();
3657                ri.activityInfo = ai;
3658                list.add(ri);
3659            }
3660            return list;
3661        }
3662
3663        // reader
3664        synchronized (mPackages) {
3665            String pkgName = intent.getPackage();
3666            if (pkgName == null) {
3667                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3668            }
3669            final PackageParser.Package pkg = mPackages.get(pkgName);
3670            if (pkg != null) {
3671                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3672                        userId);
3673            }
3674            return null;
3675        }
3676    }
3677
3678    @Override
3679    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3680        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3681        if (!sUserManager.exists(userId)) return null;
3682        if (query != null) {
3683            if (query.size() >= 1) {
3684                // If there is more than one service with the same priority,
3685                // just arbitrarily pick the first one.
3686                return query.get(0);
3687            }
3688        }
3689        return null;
3690    }
3691
3692    @Override
3693    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3694            int userId) {
3695        if (!sUserManager.exists(userId)) return Collections.emptyList();
3696        ComponentName comp = intent.getComponent();
3697        if (comp == null) {
3698            if (intent.getSelector() != null) {
3699                intent = intent.getSelector();
3700                comp = intent.getComponent();
3701            }
3702        }
3703        if (comp != null) {
3704            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3705            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3706            if (si != null) {
3707                final ResolveInfo ri = new ResolveInfo();
3708                ri.serviceInfo = si;
3709                list.add(ri);
3710            }
3711            return list;
3712        }
3713
3714        // reader
3715        synchronized (mPackages) {
3716            String pkgName = intent.getPackage();
3717            if (pkgName == null) {
3718                return mServices.queryIntent(intent, resolvedType, flags, userId);
3719            }
3720            final PackageParser.Package pkg = mPackages.get(pkgName);
3721            if (pkg != null) {
3722                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3723                        userId);
3724            }
3725            return null;
3726        }
3727    }
3728
3729    @Override
3730    public List<ResolveInfo> queryIntentContentProviders(
3731            Intent intent, String resolvedType, int flags, int userId) {
3732        if (!sUserManager.exists(userId)) return Collections.emptyList();
3733        ComponentName comp = intent.getComponent();
3734        if (comp == null) {
3735            if (intent.getSelector() != null) {
3736                intent = intent.getSelector();
3737                comp = intent.getComponent();
3738            }
3739        }
3740        if (comp != null) {
3741            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3742            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3743            if (pi != null) {
3744                final ResolveInfo ri = new ResolveInfo();
3745                ri.providerInfo = pi;
3746                list.add(ri);
3747            }
3748            return list;
3749        }
3750
3751        // reader
3752        synchronized (mPackages) {
3753            String pkgName = intent.getPackage();
3754            if (pkgName == null) {
3755                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3756            }
3757            final PackageParser.Package pkg = mPackages.get(pkgName);
3758            if (pkg != null) {
3759                return mProviders.queryIntentForPackage(
3760                        intent, resolvedType, flags, pkg.providers, userId);
3761            }
3762            return null;
3763        }
3764    }
3765
3766    @Override
3767    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3768        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3769
3770        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3771
3772        // writer
3773        synchronized (mPackages) {
3774            ArrayList<PackageInfo> list;
3775            if (listUninstalled) {
3776                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3777                for (PackageSetting ps : mSettings.mPackages.values()) {
3778                    PackageInfo pi;
3779                    if (ps.pkg != null) {
3780                        pi = generatePackageInfo(ps.pkg, flags, userId);
3781                    } else {
3782                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3783                    }
3784                    if (pi != null) {
3785                        list.add(pi);
3786                    }
3787                }
3788            } else {
3789                list = new ArrayList<PackageInfo>(mPackages.size());
3790                for (PackageParser.Package p : mPackages.values()) {
3791                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3792                    if (pi != null) {
3793                        list.add(pi);
3794                    }
3795                }
3796            }
3797
3798            return new ParceledListSlice<PackageInfo>(list);
3799        }
3800    }
3801
3802    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3803            String[] permissions, boolean[] tmp, int flags, int userId) {
3804        int numMatch = 0;
3805        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3806        for (int i=0; i<permissions.length; i++) {
3807            if (gp.grantedPermissions.contains(permissions[i])) {
3808                tmp[i] = true;
3809                numMatch++;
3810            } else {
3811                tmp[i] = false;
3812            }
3813        }
3814        if (numMatch == 0) {
3815            return;
3816        }
3817        PackageInfo pi;
3818        if (ps.pkg != null) {
3819            pi = generatePackageInfo(ps.pkg, flags, userId);
3820        } else {
3821            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3822        }
3823        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3824            if (numMatch == permissions.length) {
3825                pi.requestedPermissions = permissions;
3826            } else {
3827                pi.requestedPermissions = new String[numMatch];
3828                numMatch = 0;
3829                for (int i=0; i<permissions.length; i++) {
3830                    if (tmp[i]) {
3831                        pi.requestedPermissions[numMatch] = permissions[i];
3832                        numMatch++;
3833                    }
3834                }
3835            }
3836        }
3837        list.add(pi);
3838    }
3839
3840    @Override
3841    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3842            String[] permissions, int flags, int userId) {
3843        if (!sUserManager.exists(userId)) return null;
3844        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3845
3846        // writer
3847        synchronized (mPackages) {
3848            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3849            boolean[] tmpBools = new boolean[permissions.length];
3850            if (listUninstalled) {
3851                for (PackageSetting ps : mSettings.mPackages.values()) {
3852                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3853                }
3854            } else {
3855                for (PackageParser.Package pkg : mPackages.values()) {
3856                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3857                    if (ps != null) {
3858                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3859                                userId);
3860                    }
3861                }
3862            }
3863
3864            return new ParceledListSlice<PackageInfo>(list);
3865        }
3866    }
3867
3868    @Override
3869    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3870        if (!sUserManager.exists(userId)) return null;
3871        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3872
3873        // writer
3874        synchronized (mPackages) {
3875            ArrayList<ApplicationInfo> list;
3876            if (listUninstalled) {
3877                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3878                for (PackageSetting ps : mSettings.mPackages.values()) {
3879                    ApplicationInfo ai;
3880                    if (ps.pkg != null) {
3881                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3882                                ps.readUserState(userId), userId);
3883                    } else {
3884                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3885                    }
3886                    if (ai != null) {
3887                        list.add(ai);
3888                    }
3889                }
3890            } else {
3891                list = new ArrayList<ApplicationInfo>(mPackages.size());
3892                for (PackageParser.Package p : mPackages.values()) {
3893                    if (p.mExtras != null) {
3894                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3895                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3896                        if (ai != null) {
3897                            list.add(ai);
3898                        }
3899                    }
3900                }
3901            }
3902
3903            return new ParceledListSlice<ApplicationInfo>(list);
3904        }
3905    }
3906
3907    public List<ApplicationInfo> getPersistentApplications(int flags) {
3908        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3909
3910        // reader
3911        synchronized (mPackages) {
3912            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3913            final int userId = UserHandle.getCallingUserId();
3914            while (i.hasNext()) {
3915                final PackageParser.Package p = i.next();
3916                if (p.applicationInfo != null
3917                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3918                        && (!mSafeMode || isSystemApp(p))) {
3919                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3920                    if (ps != null) {
3921                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3922                                ps.readUserState(userId), userId);
3923                        if (ai != null) {
3924                            finalList.add(ai);
3925                        }
3926                    }
3927                }
3928            }
3929        }
3930
3931        return finalList;
3932    }
3933
3934    @Override
3935    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3936        if (!sUserManager.exists(userId)) return null;
3937        // reader
3938        synchronized (mPackages) {
3939            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3940            PackageSetting ps = provider != null
3941                    ? mSettings.mPackages.get(provider.owner.packageName)
3942                    : null;
3943            return ps != null
3944                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3945                    && (!mSafeMode || (provider.info.applicationInfo.flags
3946                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3947                    ? PackageParser.generateProviderInfo(provider, flags,
3948                            ps.readUserState(userId), userId)
3949                    : null;
3950        }
3951    }
3952
3953    /**
3954     * @deprecated
3955     */
3956    @Deprecated
3957    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3958        // reader
3959        synchronized (mPackages) {
3960            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3961                    .entrySet().iterator();
3962            final int userId = UserHandle.getCallingUserId();
3963            while (i.hasNext()) {
3964                Map.Entry<String, PackageParser.Provider> entry = i.next();
3965                PackageParser.Provider p = entry.getValue();
3966                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3967
3968                if (ps != null && p.syncable
3969                        && (!mSafeMode || (p.info.applicationInfo.flags
3970                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3971                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3972                            ps.readUserState(userId), userId);
3973                    if (info != null) {
3974                        outNames.add(entry.getKey());
3975                        outInfo.add(info);
3976                    }
3977                }
3978            }
3979        }
3980    }
3981
3982    @Override
3983    public List<ProviderInfo> queryContentProviders(String processName,
3984            int uid, int flags) {
3985        ArrayList<ProviderInfo> finalList = null;
3986        // reader
3987        synchronized (mPackages) {
3988            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3989            final int userId = processName != null ?
3990                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3991            while (i.hasNext()) {
3992                final PackageParser.Provider p = i.next();
3993                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3994                if (ps != null && p.info.authority != null
3995                        && (processName == null
3996                                || (p.info.processName.equals(processName)
3997                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3998                        && mSettings.isEnabledLPr(p.info, flags, userId)
3999                        && (!mSafeMode
4000                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4001                    if (finalList == null) {
4002                        finalList = new ArrayList<ProviderInfo>(3);
4003                    }
4004                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4005                            ps.readUserState(userId), userId);
4006                    if (info != null) {
4007                        finalList.add(info);
4008                    }
4009                }
4010            }
4011        }
4012
4013        if (finalList != null) {
4014            Collections.sort(finalList, mProviderInitOrderSorter);
4015        }
4016
4017        return finalList;
4018    }
4019
4020    @Override
4021    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4022            int flags) {
4023        // reader
4024        synchronized (mPackages) {
4025            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4026            return PackageParser.generateInstrumentationInfo(i, flags);
4027        }
4028    }
4029
4030    @Override
4031    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4032            int flags) {
4033        ArrayList<InstrumentationInfo> finalList =
4034            new ArrayList<InstrumentationInfo>();
4035
4036        // reader
4037        synchronized (mPackages) {
4038            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4039            while (i.hasNext()) {
4040                final PackageParser.Instrumentation p = i.next();
4041                if (targetPackage == null
4042                        || targetPackage.equals(p.info.targetPackage)) {
4043                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4044                            flags);
4045                    if (ii != null) {
4046                        finalList.add(ii);
4047                    }
4048                }
4049            }
4050        }
4051
4052        return finalList;
4053    }
4054
4055    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4056        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4057        if (overlays == null) {
4058            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4059            return;
4060        }
4061        for (PackageParser.Package opkg : overlays.values()) {
4062            // Not much to do if idmap fails: we already logged the error
4063            // and we certainly don't want to abort installation of pkg simply
4064            // because an overlay didn't fit properly. For these reasons,
4065            // ignore the return value of createIdmapForPackagePairLI.
4066            createIdmapForPackagePairLI(pkg, opkg);
4067        }
4068    }
4069
4070    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4071            PackageParser.Package opkg) {
4072        if (!opkg.mTrustedOverlay) {
4073            Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " +
4074                    opkg.mScanPath + ": overlay not trusted");
4075            return false;
4076        }
4077        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4078        if (overlaySet == null) {
4079            Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " +
4080                    opkg.mScanPath + " but target package has no known overlays");
4081            return false;
4082        }
4083        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4084        if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) {
4085            Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath);
4086            return false;
4087        }
4088        PackageParser.Package[] overlayArray =
4089            overlaySet.values().toArray(new PackageParser.Package[0]);
4090        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4091            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4092                return p1.mOverlayPriority - p2.mOverlayPriority;
4093            }
4094        };
4095        Arrays.sort(overlayArray, cmp);
4096
4097        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4098        int i = 0;
4099        for (PackageParser.Package p : overlayArray) {
4100            pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir;
4101        }
4102        return true;
4103    }
4104
4105    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4106        String[] files = dir.list();
4107        if (files == null) {
4108            Log.d(TAG, "No files in app dir " + dir);
4109            return;
4110        }
4111
4112        if (DEBUG_PACKAGE_SCANNING) {
4113            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4114                    + " flags=0x" + Integer.toHexString(flags));
4115        }
4116
4117        int i;
4118        for (i=0; i<files.length; i++) {
4119            File file = new File(dir, files[i]);
4120            if (!isPackageFilename(files[i])) {
4121                // Ignore entries which are not apk's
4122                continue;
4123            }
4124            PackageParser.Package pkg = scanPackageLI(file,
4125                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
4126            // Don't mess around with apps in system partition.
4127            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4128                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
4129                // Delete the apk
4130                Slog.w(TAG, "Cleaning up failed install of " + file);
4131                file.delete();
4132            }
4133        }
4134    }
4135
4136    private static File getSettingsProblemFile() {
4137        File dataDir = Environment.getDataDirectory();
4138        File systemDir = new File(dataDir, "system");
4139        File fname = new File(systemDir, "uiderrors.txt");
4140        return fname;
4141    }
4142
4143    static void reportSettingsProblem(int priority, String msg) {
4144        try {
4145            File fname = getSettingsProblemFile();
4146            FileOutputStream out = new FileOutputStream(fname, true);
4147            PrintWriter pw = new FastPrintWriter(out);
4148            SimpleDateFormat formatter = new SimpleDateFormat();
4149            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4150            pw.println(dateString + ": " + msg);
4151            pw.close();
4152            FileUtils.setPermissions(
4153                    fname.toString(),
4154                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4155                    -1, -1);
4156        } catch (java.io.IOException e) {
4157        }
4158        Slog.println(priority, TAG, msg);
4159    }
4160
4161    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
4162            PackageParser.Package pkg, File srcFile, int parseFlags) {
4163        if (ps != null
4164                && ps.codePath.equals(srcFile)
4165                && ps.timeStamp == srcFile.lastModified()
4166                && !isCompatSignatureUpdateNeeded(pkg)) {
4167            if (ps.signatures.mSignatures != null
4168                    && ps.signatures.mSignatures.length != 0) {
4169                // Optimization: reuse the existing cached certificates
4170                // if the package appears to be unchanged.
4171                pkg.mSignatures = ps.signatures.mSignatures;
4172                return true;
4173            }
4174
4175            Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
4176        } else {
4177            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4178        }
4179
4180        if (!pp.collectCertificates(pkg, parseFlags)) {
4181            mLastScanError = pp.getParseError();
4182            return false;
4183        }
4184        return true;
4185    }
4186
4187    /*
4188     *  Scan a package and return the newly parsed package.
4189     *  Returns null in case of errors and the error code is stored in mLastScanError
4190     */
4191    private PackageParser.Package scanPackageLI(File scanFile,
4192            int parseFlags, int scanMode, long currentTime, UserHandle user) {
4193        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4194        String scanPath = scanFile.getPath();
4195        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
4196        parseFlags |= mDefParseFlags;
4197        PackageParser pp = new PackageParser(scanPath);
4198        pp.setSeparateProcesses(mSeparateProcesses);
4199        pp.setOnlyCoreApps(mOnlyCore);
4200        final PackageParser.Package pkg = pp.parsePackage(scanFile,
4201                scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0);
4202
4203        if (pkg == null) {
4204            mLastScanError = pp.getParseError();
4205            return null;
4206        }
4207
4208        PackageSetting ps = null;
4209        PackageSetting updatedPkg;
4210        // reader
4211        synchronized (mPackages) {
4212            // Look to see if we already know about this package.
4213            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4214            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4215                // This package has been renamed to its original name.  Let's
4216                // use that.
4217                ps = mSettings.peekPackageLPr(oldName);
4218            }
4219            // If there was no original package, see one for the real package name.
4220            if (ps == null) {
4221                ps = mSettings.peekPackageLPr(pkg.packageName);
4222            }
4223            // Check to see if this package could be hiding/updating a system
4224            // package.  Must look for it either under the original or real
4225            // package name depending on our state.
4226            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4227            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4228        }
4229        boolean updatedPkgBetter = false;
4230        // First check if this is a system package that may involve an update
4231        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4232            if (ps != null && !ps.codePath.equals(scanFile)) {
4233                // The path has changed from what was last scanned...  check the
4234                // version of the new path against what we have stored to determine
4235                // what to do.
4236                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4237                if (pkg.mVersionCode < ps.versionCode) {
4238                    // The system package has been updated and the code path does not match
4239                    // Ignore entry. Skip it.
4240                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4241                            + " ignored: updated version " + ps.versionCode
4242                            + " better than this " + pkg.mVersionCode);
4243                    if (!updatedPkg.codePath.equals(scanFile)) {
4244                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4245                                + ps.name + " changing from " + updatedPkg.codePathString
4246                                + " to " + scanFile);
4247                        updatedPkg.codePath = scanFile;
4248                        updatedPkg.codePathString = scanFile.toString();
4249                        // This is the point at which we know that the system-disk APK
4250                        // for this package has moved during a reboot (e.g. due to an OTA),
4251                        // so we need to reevaluate it for privilege policy.
4252                        if (locationIsPrivileged(scanFile)) {
4253                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4254                        }
4255                    }
4256                    updatedPkg.pkg = pkg;
4257                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4258                    return null;
4259                } else {
4260                    // The current app on the system partion is better than
4261                    // what we have updated to on the data partition; switch
4262                    // back to the system partition version.
4263                    // At this point, its safely assumed that package installation for
4264                    // apps in system partition will go through. If not there won't be a working
4265                    // version of the app
4266                    // writer
4267                    synchronized (mPackages) {
4268                        // Just remove the loaded entries from package lists.
4269                        mPackages.remove(ps.name);
4270                    }
4271                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4272                            + "reverting from " + ps.codePathString
4273                            + ": new version " + pkg.mVersionCode
4274                            + " better than installed " + ps.versionCode);
4275
4276                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4277                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4278                            getAppInstructionSetFromSettings(ps));
4279                    synchronized (mInstallLock) {
4280                        args.cleanUpResourcesLI();
4281                    }
4282                    synchronized (mPackages) {
4283                        mSettings.enableSystemPackageLPw(ps.name);
4284                    }
4285                    updatedPkgBetter = true;
4286                }
4287            }
4288        }
4289
4290        if (updatedPkg != null) {
4291            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4292            // initially
4293            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4294
4295            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4296            // flag set initially
4297            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4298                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4299            }
4300        }
4301        // Verify certificates against what was last scanned
4302        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
4303            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
4304            return null;
4305        }
4306
4307        /*
4308         * A new system app appeared, but we already had a non-system one of the
4309         * same name installed earlier.
4310         */
4311        boolean shouldHideSystemApp = false;
4312        if (updatedPkg == null && ps != null
4313                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4314            /*
4315             * Check to make sure the signatures match first. If they don't,
4316             * wipe the installed application and its data.
4317             */
4318            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4319                    != PackageManager.SIGNATURE_MATCH) {
4320                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4321                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4322                ps = null;
4323            } else {
4324                /*
4325                 * If the newly-added system app is an older version than the
4326                 * already installed version, hide it. It will be scanned later
4327                 * and re-added like an update.
4328                 */
4329                if (pkg.mVersionCode < ps.versionCode) {
4330                    shouldHideSystemApp = true;
4331                } else {
4332                    /*
4333                     * The newly found system app is a newer version that the
4334                     * one previously installed. Simply remove the
4335                     * already-installed application and replace it with our own
4336                     * while keeping the application data.
4337                     */
4338                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4339                            + ps.codePathString + ": new version " + pkg.mVersionCode
4340                            + " better than installed " + ps.versionCode);
4341                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4342                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4343                            getAppInstructionSetFromSettings(ps));
4344                    synchronized (mInstallLock) {
4345                        args.cleanUpResourcesLI();
4346                    }
4347                }
4348            }
4349        }
4350
4351        // The apk is forward locked (not public) if its code and resources
4352        // are kept in different files. (except for app in either system or
4353        // vendor path).
4354        // TODO grab this value from PackageSettings
4355        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4356            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4357                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4358            }
4359        }
4360
4361        String codePath = null;
4362        String resPath = null;
4363        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4364            if (ps != null && ps.resourcePathString != null) {
4365                resPath = ps.resourcePathString;
4366            } else {
4367                // Should not happen at all. Just log an error.
4368                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4369            }
4370        } else {
4371            resPath = pkg.mScanPath;
4372        }
4373
4374        codePath = pkg.mScanPath;
4375        // Set application objects path explicitly.
4376        setApplicationInfoPaths(pkg, codePath, resPath);
4377        // Note that we invoke the following method only if we are about to unpack an application
4378        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4379                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4380
4381        /*
4382         * If the system app should be overridden by a previously installed
4383         * data, hide the system app now and let the /data/app scan pick it up
4384         * again.
4385         */
4386        if (shouldHideSystemApp) {
4387            synchronized (mPackages) {
4388                /*
4389                 * We have to grant systems permissions before we hide, because
4390                 * grantPermissions will assume the package update is trying to
4391                 * expand its permissions.
4392                 */
4393                grantPermissionsLPw(pkg, true);
4394                mSettings.disableSystemPackageLPw(pkg.packageName);
4395            }
4396        }
4397
4398        return scannedPkg;
4399    }
4400
4401    private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
4402            String destResPath) {
4403        pkg.mPath = pkg.mScanPath = destCodePath;
4404        pkg.applicationInfo.sourceDir = destCodePath;
4405        pkg.applicationInfo.publicSourceDir = destResPath;
4406    }
4407
4408    private static String fixProcessName(String defProcessName,
4409            String processName, int uid) {
4410        if (processName == null) {
4411            return defProcessName;
4412        }
4413        return processName;
4414    }
4415
4416    private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) {
4417        if (pkgSetting.signatures.mSignatures != null) {
4418            // Already existing package. Make sure signatures match
4419            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4420                    == PackageManager.SIGNATURE_MATCH;
4421            if (!match) {
4422                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4423                        == PackageManager.SIGNATURE_MATCH;
4424            }
4425            if (!match) {
4426                Slog.e(TAG, "Package " + pkg.packageName
4427                        + " signatures do not match the previously installed version; ignoring!");
4428                mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4429                return false;
4430            }
4431        }
4432        // Check for shared user signatures
4433        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4434            // Already existing package. Make sure signatures match
4435            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4436                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4437            if (!match) {
4438                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4439                        == PackageManager.SIGNATURE_MATCH;
4440            }
4441            if (!match) {
4442                Slog.e(TAG, "Package " + pkg.packageName
4443                        + " has no signatures that match those in shared user "
4444                        + pkgSetting.sharedUser.name + "; ignoring!");
4445                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4446                return false;
4447            }
4448        }
4449        return true;
4450    }
4451
4452    /**
4453     * Enforces that only the system UID or root's UID can call a method exposed
4454     * via Binder.
4455     *
4456     * @param message used as message if SecurityException is thrown
4457     * @throws SecurityException if the caller is not system or root
4458     */
4459    private static final void enforceSystemOrRoot(String message) {
4460        final int uid = Binder.getCallingUid();
4461        if (uid != Process.SYSTEM_UID && uid != 0) {
4462            throw new SecurityException(message);
4463        }
4464    }
4465
4466    @Override
4467    public void performBootDexOpt() {
4468        enforceSystemOrRoot("Only the system can request dexopt be performed");
4469
4470        final HashSet<PackageParser.Package> pkgs;
4471        synchronized (mPackages) {
4472            pkgs = mDeferredDexOpt;
4473            mDeferredDexOpt = null;
4474        }
4475
4476        if (pkgs != null) {
4477            // Filter out packages that aren't recently used.
4478            //
4479            // The exception is first boot of a non-eng device, which
4480            // should do a full dexopt.
4481            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4482            if (eng || !isFirstBoot()) {
4483                // TODO: add a property to control this?
4484                long dexOptLRUThresholdInMinutes;
4485                if (eng) {
4486                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4487                } else {
4488                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4489                }
4490                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4491
4492                int total = pkgs.size();
4493                int skipped = 0;
4494                long now = System.currentTimeMillis();
4495                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4496                    PackageParser.Package pkg = i.next();
4497                    long then = pkg.mLastPackageUsageTimeInMills;
4498                    if (then + dexOptLRUThresholdInMills < now) {
4499                        if (DEBUG_DEXOPT) {
4500                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4501                                  ((then == 0) ? "never" : new Date(then)));
4502                        }
4503                        i.remove();
4504                        skipped++;
4505                    }
4506                }
4507                if (DEBUG_DEXOPT) {
4508                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4509                }
4510            }
4511
4512            int i = 0;
4513            for (PackageParser.Package pkg : pkgs) {
4514                i++;
4515                if (DEBUG_DEXOPT) {
4516                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4517                          + ": " + pkg.packageName);
4518                }
4519                if (!isFirstBoot()) {
4520                    try {
4521                        ActivityManagerNative.getDefault().showBootMessage(
4522                                mContext.getResources().getString(
4523                                        R.string.android_upgrading_apk,
4524                                        i, pkgs.size()), true);
4525                    } catch (RemoteException e) {
4526                    }
4527                }
4528                PackageParser.Package p = pkg;
4529                synchronized (mInstallLock) {
4530                    if (p.mDexOptNeeded) {
4531                        performDexOptLI(p, false /* force dex */, false /* defer */,
4532                                true /* include dependencies */);
4533                    }
4534                }
4535            }
4536        }
4537    }
4538
4539    @Override
4540    public boolean performDexOpt(String packageName) {
4541        enforceSystemOrRoot("Only the system can request dexopt be performed");
4542        return performDexOpt(packageName, true);
4543    }
4544
4545    public boolean performDexOpt(String packageName, boolean updateUsage) {
4546
4547        PackageParser.Package p;
4548        synchronized (mPackages) {
4549            p = mPackages.get(packageName);
4550            if (p == null) {
4551                return false;
4552            }
4553            if (updateUsage) {
4554                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4555            }
4556            mPackageUsage.write(false);
4557            if (!p.mDexOptNeeded) {
4558                return false;
4559            }
4560        }
4561
4562        synchronized (mInstallLock) {
4563            return performDexOptLI(p, false /* force dex */, false /* defer */,
4564                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4565        }
4566    }
4567
4568    public HashSet<String> getPackagesThatNeedDexOpt() {
4569        HashSet<String> pkgs = null;
4570        synchronized (mPackages) {
4571            for (PackageParser.Package p : mPackages.values()) {
4572                if (DEBUG_DEXOPT) {
4573                    Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded);
4574                }
4575                if (!p.mDexOptNeeded) {
4576                    continue;
4577                }
4578                if (pkgs == null) {
4579                    pkgs = new HashSet<String>();
4580                }
4581                pkgs.add(p.packageName);
4582            }
4583        }
4584        return pkgs;
4585    }
4586
4587    public void shutdown() {
4588        mPackageUsage.write(true);
4589    }
4590
4591    private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet,
4592             boolean forceDex, boolean defer, HashSet<String> done) {
4593        for (int i=0; i<libs.size(); i++) {
4594            PackageParser.Package libPkg;
4595            String libName;
4596            synchronized (mPackages) {
4597                libName = libs.get(i);
4598                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4599                if (lib != null && lib.apk != null) {
4600                    libPkg = mPackages.get(lib.apk);
4601                } else {
4602                    libPkg = null;
4603                }
4604            }
4605            if (libPkg != null && !done.contains(libName)) {
4606                performDexOptLI(libPkg, instructionSet, forceDex, defer, done);
4607            }
4608        }
4609    }
4610
4611    static final int DEX_OPT_SKIPPED = 0;
4612    static final int DEX_OPT_PERFORMED = 1;
4613    static final int DEX_OPT_DEFERRED = 2;
4614    static final int DEX_OPT_FAILED = -1;
4615
4616    private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride,
4617            boolean forceDex, boolean defer, HashSet<String> done) {
4618        final String instructionSet = instructionSetOverride != null ?
4619                instructionSetOverride : getAppInstructionSet(pkg.applicationInfo);
4620
4621        if (done != null) {
4622            done.add(pkg.packageName);
4623            if (pkg.usesLibraries != null) {
4624                performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done);
4625            }
4626            if (pkg.usesOptionalLibraries != null) {
4627                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done);
4628            }
4629        }
4630
4631        boolean performed = false;
4632        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4633            String path = pkg.mScanPath;
4634            try {
4635                boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path,
4636                                                                                pkg.packageName,
4637                                                                                instructionSet,
4638                                                                                defer);
4639                // There are three basic cases here:
4640                // 1.) we need to dexopt, either because we are forced or it is needed
4641                // 2.) we are defering a needed dexopt
4642                // 3.) we are skipping an unneeded dexopt
4643                if (forceDex || (!defer && isDexOptNeededInternal)) {
4644                    Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
4645                    final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4646                    int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4647                                                pkg.packageName, instructionSet);
4648                    // Note that we ran dexopt, since rerunning will
4649                    // probably just result in an error again.
4650                    pkg.mDexOptNeeded = false;
4651                    if (ret < 0) {
4652                        return DEX_OPT_FAILED;
4653                    }
4654                    return DEX_OPT_PERFORMED;
4655                }
4656                if (defer && isDexOptNeededInternal) {
4657                    if (mDeferredDexOpt == null) {
4658                        mDeferredDexOpt = new HashSet<PackageParser.Package>();
4659                    }
4660                    mDeferredDexOpt.add(pkg);
4661                    return DEX_OPT_DEFERRED;
4662                }
4663                pkg.mDexOptNeeded = false;
4664                return DEX_OPT_SKIPPED;
4665            } catch (FileNotFoundException e) {
4666                Slog.w(TAG, "Apk not found for dexopt: " + path);
4667                return DEX_OPT_FAILED;
4668            } catch (IOException e) {
4669                Slog.w(TAG, "IOException reading apk: " + path, e);
4670                return DEX_OPT_FAILED;
4671            } catch (StaleDexCacheError e) {
4672                Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4673                return DEX_OPT_FAILED;
4674            } catch (Exception e) {
4675                Slog.w(TAG, "Exception when doing dexopt : ", e);
4676                return DEX_OPT_FAILED;
4677            }
4678        }
4679        return DEX_OPT_SKIPPED;
4680    }
4681
4682    private String getAppInstructionSet(ApplicationInfo info) {
4683        String instructionSet = getPreferredInstructionSet();
4684
4685        if (info.cpuAbi != null) {
4686            instructionSet = VMRuntime.getInstructionSet(info.cpuAbi);
4687        }
4688
4689        return instructionSet;
4690    }
4691
4692    private String getAppInstructionSetFromSettings(PackageSetting ps) {
4693        String instructionSet = getPreferredInstructionSet();
4694
4695        if (ps.cpuAbiString != null) {
4696            instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
4697        }
4698
4699        return instructionSet;
4700    }
4701
4702    private static String getPreferredInstructionSet() {
4703        if (sPreferredInstructionSet == null) {
4704            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4705        }
4706
4707        return sPreferredInstructionSet;
4708    }
4709
4710    private static List<String> getAllInstructionSets() {
4711        final String[] allAbis = Build.SUPPORTED_ABIS;
4712        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4713
4714        for (String abi : allAbis) {
4715            final String instructionSet = VMRuntime.getInstructionSet(abi);
4716            if (!allInstructionSets.contains(instructionSet)) {
4717                allInstructionSets.add(instructionSet);
4718            }
4719        }
4720
4721        return allInstructionSets;
4722    }
4723
4724    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4725            boolean inclDependencies) {
4726        HashSet<String> done;
4727        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4728            done = new HashSet<String>();
4729            done.add(pkg.packageName);
4730        } else {
4731            done = null;
4732        }
4733        return performDexOptLI(pkg, null /* instruction set override */,  forceDex, defer, done);
4734    }
4735
4736    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4737        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4738            Slog.w(TAG, "Unable to update from " + oldPkg.name
4739                    + " to " + newPkg.packageName
4740                    + ": old package not in system partition");
4741            return false;
4742        } else if (mPackages.get(oldPkg.name) != null) {
4743            Slog.w(TAG, "Unable to update from " + oldPkg.name
4744                    + " to " + newPkg.packageName
4745                    + ": old package still exists");
4746            return false;
4747        }
4748        return true;
4749    }
4750
4751    File getDataPathForUser(int userId) {
4752        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4753    }
4754
4755    private File getDataPathForPackage(String packageName, int userId) {
4756        /*
4757         * Until we fully support multiple users, return the directory we
4758         * previously would have. The PackageManagerTests will need to be
4759         * revised when this is changed back..
4760         */
4761        if (userId == 0) {
4762            return new File(mAppDataDir, packageName);
4763        } else {
4764            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4765                + File.separator + packageName);
4766        }
4767    }
4768
4769    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4770        int[] users = sUserManager.getUserIds();
4771        int res = mInstaller.install(packageName, uid, uid, seinfo);
4772        if (res < 0) {
4773            return res;
4774        }
4775        for (int user : users) {
4776            if (user != 0) {
4777                res = mInstaller.createUserData(packageName,
4778                        UserHandle.getUid(user, uid), user, seinfo);
4779                if (res < 0) {
4780                    return res;
4781                }
4782            }
4783        }
4784        return res;
4785    }
4786
4787    private int removeDataDirsLI(String packageName) {
4788        int[] users = sUserManager.getUserIds();
4789        int res = 0;
4790        for (int user : users) {
4791            int resInner = mInstaller.remove(packageName, user);
4792            if (resInner < 0) {
4793                res = resInner;
4794            }
4795        }
4796
4797        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4798        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4799        if (!nativeLibraryFile.delete()) {
4800            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4801        }
4802
4803        return res;
4804    }
4805
4806    private int addSharedLibraryLPw(final SharedLibraryEntry file, int num,
4807            PackageParser.Package changingLib) {
4808        if (file.path != null) {
4809            mTmpSharedLibraries[num] = file.path;
4810            return num+1;
4811        }
4812        PackageParser.Package p = mPackages.get(file.apk);
4813        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4814            // If we are doing this while in the middle of updating a library apk,
4815            // then we need to make sure to use that new apk for determining the
4816            // dependencies here.  (We haven't yet finished committing the new apk
4817            // to the package manager state.)
4818            if (p == null || p.packageName.equals(changingLib.packageName)) {
4819                p = changingLib;
4820            }
4821        }
4822        if (p != null) {
4823            String path = p.mPath;
4824            for (int i=0; i<num; i++) {
4825                if (mTmpSharedLibraries[i].equals(path)) {
4826                    return num;
4827                }
4828            }
4829            mTmpSharedLibraries[num] = p.mPath;
4830            return num+1;
4831        }
4832        return num;
4833    }
4834
4835    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4836            PackageParser.Package changingLib) {
4837        // We might be upgrading from a version of the platform that did not
4838        // provide per-package native library directories for system apps.
4839        // Fix that up here.
4840        if (isSystemApp(pkg)) {
4841            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4842            setInternalAppNativeLibraryPath(pkg, ps);
4843        }
4844
4845        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4846            if (mTmpSharedLibraries == null ||
4847                    mTmpSharedLibraries.length < mSharedLibraries.size()) {
4848                mTmpSharedLibraries = new String[mSharedLibraries.size()];
4849            }
4850            int num = 0;
4851            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4852            for (int i=0; i<N; i++) {
4853                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4854                if (file == null) {
4855                    Slog.e(TAG, "Package " + pkg.packageName
4856                            + " requires unavailable shared library "
4857                            + pkg.usesLibraries.get(i) + "; failing!");
4858                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4859                    return false;
4860                }
4861                num = addSharedLibraryLPw(file, num, changingLib);
4862            }
4863            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4864            for (int i=0; i<N; i++) {
4865                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4866                if (file == null) {
4867                    Slog.w(TAG, "Package " + pkg.packageName
4868                            + " desires unavailable shared library "
4869                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4870                } else {
4871                    num = addSharedLibraryLPw(file, num, changingLib);
4872                }
4873            }
4874            if (num > 0) {
4875                pkg.usesLibraryFiles = new String[num];
4876                System.arraycopy(mTmpSharedLibraries, 0,
4877                        pkg.usesLibraryFiles, 0, num);
4878            } else {
4879                pkg.usesLibraryFiles = null;
4880            }
4881        }
4882        return true;
4883    }
4884
4885    private static boolean hasString(List<String> list, List<String> which) {
4886        if (list == null) {
4887            return false;
4888        }
4889        for (int i=list.size()-1; i>=0; i--) {
4890            for (int j=which.size()-1; j>=0; j--) {
4891                if (which.get(j).equals(list.get(i))) {
4892                    return true;
4893                }
4894            }
4895        }
4896        return false;
4897    }
4898
4899    private void updateAllSharedLibrariesLPw() {
4900        for (PackageParser.Package pkg : mPackages.values()) {
4901            updateSharedLibrariesLPw(pkg, null);
4902        }
4903    }
4904
4905    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4906            PackageParser.Package changingPkg) {
4907        ArrayList<PackageParser.Package> res = null;
4908        for (PackageParser.Package pkg : mPackages.values()) {
4909            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4910                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4911                if (res == null) {
4912                    res = new ArrayList<PackageParser.Package>();
4913                }
4914                res.add(pkg);
4915                updateSharedLibrariesLPw(pkg, changingPkg);
4916            }
4917        }
4918        return res;
4919    }
4920
4921    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4922            int parseFlags, int scanMode, long currentTime, UserHandle user) {
4923        File scanFile = new File(pkg.mScanPath);
4924        if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
4925                pkg.applicationInfo.publicSourceDir == null) {
4926            // Bail out. The resource and code paths haven't been set.
4927            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4928            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4929            return null;
4930        }
4931
4932        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4933            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4934        }
4935
4936        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4937            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4938        }
4939
4940        if (mCustomResolverComponentName != null &&
4941                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4942            setUpCustomResolverActivity(pkg);
4943        }
4944
4945        if (pkg.packageName.equals("android")) {
4946            synchronized (mPackages) {
4947                if (mAndroidApplication != null) {
4948                    Slog.w(TAG, "*************************************************");
4949                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4950                    Slog.w(TAG, " file=" + scanFile);
4951                    Slog.w(TAG, "*************************************************");
4952                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4953                    return null;
4954                }
4955
4956                // Set up information for our fall-back user intent resolution activity.
4957                mPlatformPackage = pkg;
4958                pkg.mVersionCode = mSdkVersion;
4959                mAndroidApplication = pkg.applicationInfo;
4960
4961                if (!mResolverReplaced) {
4962                    mResolveActivity.applicationInfo = mAndroidApplication;
4963                    mResolveActivity.name = ResolverActivity.class.getName();
4964                    mResolveActivity.packageName = mAndroidApplication.packageName;
4965                    mResolveActivity.processName = "system:ui";
4966                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4967                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4968                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
4969                    mResolveActivity.exported = true;
4970                    mResolveActivity.enabled = true;
4971                    mResolveInfo.activityInfo = mResolveActivity;
4972                    mResolveInfo.priority = 0;
4973                    mResolveInfo.preferredOrder = 0;
4974                    mResolveInfo.match = 0;
4975                    mResolveComponentName = new ComponentName(
4976                            mAndroidApplication.packageName, mResolveActivity.name);
4977                }
4978            }
4979        }
4980
4981        if (DEBUG_PACKAGE_SCANNING) {
4982            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4983                Log.d(TAG, "Scanning package " + pkg.packageName);
4984        }
4985
4986        if (mPackages.containsKey(pkg.packageName)
4987                || mSharedLibraries.containsKey(pkg.packageName)) {
4988            Slog.w(TAG, "Application package " + pkg.packageName
4989                    + " already installed.  Skipping duplicate.");
4990            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4991            return null;
4992        }
4993
4994        // Initialize package source and resource directories
4995        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
4996        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
4997
4998        SharedUserSetting suid = null;
4999        PackageSetting pkgSetting = null;
5000
5001        if (!isSystemApp(pkg)) {
5002            // Only system apps can use these features.
5003            pkg.mOriginalPackages = null;
5004            pkg.mRealPackage = null;
5005            pkg.mAdoptPermissions = null;
5006        }
5007
5008        // writer
5009        synchronized (mPackages) {
5010            if (pkg.mSharedUserId != null) {
5011                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5012                if (suid == null) {
5013                    Slog.w(TAG, "Creating application package " + pkg.packageName
5014                            + " for shared user failed");
5015                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5016                    return null;
5017                }
5018                if (DEBUG_PACKAGE_SCANNING) {
5019                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5020                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5021                                + "): packages=" + suid.packages);
5022                }
5023            }
5024
5025            // Check if we are renaming from an original package name.
5026            PackageSetting origPackage = null;
5027            String realName = null;
5028            if (pkg.mOriginalPackages != null) {
5029                // This package may need to be renamed to a previously
5030                // installed name.  Let's check on that...
5031                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5032                if (pkg.mOriginalPackages.contains(renamed)) {
5033                    // This package had originally been installed as the
5034                    // original name, and we have already taken care of
5035                    // transitioning to the new one.  Just update the new
5036                    // one to continue using the old name.
5037                    realName = pkg.mRealPackage;
5038                    if (!pkg.packageName.equals(renamed)) {
5039                        // Callers into this function may have already taken
5040                        // care of renaming the package; only do it here if
5041                        // it is not already done.
5042                        pkg.setPackageName(renamed);
5043                    }
5044
5045                } else {
5046                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5047                        if ((origPackage = mSettings.peekPackageLPr(
5048                                pkg.mOriginalPackages.get(i))) != null) {
5049                            // We do have the package already installed under its
5050                            // original name...  should we use it?
5051                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5052                                // New package is not compatible with original.
5053                                origPackage = null;
5054                                continue;
5055                            } else if (origPackage.sharedUser != null) {
5056                                // Make sure uid is compatible between packages.
5057                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5058                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5059                                            + " to " + pkg.packageName + ": old uid "
5060                                            + origPackage.sharedUser.name
5061                                            + " differs from " + pkg.mSharedUserId);
5062                                    origPackage = null;
5063                                    continue;
5064                                }
5065                            } else {
5066                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5067                                        + pkg.packageName + " to old name " + origPackage.name);
5068                            }
5069                            break;
5070                        }
5071                    }
5072                }
5073            }
5074
5075            if (mTransferedPackages.contains(pkg.packageName)) {
5076                Slog.w(TAG, "Package " + pkg.packageName
5077                        + " was transferred to another, but its .apk remains");
5078            }
5079
5080            // Just create the setting, don't add it yet. For already existing packages
5081            // the PkgSetting exists already and doesn't have to be created.
5082            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5083                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
5084                    pkg.applicationInfo.cpuAbi,
5085                    pkg.applicationInfo.flags, user, false);
5086            if (pkgSetting == null) {
5087                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
5088                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5089                return null;
5090            }
5091
5092            if (pkgSetting.origPackage != null) {
5093                // If we are first transitioning from an original package,
5094                // fix up the new package's name now.  We need to do this after
5095                // looking up the package under its new name, so getPackageLP
5096                // can take care of fiddling things correctly.
5097                pkg.setPackageName(origPackage.name);
5098
5099                // File a report about this.
5100                String msg = "New package " + pkgSetting.realName
5101                        + " renamed to replace old package " + pkgSetting.name;
5102                reportSettingsProblem(Log.WARN, msg);
5103
5104                // Make a note of it.
5105                mTransferedPackages.add(origPackage.name);
5106
5107                // No longer need to retain this.
5108                pkgSetting.origPackage = null;
5109            }
5110
5111            if (realName != null) {
5112                // Make a note of it.
5113                mTransferedPackages.add(pkg.packageName);
5114            }
5115
5116            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5117                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5118            }
5119
5120            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5121                // Check all shared libraries and map to their actual file path.
5122                // We only do this here for apps not on a system dir, because those
5123                // are the only ones that can fail an install due to this.  We
5124                // will take care of the system apps by updating all of their
5125                // library paths after the scan is done.
5126                if (!updateSharedLibrariesLPw(pkg, null)) {
5127                    return null;
5128                }
5129            }
5130
5131            if (mFoundPolicyFile) {
5132                SELinuxMMAC.assignSeinfoValue(pkg);
5133            }
5134
5135            pkg.applicationInfo.uid = pkgSetting.appId;
5136            pkg.mExtras = pkgSetting;
5137
5138            if (!verifySignaturesLP(pkgSetting, pkg)) {
5139                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5140                    return null;
5141                }
5142                // The signature has changed, but this package is in the system
5143                // image...  let's recover!
5144                pkgSetting.signatures.mSignatures = pkg.mSignatures;
5145                // However...  if this package is part of a shared user, but it
5146                // doesn't match the signature of the shared user, let's fail.
5147                // What this means is that you can't change the signatures
5148                // associated with an overall shared user, which doesn't seem all
5149                // that unreasonable.
5150                if (pkgSetting.sharedUser != null) {
5151                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5152                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5153                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
5154                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5155                        return null;
5156                    }
5157                }
5158                // File a report about this.
5159                String msg = "System package " + pkg.packageName
5160                        + " signature changed; retaining data.";
5161                reportSettingsProblem(Log.WARN, msg);
5162            }
5163
5164            // Verify that this new package doesn't have any content providers
5165            // that conflict with existing packages.  Only do this if the
5166            // package isn't already installed, since we don't want to break
5167            // things that are installed.
5168            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5169                final int N = pkg.providers.size();
5170                int i;
5171                for (i=0; i<N; i++) {
5172                    PackageParser.Provider p = pkg.providers.get(i);
5173                    if (p.info.authority != null) {
5174                        String names[] = p.info.authority.split(";");
5175                        for (int j = 0; j < names.length; j++) {
5176                            if (mProvidersByAuthority.containsKey(names[j])) {
5177                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5178                                Slog.w(TAG, "Can't install because provider name " + names[j] +
5179                                        " (in package " + pkg.applicationInfo.packageName +
5180                                        ") is already used by "
5181                                        + ((other != null && other.getComponentName() != null)
5182                                                ? other.getComponentName().getPackageName() : "?"));
5183                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
5184                                return null;
5185                            }
5186                        }
5187                    }
5188                }
5189            }
5190
5191            if (pkg.mAdoptPermissions != null) {
5192                // This package wants to adopt ownership of permissions from
5193                // another package.
5194                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5195                    final String origName = pkg.mAdoptPermissions.get(i);
5196                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5197                    if (orig != null) {
5198                        if (verifyPackageUpdateLPr(orig, pkg)) {
5199                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5200                                    + pkg.packageName);
5201                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5202                        }
5203                    }
5204                }
5205            }
5206        }
5207
5208        final String pkgName = pkg.packageName;
5209
5210        final long scanFileTime = scanFile.lastModified();
5211        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5212        pkg.applicationInfo.processName = fixProcessName(
5213                pkg.applicationInfo.packageName,
5214                pkg.applicationInfo.processName,
5215                pkg.applicationInfo.uid);
5216
5217        File dataPath;
5218        if (mPlatformPackage == pkg) {
5219            // The system package is special.
5220            dataPath = new File (Environment.getDataDirectory(), "system");
5221            pkg.applicationInfo.dataDir = dataPath.getPath();
5222        } else {
5223            // This is a normal package, need to make its data directory.
5224            dataPath = getDataPathForPackage(pkg.packageName, 0);
5225
5226            boolean uidError = false;
5227
5228            if (dataPath.exists()) {
5229                int currentUid = 0;
5230                try {
5231                    StructStat stat = Os.stat(dataPath.getPath());
5232                    currentUid = stat.st_uid;
5233                } catch (ErrnoException e) {
5234                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5235                }
5236
5237                // If we have mismatched owners for the data path, we have a problem.
5238                if (currentUid != pkg.applicationInfo.uid) {
5239                    boolean recovered = false;
5240                    if (currentUid == 0) {
5241                        // The directory somehow became owned by root.  Wow.
5242                        // This is probably because the system was stopped while
5243                        // installd was in the middle of messing with its libs
5244                        // directory.  Ask installd to fix that.
5245                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5246                                pkg.applicationInfo.uid);
5247                        if (ret >= 0) {
5248                            recovered = true;
5249                            String msg = "Package " + pkg.packageName
5250                                    + " unexpectedly changed to uid 0; recovered to " +
5251                                    + pkg.applicationInfo.uid;
5252                            reportSettingsProblem(Log.WARN, msg);
5253                        }
5254                    }
5255                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5256                            || (scanMode&SCAN_BOOTING) != 0)) {
5257                        // If this is a system app, we can at least delete its
5258                        // current data so the application will still work.
5259                        int ret = removeDataDirsLI(pkgName);
5260                        if (ret >= 0) {
5261                            // TODO: Kill the processes first
5262                            // Old data gone!
5263                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5264                                    ? "System package " : "Third party package ";
5265                            String msg = prefix + pkg.packageName
5266                                    + " has changed from uid: "
5267                                    + currentUid + " to "
5268                                    + pkg.applicationInfo.uid + "; old data erased";
5269                            reportSettingsProblem(Log.WARN, msg);
5270                            recovered = true;
5271
5272                            // And now re-install the app.
5273                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5274                                                   pkg.applicationInfo.seinfo);
5275                            if (ret == -1) {
5276                                // Ack should not happen!
5277                                msg = prefix + pkg.packageName
5278                                        + " could not have data directory re-created after delete.";
5279                                reportSettingsProblem(Log.WARN, msg);
5280                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5281                                return null;
5282                            }
5283                        }
5284                        if (!recovered) {
5285                            mHasSystemUidErrors = true;
5286                        }
5287                    } else if (!recovered) {
5288                        // If we allow this install to proceed, we will be broken.
5289                        // Abort, abort!
5290                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
5291                        return null;
5292                    }
5293                    if (!recovered) {
5294                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5295                            + pkg.applicationInfo.uid + "/fs_"
5296                            + currentUid;
5297                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5298                        String msg = "Package " + pkg.packageName
5299                                + " has mismatched uid: "
5300                                + currentUid + " on disk, "
5301                                + pkg.applicationInfo.uid + " in settings";
5302                        // writer
5303                        synchronized (mPackages) {
5304                            mSettings.mReadMessages.append(msg);
5305                            mSettings.mReadMessages.append('\n');
5306                            uidError = true;
5307                            if (!pkgSetting.uidError) {
5308                                reportSettingsProblem(Log.ERROR, msg);
5309                            }
5310                        }
5311                    }
5312                }
5313                pkg.applicationInfo.dataDir = dataPath.getPath();
5314                if (mShouldRestoreconData) {
5315                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5316                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5317                                pkg.applicationInfo.uid);
5318                }
5319            } else {
5320                if (DEBUG_PACKAGE_SCANNING) {
5321                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5322                        Log.v(TAG, "Want this data dir: " + dataPath);
5323                }
5324                //invoke installer to do the actual installation
5325                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5326                                           pkg.applicationInfo.seinfo);
5327                if (ret < 0) {
5328                    // Error from installer
5329                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5330                    return null;
5331                }
5332
5333                if (dataPath.exists()) {
5334                    pkg.applicationInfo.dataDir = dataPath.getPath();
5335                } else {
5336                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5337                    pkg.applicationInfo.dataDir = null;
5338                }
5339            }
5340
5341            /*
5342             * Set the data dir to the default "/data/data/<package name>/lib"
5343             * if we got here without anyone telling us different (e.g., apps
5344             * stored on SD card have their native libraries stored in the ASEC
5345             * container with the APK).
5346             *
5347             * This happens during an upgrade from a package settings file that
5348             * doesn't have a native library path attribute at all.
5349             */
5350            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
5351                if (pkgSetting.nativeLibraryPathString == null) {
5352                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
5353                } else {
5354                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
5355                }
5356            }
5357            pkgSetting.uidError = uidError;
5358        }
5359
5360        String path = scanFile.getPath();
5361        /* Note: We don't want to unpack the native binaries for
5362         *        system applications, unless they have been updated
5363         *        (the binaries are already under /system/lib).
5364         *        Also, don't unpack libs for apps on the external card
5365         *        since they should have their libraries in the ASEC
5366         *        container already.
5367         *
5368         *        In other words, we're going to unpack the binaries
5369         *        only for non-system apps and system app upgrades.
5370         */
5371        if (pkg.applicationInfo.nativeLibraryDir != null) {
5372            try {
5373                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5374                final String dataPathString = dataPath.getCanonicalPath();
5375
5376                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5377                    /*
5378                     * Upgrading from a previous version of the OS sometimes
5379                     * leaves native libraries in the /data/data/<app>/lib
5380                     * directory for system apps even when they shouldn't be.
5381                     * Recent changes in the JNI library search path
5382                     * necessitates we remove those to match previous behavior.
5383                     */
5384                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
5385                        Log.i(TAG, "removed obsolete native libraries for system package "
5386                                + path);
5387                    }
5388
5389                    setInternalAppAbi(pkg, pkgSetting);
5390                } else {
5391                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
5392                        /*
5393                         * Update native library dir if it starts with
5394                         * /data/data
5395                         */
5396                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
5397                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
5398                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5399                        }
5400
5401                        try {
5402                            int copyRet = copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir);
5403                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5404                                Slog.e(TAG, "Unable to copy native libraries");
5405                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5406                                return null;
5407                            }
5408
5409                            // We've successfully copied native libraries across, so we make a
5410                            // note of what ABI we're using
5411                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5412                                pkg.applicationInfo.cpuAbi = Build.SUPPORTED_ABIS[copyRet];
5413                            } else {
5414                                pkg.applicationInfo.cpuAbi = null;
5415                            }
5416                        } catch (IOException e) {
5417                            Slog.e(TAG, "Unable to copy native libraries", e);
5418                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5419                            return null;
5420                        }
5421                    } else {
5422                        // We don't have to copy the shared libraries if we're in the ASEC container
5423                        // but we still need to scan the file to figure out what ABI the app needs.
5424                        //
5425                        // TODO: This duplicates work done in the default container service. It's possible
5426                        // to clean this up but we'll need to change the interface between this service
5427                        // and IMediaContainerService (but doing so will spread this logic out, rather
5428                        // than centralizing it).
5429                        final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5430                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS);
5431                        if (abi >= 0) {
5432                            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_ABIS[abi];
5433                        } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) {
5434                            // Note that (non upgraded) system apps will not have any native
5435                            // libraries bundled in their APK, but we're guaranteed not to be
5436                            // such an app at this point.
5437                            pkg.applicationInfo.cpuAbi = null;
5438                        } else {
5439                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5440                            return null;
5441                        }
5442                        handle.close();
5443                    }
5444
5445                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5446                    final int[] userIds = sUserManager.getUserIds();
5447                    synchronized (mInstallLock) {
5448                        for (int userId : userIds) {
5449                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
5450                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
5451                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
5452                                        + ")");
5453                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5454                                return null;
5455                            }
5456                        }
5457                    }
5458                }
5459            } catch (IOException ioe) {
5460                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5461            }
5462        }
5463        pkg.mScanPath = path;
5464
5465        if ((scanMode&SCAN_NO_DEX) == 0) {
5466            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5467                    == DEX_OPT_FAILED) {
5468                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5469                    removeDataDirsLI(pkg.packageName);
5470                }
5471
5472                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5473                return null;
5474            }
5475        }
5476
5477        if (mFactoryTest && pkg.requestedPermissions.contains(
5478                android.Manifest.permission.FACTORY_TEST)) {
5479            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5480        }
5481
5482        ArrayList<PackageParser.Package> clientLibPkgs = null;
5483
5484        // writer
5485        synchronized (mPackages) {
5486            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5487                // Only system apps can add new shared libraries.
5488                if (pkg.libraryNames != null) {
5489                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5490                        String name = pkg.libraryNames.get(i);
5491                        boolean allowed = false;
5492                        if (isUpdatedSystemApp(pkg)) {
5493                            // New library entries can only be added through the
5494                            // system image.  This is important to get rid of a lot
5495                            // of nasty edge cases: for example if we allowed a non-
5496                            // system update of the app to add a library, then uninstalling
5497                            // the update would make the library go away, and assumptions
5498                            // we made such as through app install filtering would now
5499                            // have allowed apps on the device which aren't compatible
5500                            // with it.  Better to just have the restriction here, be
5501                            // conservative, and create many fewer cases that can negatively
5502                            // impact the user experience.
5503                            final PackageSetting sysPs = mSettings
5504                                    .getDisabledSystemPkgLPr(pkg.packageName);
5505                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5506                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5507                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5508                                        allowed = true;
5509                                        allowed = true;
5510                                        break;
5511                                    }
5512                                }
5513                            }
5514                        } else {
5515                            allowed = true;
5516                        }
5517                        if (allowed) {
5518                            if (!mSharedLibraries.containsKey(name)) {
5519                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5520                            } else if (!name.equals(pkg.packageName)) {
5521                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5522                                        + name + " already exists; skipping");
5523                            }
5524                        } else {
5525                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5526                                    + name + " that is not declared on system image; skipping");
5527                        }
5528                    }
5529                    if ((scanMode&SCAN_BOOTING) == 0) {
5530                        // If we are not booting, we need to update any applications
5531                        // that are clients of our shared library.  If we are booting,
5532                        // this will all be done once the scan is complete.
5533                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5534                    }
5535                }
5536            }
5537        }
5538
5539        // We also need to dexopt any apps that are dependent on this library.  Note that
5540        // if these fail, we should abort the install since installing the library will
5541        // result in some apps being broken.
5542        if (clientLibPkgs != null) {
5543            if ((scanMode&SCAN_NO_DEX) == 0) {
5544                for (int i=0; i<clientLibPkgs.size(); i++) {
5545                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5546                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5547                            == DEX_OPT_FAILED) {
5548                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5549                            removeDataDirsLI(pkg.packageName);
5550                        }
5551
5552                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5553                        return null;
5554                    }
5555                }
5556            }
5557        }
5558
5559        // Request the ActivityManager to kill the process(only for existing packages)
5560        // so that we do not end up in a confused state while the user is still using the older
5561        // version of the application while the new one gets installed.
5562        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5563            // If the package lives in an asec, tell everyone that the container is going
5564            // away so they can clean up any references to its resources (which would prevent
5565            // vold from being able to unmount the asec)
5566            if (isForwardLocked(pkg) || isExternal(pkg)) {
5567                if (DEBUG_INSTALL) {
5568                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5569                }
5570                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5571                final ArrayList<String> pkgList = new ArrayList<String>(1);
5572                pkgList.add(pkg.applicationInfo.packageName);
5573                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5574            }
5575
5576            // Post the request that it be killed now that the going-away broadcast is en route
5577            killApplication(pkg.applicationInfo.packageName,
5578                        pkg.applicationInfo.uid, "update pkg");
5579        }
5580
5581        // Also need to kill any apps that are dependent on the library.
5582        if (clientLibPkgs != null) {
5583            for (int i=0; i<clientLibPkgs.size(); i++) {
5584                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5585                killApplication(clientPkg.applicationInfo.packageName,
5586                        clientPkg.applicationInfo.uid, "update lib");
5587            }
5588        }
5589
5590        // writer
5591        synchronized (mPackages) {
5592            if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5593                // We don't do this here during boot because we can do it all
5594                // at once after scanning all existing packages.
5595                adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5596                        true, forceDex, (scanMode & SCAN_DEFER_DEX) != 0);
5597            }
5598            // We don't expect installation to fail beyond this point,
5599            if ((scanMode&SCAN_MONITOR) != 0) {
5600                mAppDirs.put(pkg.mPath, pkg);
5601            }
5602            // Add the new setting to mSettings
5603            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5604            // Add the new setting to mPackages
5605            mPackages.put(pkg.applicationInfo.packageName, pkg);
5606            // Make sure we don't accidentally delete its data.
5607            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5608            while (iter.hasNext()) {
5609                PackageCleanItem item = iter.next();
5610                if (pkgName.equals(item.packageName)) {
5611                    iter.remove();
5612                }
5613            }
5614
5615            // Take care of first install / last update times.
5616            if (currentTime != 0) {
5617                if (pkgSetting.firstInstallTime == 0) {
5618                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5619                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5620                    pkgSetting.lastUpdateTime = currentTime;
5621                }
5622            } else if (pkgSetting.firstInstallTime == 0) {
5623                // We need *something*.  Take time time stamp of the file.
5624                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5625            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5626                if (scanFileTime != pkgSetting.timeStamp) {
5627                    // A package on the system image has changed; consider this
5628                    // to be an update.
5629                    pkgSetting.lastUpdateTime = scanFileTime;
5630                }
5631            }
5632
5633            // Add the package's KeySets to the global KeySetManager
5634            KeySetManager ksm = mSettings.mKeySetManager;
5635            try {
5636                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5637                if (pkg.mKeySetMapping != null) {
5638                    for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) {
5639                        if (entry.getValue() != null) {
5640                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5641                                entry.getValue(), entry.getKey());
5642                        }
5643                    }
5644                }
5645            } catch (NullPointerException e) {
5646                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5647            } catch (IllegalArgumentException e) {
5648                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5649            }
5650
5651            int N = pkg.providers.size();
5652            StringBuilder r = null;
5653            int i;
5654            for (i=0; i<N; i++) {
5655                PackageParser.Provider p = pkg.providers.get(i);
5656                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5657                        p.info.processName, pkg.applicationInfo.uid);
5658                mProviders.addProvider(p);
5659                p.syncable = p.info.isSyncable;
5660                if (p.info.authority != null) {
5661                    String names[] = p.info.authority.split(";");
5662                    p.info.authority = null;
5663                    for (int j = 0; j < names.length; j++) {
5664                        if (j == 1 && p.syncable) {
5665                            // We only want the first authority for a provider to possibly be
5666                            // syncable, so if we already added this provider using a different
5667                            // authority clear the syncable flag. We copy the provider before
5668                            // changing it because the mProviders object contains a reference
5669                            // to a provider that we don't want to change.
5670                            // Only do this for the second authority since the resulting provider
5671                            // object can be the same for all future authorities for this provider.
5672                            p = new PackageParser.Provider(p);
5673                            p.syncable = false;
5674                        }
5675                        if (!mProvidersByAuthority.containsKey(names[j])) {
5676                            mProvidersByAuthority.put(names[j], p);
5677                            if (p.info.authority == null) {
5678                                p.info.authority = names[j];
5679                            } else {
5680                                p.info.authority = p.info.authority + ";" + names[j];
5681                            }
5682                            if (DEBUG_PACKAGE_SCANNING) {
5683                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5684                                    Log.d(TAG, "Registered content provider: " + names[j]
5685                                            + ", className = " + p.info.name + ", isSyncable = "
5686                                            + p.info.isSyncable);
5687                            }
5688                        } else {
5689                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5690                            Slog.w(TAG, "Skipping provider name " + names[j] +
5691                                    " (in package " + pkg.applicationInfo.packageName +
5692                                    "): name already used by "
5693                                    + ((other != null && other.getComponentName() != null)
5694                                            ? other.getComponentName().getPackageName() : "?"));
5695                        }
5696                    }
5697                }
5698                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5699                    if (r == null) {
5700                        r = new StringBuilder(256);
5701                    } else {
5702                        r.append(' ');
5703                    }
5704                    r.append(p.info.name);
5705                }
5706            }
5707            if (r != null) {
5708                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5709            }
5710
5711            N = pkg.services.size();
5712            r = null;
5713            for (i=0; i<N; i++) {
5714                PackageParser.Service s = pkg.services.get(i);
5715                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5716                        s.info.processName, pkg.applicationInfo.uid);
5717                mServices.addService(s);
5718                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5719                    if (r == null) {
5720                        r = new StringBuilder(256);
5721                    } else {
5722                        r.append(' ');
5723                    }
5724                    r.append(s.info.name);
5725                }
5726            }
5727            if (r != null) {
5728                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5729            }
5730
5731            N = pkg.receivers.size();
5732            r = null;
5733            for (i=0; i<N; i++) {
5734                PackageParser.Activity a = pkg.receivers.get(i);
5735                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5736                        a.info.processName, pkg.applicationInfo.uid);
5737                mReceivers.addActivity(a, "receiver");
5738                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5739                    if (r == null) {
5740                        r = new StringBuilder(256);
5741                    } else {
5742                        r.append(' ');
5743                    }
5744                    r.append(a.info.name);
5745                }
5746            }
5747            if (r != null) {
5748                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5749            }
5750
5751            N = pkg.activities.size();
5752            r = null;
5753            for (i=0; i<N; i++) {
5754                PackageParser.Activity a = pkg.activities.get(i);
5755                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5756                        a.info.processName, pkg.applicationInfo.uid);
5757                mActivities.addActivity(a, "activity");
5758                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5759                    if (r == null) {
5760                        r = new StringBuilder(256);
5761                    } else {
5762                        r.append(' ');
5763                    }
5764                    r.append(a.info.name);
5765                }
5766            }
5767            if (r != null) {
5768                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5769            }
5770
5771            N = pkg.permissionGroups.size();
5772            r = null;
5773            for (i=0; i<N; i++) {
5774                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5775                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5776                if (cur == null) {
5777                    mPermissionGroups.put(pg.info.name, pg);
5778                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5779                        if (r == null) {
5780                            r = new StringBuilder(256);
5781                        } else {
5782                            r.append(' ');
5783                        }
5784                        r.append(pg.info.name);
5785                    }
5786                } else {
5787                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5788                            + pg.info.packageName + " ignored: original from "
5789                            + cur.info.packageName);
5790                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5791                        if (r == null) {
5792                            r = new StringBuilder(256);
5793                        } else {
5794                            r.append(' ');
5795                        }
5796                        r.append("DUP:");
5797                        r.append(pg.info.name);
5798                    }
5799                }
5800            }
5801            if (r != null) {
5802                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5803            }
5804
5805            N = pkg.permissions.size();
5806            r = null;
5807            for (i=0; i<N; i++) {
5808                PackageParser.Permission p = pkg.permissions.get(i);
5809                HashMap<String, BasePermission> permissionMap =
5810                        p.tree ? mSettings.mPermissionTrees
5811                        : mSettings.mPermissions;
5812                p.group = mPermissionGroups.get(p.info.group);
5813                if (p.info.group == null || p.group != null) {
5814                    BasePermission bp = permissionMap.get(p.info.name);
5815                    if (bp == null) {
5816                        bp = new BasePermission(p.info.name, p.info.packageName,
5817                                BasePermission.TYPE_NORMAL);
5818                        permissionMap.put(p.info.name, bp);
5819                    }
5820                    if (bp.perm == null) {
5821                        if (bp.sourcePackage != null
5822                                && !bp.sourcePackage.equals(p.info.packageName)) {
5823                            // If this is a permission that was formerly defined by a non-system
5824                            // app, but is now defined by a system app (following an upgrade),
5825                            // discard the previous declaration and consider the system's to be
5826                            // canonical.
5827                            if (isSystemApp(p.owner)) {
5828                                String msg = "New decl " + p.owner + " of permission  "
5829                                        + p.info.name + " is system";
5830                                reportSettingsProblem(Log.WARN, msg);
5831                                bp.sourcePackage = null;
5832                            }
5833                        }
5834                        if (bp.sourcePackage == null
5835                                || bp.sourcePackage.equals(p.info.packageName)) {
5836                            BasePermission tree = findPermissionTreeLP(p.info.name);
5837                            if (tree == null
5838                                    || tree.sourcePackage.equals(p.info.packageName)) {
5839                                bp.packageSetting = pkgSetting;
5840                                bp.perm = p;
5841                                bp.uid = pkg.applicationInfo.uid;
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(p.info.name);
5849                                }
5850                            } else {
5851                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5852                                        + p.info.packageName + " ignored: base tree "
5853                                        + tree.name + " is from package "
5854                                        + tree.sourcePackage);
5855                            }
5856                        } else {
5857                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5858                                    + p.info.packageName + " ignored: original from "
5859                                    + bp.sourcePackage);
5860                        }
5861                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5862                        if (r == null) {
5863                            r = new StringBuilder(256);
5864                        } else {
5865                            r.append(' ');
5866                        }
5867                        r.append("DUP:");
5868                        r.append(p.info.name);
5869                    }
5870                    if (bp.perm == p) {
5871                        bp.protectionLevel = p.info.protectionLevel;
5872                    }
5873                } else {
5874                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5875                            + p.info.packageName + " ignored: no group "
5876                            + p.group);
5877                }
5878            }
5879            if (r != null) {
5880                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5881            }
5882
5883            N = pkg.instrumentation.size();
5884            r = null;
5885            for (i=0; i<N; i++) {
5886                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5887                a.info.packageName = pkg.applicationInfo.packageName;
5888                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5889                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5890                a.info.dataDir = pkg.applicationInfo.dataDir;
5891                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5892                mInstrumentation.put(a.getComponentName(), a);
5893                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5894                    if (r == null) {
5895                        r = new StringBuilder(256);
5896                    } else {
5897                        r.append(' ');
5898                    }
5899                    r.append(a.info.name);
5900                }
5901            }
5902            if (r != null) {
5903                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5904            }
5905
5906            if (pkg.protectedBroadcasts != null) {
5907                N = pkg.protectedBroadcasts.size();
5908                for (i=0; i<N; i++) {
5909                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5910                }
5911            }
5912
5913            pkgSetting.setTimeStamp(scanFileTime);
5914
5915            // Create idmap files for pairs of (packages, overlay packages).
5916            // Note: "android", ie framework-res.apk, is handled by native layers.
5917            if (pkg.mOverlayTarget != null) {
5918                // This is an overlay package.
5919                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5920                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5921                        mOverlays.put(pkg.mOverlayTarget,
5922                                new HashMap<String, PackageParser.Package>());
5923                    }
5924                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5925                    map.put(pkg.packageName, pkg);
5926                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5927                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5928                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5929                        return null;
5930                    }
5931                }
5932            } else if (mOverlays.containsKey(pkg.packageName) &&
5933                    !pkg.packageName.equals("android")) {
5934                // This is a regular package, with one or more known overlay packages.
5935                createIdmapsForPackageLI(pkg);
5936            }
5937        }
5938
5939        return pkg;
5940    }
5941
5942    public void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
5943            boolean doDexOpt, boolean forceDexOpt, boolean deferDexOpt) {
5944        String requiredInstructionSet = null;
5945        PackageSetting requirer = null;
5946        for (PackageSetting ps : packagesForUser) {
5947            if (ps.cpuAbiString != null) {
5948                final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
5949                if (requiredInstructionSet != null) {
5950                    if (!instructionSet.equals(requiredInstructionSet)) {
5951                        // We have a mismatch between instruction sets (say arm vs arm64).
5952                        //
5953                        // TODO: We should rescan all the packages in a shared UID to check if
5954                        // they do contain shared libs for other ABIs in addition to the ones we've
5955                        // already extracted. For example, the package might contain both arm64-v8a
5956                        // and armeabi-v7a shared libs, and we'd have chosen arm64-v8a on 64 bit
5957                        // devices.
5958                        String errorMessage = "Instruction set mismatch, " + requirer.pkg.packageName
5959                                + " requires " + requiredInstructionSet + " whereas " + ps.pkg.packageName
5960                                + " requires " + instructionSet;
5961                        Slog.e(TAG, errorMessage);
5962
5963                        reportSettingsProblem(Log.WARN, errorMessage);
5964                        // Give up, don't bother making any other changes to the package settings.
5965                        return;
5966                    }
5967                } else {
5968                    requiredInstructionSet = instructionSet;
5969                    requirer = ps;
5970                }
5971            }
5972        }
5973
5974        if (requiredInstructionSet != null) {
5975            for (PackageSetting ps : packagesForUser) {
5976                if (ps.cpuAbiString == null) {
5977                    ps.cpuAbiString = requirer.cpuAbiString;
5978                    if (ps.pkg != null) {
5979                        ps.pkg.applicationInfo.cpuAbi = requirer.cpuAbiString;
5980                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + ps.cpuAbiString);
5981                        if (doDexOpt) {
5982                            performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true);
5983                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
5984                        }
5985                    }
5986                }
5987            }
5988        }
5989    }
5990
5991    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
5992        synchronized (mPackages) {
5993            mResolverReplaced = true;
5994            // Set up information for custom user intent resolution activity.
5995            mResolveActivity.applicationInfo = pkg.applicationInfo;
5996            mResolveActivity.name = mCustomResolverComponentName.getClassName();
5997            mResolveActivity.packageName = pkg.applicationInfo.packageName;
5998            mResolveActivity.processName = null;
5999            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6000            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6001                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6002            mResolveActivity.theme = 0;
6003            mResolveActivity.exported = true;
6004            mResolveActivity.enabled = true;
6005            mResolveInfo.activityInfo = mResolveActivity;
6006            mResolveInfo.priority = 0;
6007            mResolveInfo.preferredOrder = 0;
6008            mResolveInfo.match = 0;
6009            mResolveComponentName = mCustomResolverComponentName;
6010            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6011                    mResolveComponentName);
6012        }
6013    }
6014
6015    private String calculateApkRoot(final String codePathString) {
6016        final File codePath = new File(codePathString);
6017        final File codeRoot;
6018        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6019            codeRoot = Environment.getRootDirectory();
6020        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6021            codeRoot = Environment.getOemDirectory();
6022        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6023            codeRoot = Environment.getVendorDirectory();
6024        } else {
6025            // Unrecognized code path; take its top real segment as the apk root:
6026            // e.g. /something/app/blah.apk => /something
6027            try {
6028                File f = codePath.getCanonicalFile();
6029                File parent = f.getParentFile();    // non-null because codePath is a file
6030                File tmp;
6031                while ((tmp = parent.getParentFile()) != null) {
6032                    f = parent;
6033                    parent = tmp;
6034                }
6035                codeRoot = f;
6036                Slog.w(TAG, "Unrecognized code path "
6037                        + codePath + " - using " + codeRoot);
6038            } catch (IOException e) {
6039                // Can't canonicalize the lib path -- shenanigans?
6040                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6041                return Environment.getRootDirectory().getPath();
6042            }
6043        }
6044        return codeRoot.getPath();
6045    }
6046
6047    // This is the initial scan-time determination of how to handle a given
6048    // package for purposes of native library location.
6049    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
6050            PackageSetting pkgSetting) {
6051        // "bundled" here means system-installed with no overriding update
6052        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
6053        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6054        final File libDir;
6055        if (bundledApk) {
6056            // If "/system/lib64/apkname" exists, assume that is the per-package
6057            // native library directory to use; otherwise use "/system/lib/apkname".
6058            String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6059            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
6060            File packLib64 = new File(lib64, apkName);
6061            libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
6062        } else {
6063            libDir = mAppLibInstallDir;
6064        }
6065        final String nativeLibraryPath = (new File(libDir, apkName)).getPath();
6066        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
6067        pkgSetting.nativeLibraryPathString = nativeLibraryPath;
6068    }
6069
6070    // Deduces the required ABI of an upgraded system app.
6071    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
6072        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6073        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6074
6075        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
6076        // or similar.
6077        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
6078        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
6079
6080        // Assume that the bundled native libraries always correspond to the
6081        // most preferred 32 or 64 bit ABI.
6082        if (lib64.exists()) {
6083            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6084            pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
6085        } else if (lib.exists()) {
6086            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6087            pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
6088        } else {
6089            // This is the case where the app has no native code.
6090            pkg.applicationInfo.cpuAbi = null;
6091            pkgSetting.cpuAbiString = null;
6092        }
6093    }
6094
6095    private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir)
6096            throws IOException {
6097        if (!nativeLibraryDir.isDirectory()) {
6098            nativeLibraryDir.delete();
6099
6100            if (!nativeLibraryDir.mkdir()) {
6101                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
6102            }
6103
6104            try {
6105                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6106            } catch (ErrnoException e) {
6107                throw new IOException("Cannot chmod native library directory "
6108                        + nativeLibraryDir.getPath(), e);
6109            }
6110        } else if (!SELinux.restorecon(nativeLibraryDir)) {
6111            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
6112        }
6113
6114        /*
6115         * If this is an internal application or our nativeLibraryPath points to
6116         * the app-lib directory, unpack the libraries if necessary.
6117         */
6118        final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
6119        try {
6120            int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS);
6121            if (abi >= 0) {
6122                int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
6123                        nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
6124                if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6125                    return copyRet;
6126                }
6127            }
6128
6129            return abi;
6130        } finally {
6131            handle.close();
6132        }
6133    }
6134
6135    private void killApplication(String pkgName, int appId, String reason) {
6136        // Request the ActivityManager to kill the process(only for existing packages)
6137        // so that we do not end up in a confused state while the user is still using the older
6138        // version of the application while the new one gets installed.
6139        IActivityManager am = ActivityManagerNative.getDefault();
6140        if (am != null) {
6141            try {
6142                am.killApplicationWithAppId(pkgName, appId, reason);
6143            } catch (RemoteException e) {
6144            }
6145        }
6146    }
6147
6148    void removePackageLI(PackageSetting ps, boolean chatty) {
6149        if (DEBUG_INSTALL) {
6150            if (chatty)
6151                Log.d(TAG, "Removing package " + ps.name);
6152        }
6153
6154        // writer
6155        synchronized (mPackages) {
6156            mPackages.remove(ps.name);
6157            if (ps.codePathString != null) {
6158                mAppDirs.remove(ps.codePathString);
6159            }
6160
6161            final PackageParser.Package pkg = ps.pkg;
6162            if (pkg != null) {
6163                cleanPackageDataStructuresLILPw(pkg, chatty);
6164            }
6165        }
6166    }
6167
6168    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6169        if (DEBUG_INSTALL) {
6170            if (chatty)
6171                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6172        }
6173
6174        // writer
6175        synchronized (mPackages) {
6176            mPackages.remove(pkg.applicationInfo.packageName);
6177            if (pkg.mPath != null) {
6178                mAppDirs.remove(pkg.mPath);
6179            }
6180            cleanPackageDataStructuresLILPw(pkg, chatty);
6181        }
6182    }
6183
6184    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6185        int N = pkg.providers.size();
6186        StringBuilder r = null;
6187        int i;
6188        for (i=0; i<N; i++) {
6189            PackageParser.Provider p = pkg.providers.get(i);
6190            mProviders.removeProvider(p);
6191            if (p.info.authority == null) {
6192
6193                /* There was another ContentProvider with this authority when
6194                 * this app was installed so this authority is null,
6195                 * Ignore it as we don't have to unregister the provider.
6196                 */
6197                continue;
6198            }
6199            String names[] = p.info.authority.split(";");
6200            for (int j = 0; j < names.length; j++) {
6201                if (mProvidersByAuthority.get(names[j]) == p) {
6202                    mProvidersByAuthority.remove(names[j]);
6203                    if (DEBUG_REMOVE) {
6204                        if (chatty)
6205                            Log.d(TAG, "Unregistered content provider: " + names[j]
6206                                    + ", className = " + p.info.name + ", isSyncable = "
6207                                    + p.info.isSyncable);
6208                    }
6209                }
6210            }
6211            if (DEBUG_REMOVE && chatty) {
6212                if (r == null) {
6213                    r = new StringBuilder(256);
6214                } else {
6215                    r.append(' ');
6216                }
6217                r.append(p.info.name);
6218            }
6219        }
6220        if (r != null) {
6221            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6222        }
6223
6224        N = pkg.services.size();
6225        r = null;
6226        for (i=0; i<N; i++) {
6227            PackageParser.Service s = pkg.services.get(i);
6228            mServices.removeService(s);
6229            if (chatty) {
6230                if (r == null) {
6231                    r = new StringBuilder(256);
6232                } else {
6233                    r.append(' ');
6234                }
6235                r.append(s.info.name);
6236            }
6237        }
6238        if (r != null) {
6239            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6240        }
6241
6242        N = pkg.receivers.size();
6243        r = null;
6244        for (i=0; i<N; i++) {
6245            PackageParser.Activity a = pkg.receivers.get(i);
6246            mReceivers.removeActivity(a, "receiver");
6247            if (DEBUG_REMOVE && chatty) {
6248                if (r == null) {
6249                    r = new StringBuilder(256);
6250                } else {
6251                    r.append(' ');
6252                }
6253                r.append(a.info.name);
6254            }
6255        }
6256        if (r != null) {
6257            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6258        }
6259
6260        N = pkg.activities.size();
6261        r = null;
6262        for (i=0; i<N; i++) {
6263            PackageParser.Activity a = pkg.activities.get(i);
6264            mActivities.removeActivity(a, "activity");
6265            if (DEBUG_REMOVE && chatty) {
6266                if (r == null) {
6267                    r = new StringBuilder(256);
6268                } else {
6269                    r.append(' ');
6270                }
6271                r.append(a.info.name);
6272            }
6273        }
6274        if (r != null) {
6275            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6276        }
6277
6278        N = pkg.permissions.size();
6279        r = null;
6280        for (i=0; i<N; i++) {
6281            PackageParser.Permission p = pkg.permissions.get(i);
6282            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6283            if (bp == null) {
6284                bp = mSettings.mPermissionTrees.get(p.info.name);
6285            }
6286            if (bp != null && bp.perm == p) {
6287                bp.perm = null;
6288                if (DEBUG_REMOVE && chatty) {
6289                    if (r == null) {
6290                        r = new StringBuilder(256);
6291                    } else {
6292                        r.append(' ');
6293                    }
6294                    r.append(p.info.name);
6295                }
6296            }
6297        }
6298        if (r != null) {
6299            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6300        }
6301
6302        N = pkg.instrumentation.size();
6303        r = null;
6304        for (i=0; i<N; i++) {
6305            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6306            mInstrumentation.remove(a.getComponentName());
6307            if (DEBUG_REMOVE && chatty) {
6308                if (r == null) {
6309                    r = new StringBuilder(256);
6310                } else {
6311                    r.append(' ');
6312                }
6313                r.append(a.info.name);
6314            }
6315        }
6316        if (r != null) {
6317            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6318        }
6319
6320        r = null;
6321        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6322            // Only system apps can hold shared libraries.
6323            if (pkg.libraryNames != null) {
6324                for (i=0; i<pkg.libraryNames.size(); i++) {
6325                    String name = pkg.libraryNames.get(i);
6326                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6327                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6328                        mSharedLibraries.remove(name);
6329                        if (DEBUG_REMOVE && chatty) {
6330                            if (r == null) {
6331                                r = new StringBuilder(256);
6332                            } else {
6333                                r.append(' ');
6334                            }
6335                            r.append(name);
6336                        }
6337                    }
6338                }
6339            }
6340        }
6341        if (r != null) {
6342            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6343        }
6344    }
6345
6346    private static final boolean isPackageFilename(String name) {
6347        return name != null && name.endsWith(".apk");
6348    }
6349
6350    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6351        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6352            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6353                return true;
6354            }
6355        }
6356        return false;
6357    }
6358
6359    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6360    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6361    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6362
6363    private void updatePermissionsLPw(String changingPkg,
6364            PackageParser.Package pkgInfo, int flags) {
6365        // Make sure there are no dangling permission trees.
6366        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6367        while (it.hasNext()) {
6368            final BasePermission bp = it.next();
6369            if (bp.packageSetting == null) {
6370                // We may not yet have parsed the package, so just see if
6371                // we still know about its settings.
6372                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6373            }
6374            if (bp.packageSetting == null) {
6375                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6376                        + " from package " + bp.sourcePackage);
6377                it.remove();
6378            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6379                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6380                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6381                            + " from package " + bp.sourcePackage);
6382                    flags |= UPDATE_PERMISSIONS_ALL;
6383                    it.remove();
6384                }
6385            }
6386        }
6387
6388        // Make sure all dynamic permissions have been assigned to a package,
6389        // and make sure there are no dangling permissions.
6390        it = mSettings.mPermissions.values().iterator();
6391        while (it.hasNext()) {
6392            final BasePermission bp = it.next();
6393            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6394                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6395                        + bp.name + " pkg=" + bp.sourcePackage
6396                        + " info=" + bp.pendingInfo);
6397                if (bp.packageSetting == null && bp.pendingInfo != null) {
6398                    final BasePermission tree = findPermissionTreeLP(bp.name);
6399                    if (tree != null && tree.perm != null) {
6400                        bp.packageSetting = tree.packageSetting;
6401                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6402                                new PermissionInfo(bp.pendingInfo));
6403                        bp.perm.info.packageName = tree.perm.info.packageName;
6404                        bp.perm.info.name = bp.name;
6405                        bp.uid = tree.uid;
6406                    }
6407                }
6408            }
6409            if (bp.packageSetting == null) {
6410                // We may not yet have parsed the package, so just see if
6411                // we still know about its settings.
6412                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6413            }
6414            if (bp.packageSetting == null) {
6415                Slog.w(TAG, "Removing dangling permission: " + bp.name
6416                        + " from package " + bp.sourcePackage);
6417                it.remove();
6418            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6419                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6420                    Slog.i(TAG, "Removing old permission: " + bp.name
6421                            + " from package " + bp.sourcePackage);
6422                    flags |= UPDATE_PERMISSIONS_ALL;
6423                    it.remove();
6424                }
6425            }
6426        }
6427
6428        // Now update the permissions for all packages, in particular
6429        // replace the granted permissions of the system packages.
6430        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6431            for (PackageParser.Package pkg : mPackages.values()) {
6432                if (pkg != pkgInfo) {
6433                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6434                }
6435            }
6436        }
6437
6438        if (pkgInfo != null) {
6439            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6440        }
6441    }
6442
6443    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6444        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6445        if (ps == null) {
6446            return;
6447        }
6448        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6449        HashSet<String> origPermissions = gp.grantedPermissions;
6450        boolean changedPermission = false;
6451
6452        if (replace) {
6453            ps.permissionsFixed = false;
6454            if (gp == ps) {
6455                origPermissions = new HashSet<String>(gp.grantedPermissions);
6456                gp.grantedPermissions.clear();
6457                gp.gids = mGlobalGids;
6458            }
6459        }
6460
6461        if (gp.gids == null) {
6462            gp.gids = mGlobalGids;
6463        }
6464
6465        final int N = pkg.requestedPermissions.size();
6466        for (int i=0; i<N; i++) {
6467            final String name = pkg.requestedPermissions.get(i);
6468            final boolean required = pkg.requestedPermissionsRequired.get(i);
6469            final BasePermission bp = mSettings.mPermissions.get(name);
6470            if (DEBUG_INSTALL) {
6471                if (gp != ps) {
6472                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6473                }
6474            }
6475
6476            if (bp == null || bp.packageSetting == null) {
6477                Slog.w(TAG, "Unknown permission " + name
6478                        + " in package " + pkg.packageName);
6479                continue;
6480            }
6481
6482            final String perm = bp.name;
6483            boolean allowed;
6484            boolean allowedSig = false;
6485            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6486            if (level == PermissionInfo.PROTECTION_NORMAL
6487                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6488                // We grant a normal or dangerous permission if any of the following
6489                // are true:
6490                // 1) The permission is required
6491                // 2) The permission is optional, but was granted in the past
6492                // 3) The permission is optional, but was requested by an
6493                //    app in /system (not /data)
6494                //
6495                // Otherwise, reject the permission.
6496                allowed = (required || origPermissions.contains(perm)
6497                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6498            } else if (bp.packageSetting == null) {
6499                // This permission is invalid; skip it.
6500                allowed = false;
6501            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6502                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6503                if (allowed) {
6504                    allowedSig = true;
6505                }
6506            } else {
6507                allowed = false;
6508            }
6509            if (DEBUG_INSTALL) {
6510                if (gp != ps) {
6511                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6512                }
6513            }
6514            if (allowed) {
6515                if (!isSystemApp(ps) && ps.permissionsFixed) {
6516                    // If this is an existing, non-system package, then
6517                    // we can't add any new permissions to it.
6518                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6519                        // Except...  if this is a permission that was added
6520                        // to the platform (note: need to only do this when
6521                        // updating the platform).
6522                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6523                    }
6524                }
6525                if (allowed) {
6526                    if (!gp.grantedPermissions.contains(perm)) {
6527                        changedPermission = true;
6528                        gp.grantedPermissions.add(perm);
6529                        gp.gids = appendInts(gp.gids, bp.gids);
6530                    } else if (!ps.haveGids) {
6531                        gp.gids = appendInts(gp.gids, bp.gids);
6532                    }
6533                } else {
6534                    Slog.w(TAG, "Not granting permission " + perm
6535                            + " to package " + pkg.packageName
6536                            + " because it was previously installed without");
6537                }
6538            } else {
6539                if (gp.grantedPermissions.remove(perm)) {
6540                    changedPermission = true;
6541                    gp.gids = removeInts(gp.gids, bp.gids);
6542                    Slog.i(TAG, "Un-granting permission " + perm
6543                            + " from package " + pkg.packageName
6544                            + " (protectionLevel=" + bp.protectionLevel
6545                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6546                            + ")");
6547                } else {
6548                    Slog.w(TAG, "Not granting permission " + perm
6549                            + " to package " + pkg.packageName
6550                            + " (protectionLevel=" + bp.protectionLevel
6551                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6552                            + ")");
6553                }
6554            }
6555        }
6556
6557        if ((changedPermission || replace) && !ps.permissionsFixed &&
6558                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6559            // This is the first that we have heard about this package, so the
6560            // permissions we have now selected are fixed until explicitly
6561            // changed.
6562            ps.permissionsFixed = true;
6563        }
6564        ps.haveGids = true;
6565    }
6566
6567    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6568        boolean allowed = false;
6569        final int NP = PackageParser.NEW_PERMISSIONS.length;
6570        for (int ip=0; ip<NP; ip++) {
6571            final PackageParser.NewPermissionInfo npi
6572                    = PackageParser.NEW_PERMISSIONS[ip];
6573            if (npi.name.equals(perm)
6574                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6575                allowed = true;
6576                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6577                        + pkg.packageName);
6578                break;
6579            }
6580        }
6581        return allowed;
6582    }
6583
6584    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6585                                          BasePermission bp, HashSet<String> origPermissions) {
6586        boolean allowed;
6587        allowed = (compareSignatures(
6588                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6589                        == PackageManager.SIGNATURE_MATCH)
6590                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6591                        == PackageManager.SIGNATURE_MATCH);
6592        if (!allowed && (bp.protectionLevel
6593                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6594            if (isSystemApp(pkg)) {
6595                // For updated system applications, a system permission
6596                // is granted only if it had been defined by the original application.
6597                if (isUpdatedSystemApp(pkg)) {
6598                    final PackageSetting sysPs = mSettings
6599                            .getDisabledSystemPkgLPr(pkg.packageName);
6600                    final GrantedPermissions origGp = sysPs.sharedUser != null
6601                            ? sysPs.sharedUser : sysPs;
6602
6603                    if (origGp.grantedPermissions.contains(perm)) {
6604                        // If the original was granted this permission, we take
6605                        // that grant decision as read and propagate it to the
6606                        // update.
6607                        allowed = true;
6608                    } else {
6609                        // The system apk may have been updated with an older
6610                        // version of the one on the data partition, but which
6611                        // granted a new system permission that it didn't have
6612                        // before.  In this case we do want to allow the app to
6613                        // now get the new permission if the ancestral apk is
6614                        // privileged to get it.
6615                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6616                            for (int j=0;
6617                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6618                                if (perm.equals(
6619                                        sysPs.pkg.requestedPermissions.get(j))) {
6620                                    allowed = true;
6621                                    break;
6622                                }
6623                            }
6624                        }
6625                    }
6626                } else {
6627                    allowed = isPrivilegedApp(pkg);
6628                }
6629            }
6630        }
6631        if (!allowed && (bp.protectionLevel
6632                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6633            // For development permissions, a development permission
6634            // is granted only if it was already granted.
6635            allowed = origPermissions.contains(perm);
6636        }
6637        return allowed;
6638    }
6639
6640    final class ActivityIntentResolver
6641            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6642        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6643                boolean defaultOnly, int userId) {
6644            if (!sUserManager.exists(userId)) return null;
6645            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6646            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6647        }
6648
6649        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6650                int userId) {
6651            if (!sUserManager.exists(userId)) return null;
6652            mFlags = flags;
6653            return super.queryIntent(intent, resolvedType,
6654                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6655        }
6656
6657        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6658                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6659            if (!sUserManager.exists(userId)) return null;
6660            if (packageActivities == null) {
6661                return null;
6662            }
6663            mFlags = flags;
6664            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6665            final int N = packageActivities.size();
6666            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6667                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6668
6669            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6670            for (int i = 0; i < N; ++i) {
6671                intentFilters = packageActivities.get(i).intents;
6672                if (intentFilters != null && intentFilters.size() > 0) {
6673                    PackageParser.ActivityIntentInfo[] array =
6674                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6675                    intentFilters.toArray(array);
6676                    listCut.add(array);
6677                }
6678            }
6679            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6680        }
6681
6682        public final void addActivity(PackageParser.Activity a, String type) {
6683            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6684            mActivities.put(a.getComponentName(), a);
6685            if (DEBUG_SHOW_INFO)
6686                Log.v(
6687                TAG, "  " + type + " " +
6688                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6689            if (DEBUG_SHOW_INFO)
6690                Log.v(TAG, "    Class=" + a.info.name);
6691            final int NI = a.intents.size();
6692            for (int j=0; j<NI; j++) {
6693                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6694                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6695                    intent.setPriority(0);
6696                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6697                            + a.className + " with priority > 0, forcing to 0");
6698                }
6699                if (DEBUG_SHOW_INFO) {
6700                    Log.v(TAG, "    IntentFilter:");
6701                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6702                }
6703                if (!intent.debugCheck()) {
6704                    Log.w(TAG, "==> For Activity " + a.info.name);
6705                }
6706                addFilter(intent);
6707            }
6708        }
6709
6710        public final void removeActivity(PackageParser.Activity a, String type) {
6711            mActivities.remove(a.getComponentName());
6712            if (DEBUG_SHOW_INFO) {
6713                Log.v(TAG, "  " + type + " "
6714                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6715                                : a.info.name) + ":");
6716                Log.v(TAG, "    Class=" + a.info.name);
6717            }
6718            final int NI = a.intents.size();
6719            for (int j=0; j<NI; j++) {
6720                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6721                if (DEBUG_SHOW_INFO) {
6722                    Log.v(TAG, "    IntentFilter:");
6723                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6724                }
6725                removeFilter(intent);
6726            }
6727        }
6728
6729        @Override
6730        protected boolean allowFilterResult(
6731                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6732            ActivityInfo filterAi = filter.activity.info;
6733            for (int i=dest.size()-1; i>=0; i--) {
6734                ActivityInfo destAi = dest.get(i).activityInfo;
6735                if (destAi.name == filterAi.name
6736                        && destAi.packageName == filterAi.packageName) {
6737                    return false;
6738                }
6739            }
6740            return true;
6741        }
6742
6743        @Override
6744        protected ActivityIntentInfo[] newArray(int size) {
6745            return new ActivityIntentInfo[size];
6746        }
6747
6748        @Override
6749        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6750            if (!sUserManager.exists(userId)) return true;
6751            PackageParser.Package p = filter.activity.owner;
6752            if (p != null) {
6753                PackageSetting ps = (PackageSetting)p.mExtras;
6754                if (ps != null) {
6755                    // System apps are never considered stopped for purposes of
6756                    // filtering, because there may be no way for the user to
6757                    // actually re-launch them.
6758                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6759                            && ps.getStopped(userId);
6760                }
6761            }
6762            return false;
6763        }
6764
6765        @Override
6766        protected boolean isPackageForFilter(String packageName,
6767                PackageParser.ActivityIntentInfo info) {
6768            return packageName.equals(info.activity.owner.packageName);
6769        }
6770
6771        @Override
6772        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6773                int match, int userId) {
6774            if (!sUserManager.exists(userId)) return null;
6775            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6776                return null;
6777            }
6778            final PackageParser.Activity activity = info.activity;
6779            if (mSafeMode && (activity.info.applicationInfo.flags
6780                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6781                return null;
6782            }
6783            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6784            if (ps == null) {
6785                return null;
6786            }
6787            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6788                    ps.readUserState(userId), userId);
6789            if (ai == null) {
6790                return null;
6791            }
6792            final ResolveInfo res = new ResolveInfo();
6793            res.activityInfo = ai;
6794            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6795                res.filter = info;
6796            }
6797            res.priority = info.getPriority();
6798            res.preferredOrder = activity.owner.mPreferredOrder;
6799            //System.out.println("Result: " + res.activityInfo.className +
6800            //                   " = " + res.priority);
6801            res.match = match;
6802            res.isDefault = info.hasDefault;
6803            res.labelRes = info.labelRes;
6804            res.nonLocalizedLabel = info.nonLocalizedLabel;
6805            res.icon = info.icon;
6806            res.system = isSystemApp(res.activityInfo.applicationInfo);
6807            return res;
6808        }
6809
6810        @Override
6811        protected void sortResults(List<ResolveInfo> results) {
6812            Collections.sort(results, mResolvePrioritySorter);
6813        }
6814
6815        @Override
6816        protected void dumpFilter(PrintWriter out, String prefix,
6817                PackageParser.ActivityIntentInfo filter) {
6818            out.print(prefix); out.print(
6819                    Integer.toHexString(System.identityHashCode(filter.activity)));
6820                    out.print(' ');
6821                    filter.activity.printComponentShortName(out);
6822                    out.print(" filter ");
6823                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6824        }
6825
6826//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6827//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6828//            final List<ResolveInfo> retList = Lists.newArrayList();
6829//            while (i.hasNext()) {
6830//                final ResolveInfo resolveInfo = i.next();
6831//                if (isEnabledLP(resolveInfo.activityInfo)) {
6832//                    retList.add(resolveInfo);
6833//                }
6834//            }
6835//            return retList;
6836//        }
6837
6838        // Keys are String (activity class name), values are Activity.
6839        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6840                = new HashMap<ComponentName, PackageParser.Activity>();
6841        private int mFlags;
6842    }
6843
6844    private final class ServiceIntentResolver
6845            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6846        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6847                boolean defaultOnly, int userId) {
6848            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6849            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6850        }
6851
6852        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6853                int userId) {
6854            if (!sUserManager.exists(userId)) return null;
6855            mFlags = flags;
6856            return super.queryIntent(intent, resolvedType,
6857                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6858        }
6859
6860        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6861                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6862            if (!sUserManager.exists(userId)) return null;
6863            if (packageServices == null) {
6864                return null;
6865            }
6866            mFlags = flags;
6867            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6868            final int N = packageServices.size();
6869            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6870                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6871
6872            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6873            for (int i = 0; i < N; ++i) {
6874                intentFilters = packageServices.get(i).intents;
6875                if (intentFilters != null && intentFilters.size() > 0) {
6876                    PackageParser.ServiceIntentInfo[] array =
6877                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6878                    intentFilters.toArray(array);
6879                    listCut.add(array);
6880                }
6881            }
6882            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6883        }
6884
6885        public final void addService(PackageParser.Service s) {
6886            mServices.put(s.getComponentName(), s);
6887            if (DEBUG_SHOW_INFO) {
6888                Log.v(TAG, "  "
6889                        + (s.info.nonLocalizedLabel != null
6890                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6891                Log.v(TAG, "    Class=" + s.info.name);
6892            }
6893            final int NI = s.intents.size();
6894            int j;
6895            for (j=0; j<NI; j++) {
6896                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6897                if (DEBUG_SHOW_INFO) {
6898                    Log.v(TAG, "    IntentFilter:");
6899                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6900                }
6901                if (!intent.debugCheck()) {
6902                    Log.w(TAG, "==> For Service " + s.info.name);
6903                }
6904                addFilter(intent);
6905            }
6906        }
6907
6908        public final void removeService(PackageParser.Service s) {
6909            mServices.remove(s.getComponentName());
6910            if (DEBUG_SHOW_INFO) {
6911                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
6912                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6913                Log.v(TAG, "    Class=" + s.info.name);
6914            }
6915            final int NI = s.intents.size();
6916            int j;
6917            for (j=0; j<NI; j++) {
6918                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6919                if (DEBUG_SHOW_INFO) {
6920                    Log.v(TAG, "    IntentFilter:");
6921                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6922                }
6923                removeFilter(intent);
6924            }
6925        }
6926
6927        @Override
6928        protected boolean allowFilterResult(
6929                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
6930            ServiceInfo filterSi = filter.service.info;
6931            for (int i=dest.size()-1; i>=0; i--) {
6932                ServiceInfo destAi = dest.get(i).serviceInfo;
6933                if (destAi.name == filterSi.name
6934                        && destAi.packageName == filterSi.packageName) {
6935                    return false;
6936                }
6937            }
6938            return true;
6939        }
6940
6941        @Override
6942        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
6943            return new PackageParser.ServiceIntentInfo[size];
6944        }
6945
6946        @Override
6947        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
6948            if (!sUserManager.exists(userId)) return true;
6949            PackageParser.Package p = filter.service.owner;
6950            if (p != null) {
6951                PackageSetting ps = (PackageSetting)p.mExtras;
6952                if (ps != null) {
6953                    // System apps are never considered stopped for purposes of
6954                    // filtering, because there may be no way for the user to
6955                    // actually re-launch them.
6956                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6957                            && ps.getStopped(userId);
6958                }
6959            }
6960            return false;
6961        }
6962
6963        @Override
6964        protected boolean isPackageForFilter(String packageName,
6965                PackageParser.ServiceIntentInfo info) {
6966            return packageName.equals(info.service.owner.packageName);
6967        }
6968
6969        @Override
6970        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
6971                int match, int userId) {
6972            if (!sUserManager.exists(userId)) return null;
6973            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
6974            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
6975                return null;
6976            }
6977            final PackageParser.Service service = info.service;
6978            if (mSafeMode && (service.info.applicationInfo.flags
6979                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6980                return null;
6981            }
6982            PackageSetting ps = (PackageSetting) service.owner.mExtras;
6983            if (ps == null) {
6984                return null;
6985            }
6986            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
6987                    ps.readUserState(userId), userId);
6988            if (si == null) {
6989                return null;
6990            }
6991            final ResolveInfo res = new ResolveInfo();
6992            res.serviceInfo = si;
6993            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6994                res.filter = filter;
6995            }
6996            res.priority = info.getPriority();
6997            res.preferredOrder = service.owner.mPreferredOrder;
6998            //System.out.println("Result: " + res.activityInfo.className +
6999            //                   " = " + res.priority);
7000            res.match = match;
7001            res.isDefault = info.hasDefault;
7002            res.labelRes = info.labelRes;
7003            res.nonLocalizedLabel = info.nonLocalizedLabel;
7004            res.icon = info.icon;
7005            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7006            return res;
7007        }
7008
7009        @Override
7010        protected void sortResults(List<ResolveInfo> results) {
7011            Collections.sort(results, mResolvePrioritySorter);
7012        }
7013
7014        @Override
7015        protected void dumpFilter(PrintWriter out, String prefix,
7016                PackageParser.ServiceIntentInfo filter) {
7017            out.print(prefix); out.print(
7018                    Integer.toHexString(System.identityHashCode(filter.service)));
7019                    out.print(' ');
7020                    filter.service.printComponentShortName(out);
7021                    out.print(" filter ");
7022                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7023        }
7024
7025//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7026//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7027//            final List<ResolveInfo> retList = Lists.newArrayList();
7028//            while (i.hasNext()) {
7029//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7030//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7031//                    retList.add(resolveInfo);
7032//                }
7033//            }
7034//            return retList;
7035//        }
7036
7037        // Keys are String (activity class name), values are Activity.
7038        private final HashMap<ComponentName, PackageParser.Service> mServices
7039                = new HashMap<ComponentName, PackageParser.Service>();
7040        private int mFlags;
7041    };
7042
7043    private final class ProviderIntentResolver
7044            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7045        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7046                boolean defaultOnly, int userId) {
7047            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7048            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7049        }
7050
7051        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7052                int userId) {
7053            if (!sUserManager.exists(userId))
7054                return null;
7055            mFlags = flags;
7056            return super.queryIntent(intent, resolvedType,
7057                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7058        }
7059
7060        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7061                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7062            if (!sUserManager.exists(userId))
7063                return null;
7064            if (packageProviders == null) {
7065                return null;
7066            }
7067            mFlags = flags;
7068            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7069            final int N = packageProviders.size();
7070            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7071                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7072
7073            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7074            for (int i = 0; i < N; ++i) {
7075                intentFilters = packageProviders.get(i).intents;
7076                if (intentFilters != null && intentFilters.size() > 0) {
7077                    PackageParser.ProviderIntentInfo[] array =
7078                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7079                    intentFilters.toArray(array);
7080                    listCut.add(array);
7081                }
7082            }
7083            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7084        }
7085
7086        public final void addProvider(PackageParser.Provider p) {
7087            if (mProviders.containsKey(p.getComponentName())) {
7088                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7089                return;
7090            }
7091
7092            mProviders.put(p.getComponentName(), p);
7093            if (DEBUG_SHOW_INFO) {
7094                Log.v(TAG, "  "
7095                        + (p.info.nonLocalizedLabel != null
7096                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7097                Log.v(TAG, "    Class=" + p.info.name);
7098            }
7099            final int NI = p.intents.size();
7100            int j;
7101            for (j = 0; j < NI; j++) {
7102                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7103                if (DEBUG_SHOW_INFO) {
7104                    Log.v(TAG, "    IntentFilter:");
7105                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7106                }
7107                if (!intent.debugCheck()) {
7108                    Log.w(TAG, "==> For Provider " + p.info.name);
7109                }
7110                addFilter(intent);
7111            }
7112        }
7113
7114        public final void removeProvider(PackageParser.Provider p) {
7115            mProviders.remove(p.getComponentName());
7116            if (DEBUG_SHOW_INFO) {
7117                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7118                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7119                Log.v(TAG, "    Class=" + p.info.name);
7120            }
7121            final int NI = p.intents.size();
7122            int j;
7123            for (j = 0; j < NI; j++) {
7124                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7125                if (DEBUG_SHOW_INFO) {
7126                    Log.v(TAG, "    IntentFilter:");
7127                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7128                }
7129                removeFilter(intent);
7130            }
7131        }
7132
7133        @Override
7134        protected boolean allowFilterResult(
7135                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7136            ProviderInfo filterPi = filter.provider.info;
7137            for (int i = dest.size() - 1; i >= 0; i--) {
7138                ProviderInfo destPi = dest.get(i).providerInfo;
7139                if (destPi.name == filterPi.name
7140                        && destPi.packageName == filterPi.packageName) {
7141                    return false;
7142                }
7143            }
7144            return true;
7145        }
7146
7147        @Override
7148        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7149            return new PackageParser.ProviderIntentInfo[size];
7150        }
7151
7152        @Override
7153        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7154            if (!sUserManager.exists(userId))
7155                return true;
7156            PackageParser.Package p = filter.provider.owner;
7157            if (p != null) {
7158                PackageSetting ps = (PackageSetting) p.mExtras;
7159                if (ps != null) {
7160                    // System apps are never considered stopped for purposes of
7161                    // filtering, because there may be no way for the user to
7162                    // actually re-launch them.
7163                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7164                            && ps.getStopped(userId);
7165                }
7166            }
7167            return false;
7168        }
7169
7170        @Override
7171        protected boolean isPackageForFilter(String packageName,
7172                PackageParser.ProviderIntentInfo info) {
7173            return packageName.equals(info.provider.owner.packageName);
7174        }
7175
7176        @Override
7177        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7178                int match, int userId) {
7179            if (!sUserManager.exists(userId))
7180                return null;
7181            final PackageParser.ProviderIntentInfo info = filter;
7182            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7183                return null;
7184            }
7185            final PackageParser.Provider provider = info.provider;
7186            if (mSafeMode && (provider.info.applicationInfo.flags
7187                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7188                return null;
7189            }
7190            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7191            if (ps == null) {
7192                return null;
7193            }
7194            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7195                    ps.readUserState(userId), userId);
7196            if (pi == null) {
7197                return null;
7198            }
7199            final ResolveInfo res = new ResolveInfo();
7200            res.providerInfo = pi;
7201            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7202                res.filter = filter;
7203            }
7204            res.priority = info.getPriority();
7205            res.preferredOrder = provider.owner.mPreferredOrder;
7206            res.match = match;
7207            res.isDefault = info.hasDefault;
7208            res.labelRes = info.labelRes;
7209            res.nonLocalizedLabel = info.nonLocalizedLabel;
7210            res.icon = info.icon;
7211            res.system = isSystemApp(res.providerInfo.applicationInfo);
7212            return res;
7213        }
7214
7215        @Override
7216        protected void sortResults(List<ResolveInfo> results) {
7217            Collections.sort(results, mResolvePrioritySorter);
7218        }
7219
7220        @Override
7221        protected void dumpFilter(PrintWriter out, String prefix,
7222                PackageParser.ProviderIntentInfo filter) {
7223            out.print(prefix);
7224            out.print(
7225                    Integer.toHexString(System.identityHashCode(filter.provider)));
7226            out.print(' ');
7227            filter.provider.printComponentShortName(out);
7228            out.print(" filter ");
7229            out.println(Integer.toHexString(System.identityHashCode(filter)));
7230        }
7231
7232        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7233                = new HashMap<ComponentName, PackageParser.Provider>();
7234        private int mFlags;
7235    };
7236
7237    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7238            new Comparator<ResolveInfo>() {
7239        public int compare(ResolveInfo r1, ResolveInfo r2) {
7240            int v1 = r1.priority;
7241            int v2 = r2.priority;
7242            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7243            if (v1 != v2) {
7244                return (v1 > v2) ? -1 : 1;
7245            }
7246            v1 = r1.preferredOrder;
7247            v2 = r2.preferredOrder;
7248            if (v1 != v2) {
7249                return (v1 > v2) ? -1 : 1;
7250            }
7251            if (r1.isDefault != r2.isDefault) {
7252                return r1.isDefault ? -1 : 1;
7253            }
7254            v1 = r1.match;
7255            v2 = r2.match;
7256            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7257            if (v1 != v2) {
7258                return (v1 > v2) ? -1 : 1;
7259            }
7260            if (r1.system != r2.system) {
7261                return r1.system ? -1 : 1;
7262            }
7263            return 0;
7264        }
7265    };
7266
7267    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7268            new Comparator<ProviderInfo>() {
7269        public int compare(ProviderInfo p1, ProviderInfo p2) {
7270            final int v1 = p1.initOrder;
7271            final int v2 = p2.initOrder;
7272            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7273        }
7274    };
7275
7276    static final void sendPackageBroadcast(String action, String pkg,
7277            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7278            int[] userIds) {
7279        IActivityManager am = ActivityManagerNative.getDefault();
7280        if (am != null) {
7281            try {
7282                if (userIds == null) {
7283                    userIds = am.getRunningUserIds();
7284                }
7285                for (int id : userIds) {
7286                    final Intent intent = new Intent(action,
7287                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7288                    if (extras != null) {
7289                        intent.putExtras(extras);
7290                    }
7291                    if (targetPkg != null) {
7292                        intent.setPackage(targetPkg);
7293                    }
7294                    // Modify the UID when posting to other users
7295                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7296                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7297                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7298                        intent.putExtra(Intent.EXTRA_UID, uid);
7299                    }
7300                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7301                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7302                    if (DEBUG_BROADCASTS) {
7303                        RuntimeException here = new RuntimeException("here");
7304                        here.fillInStackTrace();
7305                        Slog.d(TAG, "Sending to user " + id + ": "
7306                                + intent.toShortString(false, true, false, false)
7307                                + " " + intent.getExtras(), here);
7308                    }
7309                    am.broadcastIntent(null, intent, null, finishedReceiver,
7310                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7311                            finishedReceiver != null, false, id);
7312                }
7313            } catch (RemoteException ex) {
7314            }
7315        }
7316    }
7317
7318    /**
7319     * Check if the external storage media is available. This is true if there
7320     * is a mounted external storage medium or if the external storage is
7321     * emulated.
7322     */
7323    private boolean isExternalMediaAvailable() {
7324        return mMediaMounted || Environment.isExternalStorageEmulated();
7325    }
7326
7327    @Override
7328    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7329        // writer
7330        synchronized (mPackages) {
7331            if (!isExternalMediaAvailable()) {
7332                // If the external storage is no longer mounted at this point,
7333                // the caller may not have been able to delete all of this
7334                // packages files and can not delete any more.  Bail.
7335                return null;
7336            }
7337            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7338            if (lastPackage != null) {
7339                pkgs.remove(lastPackage);
7340            }
7341            if (pkgs.size() > 0) {
7342                return pkgs.get(0);
7343            }
7344        }
7345        return null;
7346    }
7347
7348    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7349        if (false) {
7350            RuntimeException here = new RuntimeException("here");
7351            here.fillInStackTrace();
7352            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7353                    + " andCode=" + andCode, here);
7354        }
7355        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7356                userId, andCode ? 1 : 0, packageName));
7357    }
7358
7359    void startCleaningPackages() {
7360        // reader
7361        synchronized (mPackages) {
7362            if (!isExternalMediaAvailable()) {
7363                return;
7364            }
7365            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7366                return;
7367            }
7368        }
7369        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7370        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7371        IActivityManager am = ActivityManagerNative.getDefault();
7372        if (am != null) {
7373            try {
7374                am.startService(null, intent, null, UserHandle.USER_OWNER);
7375            } catch (RemoteException e) {
7376            }
7377        }
7378    }
7379
7380    private final class AppDirObserver extends FileObserver {
7381        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7382            super(path, mask);
7383            mRootDir = path;
7384            mIsRom = isrom;
7385            mIsPrivileged = isPrivileged;
7386        }
7387
7388        public void onEvent(int event, String path) {
7389            String removedPackage = null;
7390            int removedAppId = -1;
7391            int[] removedUsers = null;
7392            String addedPackage = null;
7393            int addedAppId = -1;
7394            int[] addedUsers = null;
7395
7396            // TODO post a message to the handler to obtain serial ordering
7397            synchronized (mInstallLock) {
7398                String fullPathStr = null;
7399                File fullPath = null;
7400                if (path != null) {
7401                    fullPath = new File(mRootDir, path);
7402                    fullPathStr = fullPath.getPath();
7403                }
7404
7405                if (DEBUG_APP_DIR_OBSERVER)
7406                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7407
7408                if (!isPackageFilename(path)) {
7409                    if (DEBUG_APP_DIR_OBSERVER)
7410                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7411                    return;
7412                }
7413
7414                // Ignore packages that are being installed or
7415                // have just been installed.
7416                if (ignoreCodePath(fullPathStr)) {
7417                    return;
7418                }
7419                PackageParser.Package p = null;
7420                PackageSetting ps = null;
7421                // reader
7422                synchronized (mPackages) {
7423                    p = mAppDirs.get(fullPathStr);
7424                    if (p != null) {
7425                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7426                        if (ps != null) {
7427                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7428                        } else {
7429                            removedUsers = sUserManager.getUserIds();
7430                        }
7431                    }
7432                    addedUsers = sUserManager.getUserIds();
7433                }
7434                if ((event&REMOVE_EVENTS) != 0) {
7435                    if (ps != null) {
7436                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7437                        removePackageLI(ps, true);
7438                        removedPackage = ps.name;
7439                        removedAppId = ps.appId;
7440                    }
7441                }
7442
7443                if ((event&ADD_EVENTS) != 0) {
7444                    if (p == null) {
7445                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7446                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7447                        if (mIsRom) {
7448                            flags |= PackageParser.PARSE_IS_SYSTEM
7449                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7450                            if (mIsPrivileged) {
7451                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7452                            }
7453                        }
7454                        p = scanPackageLI(fullPath, flags,
7455                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7456                                System.currentTimeMillis(), UserHandle.ALL);
7457                        if (p != null) {
7458                            /*
7459                             * TODO this seems dangerous as the package may have
7460                             * changed since we last acquired the mPackages
7461                             * lock.
7462                             */
7463                            // writer
7464                            synchronized (mPackages) {
7465                                updatePermissionsLPw(p.packageName, p,
7466                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7467                            }
7468                            addedPackage = p.applicationInfo.packageName;
7469                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7470                        }
7471                    }
7472                }
7473
7474                // reader
7475                synchronized (mPackages) {
7476                    mSettings.writeLPr();
7477                }
7478            }
7479
7480            if (removedPackage != null) {
7481                Bundle extras = new Bundle(1);
7482                extras.putInt(Intent.EXTRA_UID, removedAppId);
7483                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7484                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7485                        extras, null, null, removedUsers);
7486            }
7487            if (addedPackage != null) {
7488                Bundle extras = new Bundle(1);
7489                extras.putInt(Intent.EXTRA_UID, addedAppId);
7490                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7491                        extras, null, null, addedUsers);
7492            }
7493        }
7494
7495        private final String mRootDir;
7496        private final boolean mIsRom;
7497        private final boolean mIsPrivileged;
7498    }
7499
7500    /*
7501     * The old-style observer methods all just trampoline to the newer signature with
7502     * expanded install observer API.  The older API continues to work but does not
7503     * supply the additional details of the Observer2 API.
7504     */
7505
7506    /* Called when a downloaded package installation has been confirmed by the user */
7507    public void installPackage(
7508            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
7509        installPackageEtc(packageURI, observer, null, flags, null);
7510    }
7511
7512    /* Called when a downloaded package installation has been confirmed by the user */
7513    @Override
7514    public void installPackage(
7515            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
7516            final String installerPackageName) {
7517        installPackageWithVerificationEtc(packageURI, observer, null, flags,
7518                installerPackageName, null, null, null);
7519    }
7520
7521    @Override
7522    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
7523            int flags, String installerPackageName, Uri verificationURI,
7524            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7525        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7526                VerificationParams.NO_UID, manifestDigest);
7527        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7528                installerPackageName, verificationParams, encryptionParams);
7529    }
7530
7531    @Override
7532    public void installPackageWithVerificationAndEncryption(Uri packageURI,
7533            IPackageInstallObserver observer, int flags, String installerPackageName,
7534            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7535        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7536                installerPackageName, verificationParams, encryptionParams);
7537    }
7538
7539    /*
7540     * And here are the "live" versions that take both observer arguments
7541     */
7542    public void installPackageEtc(
7543            final Uri packageURI, final IPackageInstallObserver observer,
7544            IPackageInstallObserver2 observer2, final int flags) {
7545        installPackageEtc(packageURI, observer, observer2, flags, null);
7546    }
7547
7548    public void installPackageEtc(
7549            final Uri packageURI, final IPackageInstallObserver observer,
7550            final IPackageInstallObserver2 observer2, final int flags,
7551            final String installerPackageName) {
7552        installPackageWithVerificationEtc(packageURI, observer, observer2, flags,
7553                installerPackageName, null, null, null);
7554    }
7555
7556    @Override
7557    public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer,
7558            IPackageInstallObserver2 observer2,
7559            int flags, String installerPackageName, Uri verificationURI,
7560            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7561        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7562                VerificationParams.NO_UID, manifestDigest);
7563        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags,
7564                installerPackageName, verificationParams, encryptionParams);
7565    }
7566
7567    /*
7568     * All of the installPackage...*() methods redirect to this one for the master implementation
7569     */
7570    public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI,
7571            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7572            int flags, String installerPackageName,
7573            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7574        if (observer == null && observer2 == null) {
7575            throw new IllegalArgumentException("No install observer supplied");
7576        }
7577        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7578                null);
7579
7580        final int uid = Binder.getCallingUid();
7581        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7582            try {
7583                if (observer != null) {
7584                    observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7585                }
7586                if (observer2 != null) {
7587                    observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7588                }
7589            } catch (RemoteException re) {
7590            }
7591            return;
7592        }
7593
7594        UserHandle user;
7595        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7596            user = UserHandle.ALL;
7597        } else {
7598            user = new UserHandle(UserHandle.getUserId(uid));
7599        }
7600
7601        final int filteredFlags;
7602
7603        if (uid == Process.SHELL_UID || uid == 0) {
7604            if (DEBUG_INSTALL) {
7605                Slog.v(TAG, "Install from ADB");
7606            }
7607            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7608        } else {
7609            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7610        }
7611
7612        verificationParams.setInstallerUid(uid);
7613
7614        final Message msg = mHandler.obtainMessage(INIT_COPY);
7615        msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags,
7616                installerPackageName, verificationParams, encryptionParams, user);
7617        mHandler.sendMessage(msg);
7618    }
7619
7620    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7621        Bundle extras = new Bundle(1);
7622        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7623
7624        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7625                packageName, extras, null, null, new int[] {userId});
7626        try {
7627            IActivityManager am = ActivityManagerNative.getDefault();
7628            final boolean isSystem =
7629                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7630            if (isSystem && am.isUserRunning(userId, false)) {
7631                // The just-installed/enabled app is bundled on the system, so presumed
7632                // to be able to run automatically without needing an explicit launch.
7633                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7634                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7635                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7636                        .setPackage(packageName);
7637                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7638                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7639            }
7640        } catch (RemoteException e) {
7641            // shouldn't happen
7642            Slog.w(TAG, "Unable to bootstrap installed package", e);
7643        }
7644    }
7645
7646    @Override
7647    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7648            int userId) {
7649        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7650        PackageSetting pkgSetting;
7651        final int uid = Binder.getCallingUid();
7652        if (UserHandle.getUserId(uid) != userId) {
7653            mContext.enforceCallingOrSelfPermission(
7654                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7655                    "setApplicationBlockedSetting for user " + userId);
7656        }
7657
7658        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7659            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7660            return false;
7661        }
7662
7663        long callingId = Binder.clearCallingIdentity();
7664        try {
7665            boolean sendAdded = false;
7666            boolean sendRemoved = false;
7667            // writer
7668            synchronized (mPackages) {
7669                pkgSetting = mSettings.mPackages.get(packageName);
7670                if (pkgSetting == null) {
7671                    return false;
7672                }
7673                if (pkgSetting.getBlocked(userId) != blocked) {
7674                    pkgSetting.setBlocked(blocked, userId);
7675                    mSettings.writePackageRestrictionsLPr(userId);
7676                    if (blocked) {
7677                        sendRemoved = true;
7678                    } else {
7679                        sendAdded = true;
7680                    }
7681                }
7682            }
7683            if (sendAdded) {
7684                sendPackageAddedForUser(packageName, pkgSetting, userId);
7685                return true;
7686            }
7687            if (sendRemoved) {
7688                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7689                        "blocking pkg");
7690                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7691            }
7692        } finally {
7693            Binder.restoreCallingIdentity(callingId);
7694        }
7695        return false;
7696    }
7697
7698    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7699            int userId) {
7700        final PackageRemovedInfo info = new PackageRemovedInfo();
7701        info.removedPackage = packageName;
7702        info.removedUsers = new int[] {userId};
7703        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7704        info.sendBroadcast(false, false, false);
7705    }
7706
7707    /**
7708     * Returns true if application is not found or there was an error. Otherwise it returns
7709     * the blocked state of the package for the given user.
7710     */
7711    @Override
7712    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7713        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7714        PackageSetting pkgSetting;
7715        final int uid = Binder.getCallingUid();
7716        if (UserHandle.getUserId(uid) != userId) {
7717            mContext.enforceCallingPermission(
7718                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7719                    "getApplicationBlocked for user " + userId);
7720        }
7721        long callingId = Binder.clearCallingIdentity();
7722        try {
7723            // writer
7724            synchronized (mPackages) {
7725                pkgSetting = mSettings.mPackages.get(packageName);
7726                if (pkgSetting == null) {
7727                    return true;
7728                }
7729                return pkgSetting.getBlocked(userId);
7730            }
7731        } finally {
7732            Binder.restoreCallingIdentity(callingId);
7733        }
7734    }
7735
7736    /**
7737     * @hide
7738     */
7739    @Override
7740    public int installExistingPackageAsUser(String packageName, int userId) {
7741        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7742                null);
7743        PackageSetting pkgSetting;
7744        final int uid = Binder.getCallingUid();
7745        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7746        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7747            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7748        }
7749
7750        long callingId = Binder.clearCallingIdentity();
7751        try {
7752            boolean sendAdded = false;
7753            Bundle extras = new Bundle(1);
7754
7755            // writer
7756            synchronized (mPackages) {
7757                pkgSetting = mSettings.mPackages.get(packageName);
7758                if (pkgSetting == null) {
7759                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7760                }
7761                if (!pkgSetting.getInstalled(userId)) {
7762                    pkgSetting.setInstalled(true, userId);
7763                    pkgSetting.setBlocked(false, userId);
7764                    mSettings.writePackageRestrictionsLPr(userId);
7765                    sendAdded = true;
7766                }
7767            }
7768
7769            if (sendAdded) {
7770                sendPackageAddedForUser(packageName, pkgSetting, userId);
7771            }
7772        } finally {
7773            Binder.restoreCallingIdentity(callingId);
7774        }
7775
7776        return PackageManager.INSTALL_SUCCEEDED;
7777    }
7778
7779    private boolean isUserRestricted(int userId, String restrictionKey) {
7780        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7781        if (restrictions.getBoolean(restrictionKey, false)) {
7782            Log.w(TAG, "User is restricted: " + restrictionKey);
7783            return true;
7784        }
7785        return false;
7786    }
7787
7788    @Override
7789    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7790        mContext.enforceCallingOrSelfPermission(
7791                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7792                "Only package verification agents can verify applications");
7793
7794        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7795        final PackageVerificationResponse response = new PackageVerificationResponse(
7796                verificationCode, Binder.getCallingUid());
7797        msg.arg1 = id;
7798        msg.obj = response;
7799        mHandler.sendMessage(msg);
7800    }
7801
7802    @Override
7803    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7804            long millisecondsToDelay) {
7805        mContext.enforceCallingOrSelfPermission(
7806                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7807                "Only package verification agents can extend verification timeouts");
7808
7809        final PackageVerificationState state = mPendingVerification.get(id);
7810        final PackageVerificationResponse response = new PackageVerificationResponse(
7811                verificationCodeAtTimeout, Binder.getCallingUid());
7812
7813        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7814            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7815        }
7816        if (millisecondsToDelay < 0) {
7817            millisecondsToDelay = 0;
7818        }
7819        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7820                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7821            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7822        }
7823
7824        if ((state != null) && !state.timeoutExtended()) {
7825            state.extendTimeout();
7826
7827            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7828            msg.arg1 = id;
7829            msg.obj = response;
7830            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7831        }
7832    }
7833
7834    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7835            int verificationCode, UserHandle user) {
7836        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7837        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7838        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7839        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7840        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7841
7842        mContext.sendBroadcastAsUser(intent, user,
7843                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7844    }
7845
7846    private ComponentName matchComponentForVerifier(String packageName,
7847            List<ResolveInfo> receivers) {
7848        ActivityInfo targetReceiver = null;
7849
7850        final int NR = receivers.size();
7851        for (int i = 0; i < NR; i++) {
7852            final ResolveInfo info = receivers.get(i);
7853            if (info.activityInfo == null) {
7854                continue;
7855            }
7856
7857            if (packageName.equals(info.activityInfo.packageName)) {
7858                targetReceiver = info.activityInfo;
7859                break;
7860            }
7861        }
7862
7863        if (targetReceiver == null) {
7864            return null;
7865        }
7866
7867        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7868    }
7869
7870    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7871            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7872        if (pkgInfo.verifiers.length == 0) {
7873            return null;
7874        }
7875
7876        final int N = pkgInfo.verifiers.length;
7877        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7878        for (int i = 0; i < N; i++) {
7879            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7880
7881            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7882                    receivers);
7883            if (comp == null) {
7884                continue;
7885            }
7886
7887            final int verifierUid = getUidForVerifier(verifierInfo);
7888            if (verifierUid == -1) {
7889                continue;
7890            }
7891
7892            if (DEBUG_VERIFY) {
7893                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
7894                        + " with the correct signature");
7895            }
7896            sufficientVerifiers.add(comp);
7897            verificationState.addSufficientVerifier(verifierUid);
7898        }
7899
7900        return sufficientVerifiers;
7901    }
7902
7903    private int getUidForVerifier(VerifierInfo verifierInfo) {
7904        synchronized (mPackages) {
7905            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
7906            if (pkg == null) {
7907                return -1;
7908            } else if (pkg.mSignatures.length != 1) {
7909                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7910                        + " has more than one signature; ignoring");
7911                return -1;
7912            }
7913
7914            /*
7915             * If the public key of the package's signature does not match
7916             * our expected public key, then this is a different package and
7917             * we should skip.
7918             */
7919
7920            final byte[] expectedPublicKey;
7921            try {
7922                final Signature verifierSig = pkg.mSignatures[0];
7923                final PublicKey publicKey = verifierSig.getPublicKey();
7924                expectedPublicKey = publicKey.getEncoded();
7925            } catch (CertificateException e) {
7926                return -1;
7927            }
7928
7929            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
7930
7931            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
7932                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7933                        + " does not have the expected public key; ignoring");
7934                return -1;
7935            }
7936
7937            return pkg.applicationInfo.uid;
7938        }
7939    }
7940
7941    @Override
7942    public void finishPackageInstall(int token) {
7943        enforceSystemOrRoot("Only the system is allowed to finish installs");
7944
7945        if (DEBUG_INSTALL) {
7946            Slog.v(TAG, "BM finishing package install for " + token);
7947        }
7948
7949        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7950        mHandler.sendMessage(msg);
7951    }
7952
7953    /**
7954     * Get the verification agent timeout.
7955     *
7956     * @return verification timeout in milliseconds
7957     */
7958    private long getVerificationTimeout() {
7959        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
7960                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
7961                DEFAULT_VERIFICATION_TIMEOUT);
7962    }
7963
7964    /**
7965     * Get the default verification agent response code.
7966     *
7967     * @return default verification response code
7968     */
7969    private int getDefaultVerificationResponse() {
7970        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7971                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
7972                DEFAULT_VERIFICATION_RESPONSE);
7973    }
7974
7975    /**
7976     * Check whether or not package verification has been enabled.
7977     *
7978     * @return true if verification should be performed
7979     */
7980    private boolean isVerificationEnabled(int flags) {
7981        if (!DEFAULT_VERIFY_ENABLE) {
7982            return false;
7983        }
7984
7985        // Check if installing from ADB
7986        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
7987            // Do not run verification in a test harness environment
7988            if (ActivityManager.isRunningInTestHarness()) {
7989                return false;
7990            }
7991            // Check if the developer does not want package verification for ADB installs
7992            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7993                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
7994                return false;
7995            }
7996        }
7997
7998        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7999                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8000    }
8001
8002    /**
8003     * Get the "allow unknown sources" setting.
8004     *
8005     * @return the current "allow unknown sources" setting
8006     */
8007    private int getUnknownSourcesSettings() {
8008        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8009                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8010                -1);
8011    }
8012
8013    @Override
8014    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8015        final int uid = Binder.getCallingUid();
8016        // writer
8017        synchronized (mPackages) {
8018            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8019            if (targetPackageSetting == null) {
8020                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8021            }
8022
8023            PackageSetting installerPackageSetting;
8024            if (installerPackageName != null) {
8025                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8026                if (installerPackageSetting == null) {
8027                    throw new IllegalArgumentException("Unknown installer package: "
8028                            + installerPackageName);
8029                }
8030            } else {
8031                installerPackageSetting = null;
8032            }
8033
8034            Signature[] callerSignature;
8035            Object obj = mSettings.getUserIdLPr(uid);
8036            if (obj != null) {
8037                if (obj instanceof SharedUserSetting) {
8038                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8039                } else if (obj instanceof PackageSetting) {
8040                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8041                } else {
8042                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8043                }
8044            } else {
8045                throw new SecurityException("Unknown calling uid " + uid);
8046            }
8047
8048            // Verify: can't set installerPackageName to a package that is
8049            // not signed with the same cert as the caller.
8050            if (installerPackageSetting != null) {
8051                if (compareSignatures(callerSignature,
8052                        installerPackageSetting.signatures.mSignatures)
8053                        != PackageManager.SIGNATURE_MATCH) {
8054                    throw new SecurityException(
8055                            "Caller does not have same cert as new installer package "
8056                            + installerPackageName);
8057                }
8058            }
8059
8060            // Verify: if target already has an installer package, it must
8061            // be signed with the same cert as the caller.
8062            if (targetPackageSetting.installerPackageName != null) {
8063                PackageSetting setting = mSettings.mPackages.get(
8064                        targetPackageSetting.installerPackageName);
8065                // If the currently set package isn't valid, then it's always
8066                // okay to change it.
8067                if (setting != null) {
8068                    if (compareSignatures(callerSignature,
8069                            setting.signatures.mSignatures)
8070                            != PackageManager.SIGNATURE_MATCH) {
8071                        throw new SecurityException(
8072                                "Caller does not have same cert as old installer package "
8073                                + targetPackageSetting.installerPackageName);
8074                    }
8075                }
8076            }
8077
8078            // Okay!
8079            targetPackageSetting.installerPackageName = installerPackageName;
8080            scheduleWriteSettingsLocked();
8081        }
8082    }
8083
8084    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8085        // Queue up an async operation since the package installation may take a little while.
8086        mHandler.post(new Runnable() {
8087            public void run() {
8088                mHandler.removeCallbacks(this);
8089                 // Result object to be returned
8090                PackageInstalledInfo res = new PackageInstalledInfo();
8091                res.returnCode = currentStatus;
8092                res.uid = -1;
8093                res.pkg = null;
8094                res.removedInfo = new PackageRemovedInfo();
8095                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8096                    args.doPreInstall(res.returnCode);
8097                    synchronized (mInstallLock) {
8098                        installPackageLI(args, true, res);
8099                    }
8100                    args.doPostInstall(res.returnCode, res.uid);
8101                }
8102
8103                // A restore should be performed at this point if (a) the install
8104                // succeeded, (b) the operation is not an update, and (c) the new
8105                // package has a backupAgent defined.
8106                final boolean update = res.removedInfo.removedPackage != null;
8107                boolean doRestore = (!update
8108                        && res.pkg != null
8109                        && res.pkg.applicationInfo.backupAgentName != null);
8110
8111                // Set up the post-install work request bookkeeping.  This will be used
8112                // and cleaned up by the post-install event handling regardless of whether
8113                // there's a restore pass performed.  Token values are >= 1.
8114                int token;
8115                if (mNextInstallToken < 0) mNextInstallToken = 1;
8116                token = mNextInstallToken++;
8117
8118                PostInstallData data = new PostInstallData(args, res);
8119                mRunningInstalls.put(token, data);
8120                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8121
8122                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8123                    // Pass responsibility to the Backup Manager.  It will perform a
8124                    // restore if appropriate, then pass responsibility back to the
8125                    // Package Manager to run the post-install observer callbacks
8126                    // and broadcasts.
8127                    IBackupManager bm = IBackupManager.Stub.asInterface(
8128                            ServiceManager.getService(Context.BACKUP_SERVICE));
8129                    if (bm != null) {
8130                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8131                                + " to BM for possible restore");
8132                        try {
8133                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8134                        } catch (RemoteException e) {
8135                            // can't happen; the backup manager is local
8136                        } catch (Exception e) {
8137                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8138                            doRestore = false;
8139                        }
8140                    } else {
8141                        Slog.e(TAG, "Backup Manager not found!");
8142                        doRestore = false;
8143                    }
8144                }
8145
8146                if (!doRestore) {
8147                    // No restore possible, or the Backup Manager was mysteriously not
8148                    // available -- just fire the post-install work request directly.
8149                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8150                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8151                    mHandler.sendMessage(msg);
8152                }
8153            }
8154        });
8155    }
8156
8157    private abstract class HandlerParams {
8158        private static final int MAX_RETRIES = 4;
8159
8160        /**
8161         * Number of times startCopy() has been attempted and had a non-fatal
8162         * error.
8163         */
8164        private int mRetries = 0;
8165
8166        /** User handle for the user requesting the information or installation. */
8167        private final UserHandle mUser;
8168
8169        HandlerParams(UserHandle user) {
8170            mUser = user;
8171        }
8172
8173        UserHandle getUser() {
8174            return mUser;
8175        }
8176
8177        final boolean startCopy() {
8178            boolean res;
8179            try {
8180                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8181
8182                if (++mRetries > MAX_RETRIES) {
8183                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8184                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8185                    handleServiceError();
8186                    return false;
8187                } else {
8188                    handleStartCopy();
8189                    res = true;
8190                }
8191            } catch (RemoteException e) {
8192                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8193                mHandler.sendEmptyMessage(MCS_RECONNECT);
8194                res = false;
8195            }
8196            handleReturnCode();
8197            return res;
8198        }
8199
8200        final void serviceError() {
8201            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8202            handleServiceError();
8203            handleReturnCode();
8204        }
8205
8206        abstract void handleStartCopy() throws RemoteException;
8207        abstract void handleServiceError();
8208        abstract void handleReturnCode();
8209    }
8210
8211    class MeasureParams extends HandlerParams {
8212        private final PackageStats mStats;
8213        private boolean mSuccess;
8214
8215        private final IPackageStatsObserver mObserver;
8216
8217        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8218            super(new UserHandle(stats.userHandle));
8219            mObserver = observer;
8220            mStats = stats;
8221        }
8222
8223        @Override
8224        public String toString() {
8225            return "MeasureParams{"
8226                + Integer.toHexString(System.identityHashCode(this))
8227                + " " + mStats.packageName + "}";
8228        }
8229
8230        @Override
8231        void handleStartCopy() throws RemoteException {
8232            synchronized (mInstallLock) {
8233                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8234            }
8235
8236            if (mSuccess) {
8237                final boolean mounted;
8238                if (Environment.isExternalStorageEmulated()) {
8239                    mounted = true;
8240                } else {
8241                    final String status = Environment.getExternalStorageState();
8242                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8243                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8244                }
8245
8246                if (mounted) {
8247                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8248
8249                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8250                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8251
8252                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8253                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8254
8255                    // Always subtract cache size, since it's a subdirectory
8256                    mStats.externalDataSize -= mStats.externalCacheSize;
8257
8258                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8259                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8260
8261                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8262                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8263                }
8264            }
8265        }
8266
8267        @Override
8268        void handleReturnCode() {
8269            if (mObserver != null) {
8270                try {
8271                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8272                } catch (RemoteException e) {
8273                    Slog.i(TAG, "Observer no longer exists.");
8274                }
8275            }
8276        }
8277
8278        @Override
8279        void handleServiceError() {
8280            Slog.e(TAG, "Could not measure application " + mStats.packageName
8281                            + " external storage");
8282        }
8283    }
8284
8285    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8286            throws RemoteException {
8287        long result = 0;
8288        for (File path : paths) {
8289            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8290        }
8291        return result;
8292    }
8293
8294    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8295        for (File path : paths) {
8296            try {
8297                mcs.clearDirectory(path.getAbsolutePath());
8298            } catch (RemoteException e) {
8299            }
8300        }
8301    }
8302
8303    class InstallParams extends HandlerParams {
8304        final IPackageInstallObserver observer;
8305        final IPackageInstallObserver2 observer2;
8306        int flags;
8307
8308        private final Uri mPackageURI;
8309        final String installerPackageName;
8310        final VerificationParams verificationParams;
8311        private InstallArgs mArgs;
8312        private int mRet;
8313        private File mTempPackage;
8314        final ContainerEncryptionParams encryptionParams;
8315
8316        InstallParams(Uri packageURI,
8317                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8318                int flags, String installerPackageName, VerificationParams verificationParams,
8319                ContainerEncryptionParams encryptionParams, UserHandle user) {
8320            super(user);
8321            this.mPackageURI = packageURI;
8322            this.flags = flags;
8323            this.observer = observer;
8324            this.observer2 = observer2;
8325            this.installerPackageName = installerPackageName;
8326            this.verificationParams = verificationParams;
8327            this.encryptionParams = encryptionParams;
8328        }
8329
8330        @Override
8331        public String toString() {
8332            return "InstallParams{"
8333                + Integer.toHexString(System.identityHashCode(this))
8334                + " " + mPackageURI + "}";
8335        }
8336
8337        public ManifestDigest getManifestDigest() {
8338            if (verificationParams == null) {
8339                return null;
8340            }
8341            return verificationParams.getManifestDigest();
8342        }
8343
8344        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8345            String packageName = pkgLite.packageName;
8346            int installLocation = pkgLite.installLocation;
8347            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8348            // reader
8349            synchronized (mPackages) {
8350                PackageParser.Package pkg = mPackages.get(packageName);
8351                if (pkg != null) {
8352                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8353                        // Check for downgrading.
8354                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8355                            if (pkgLite.versionCode < pkg.mVersionCode) {
8356                                Slog.w(TAG, "Can't install update of " + packageName
8357                                        + " update version " + pkgLite.versionCode
8358                                        + " is older than installed version "
8359                                        + pkg.mVersionCode);
8360                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8361                            }
8362                        }
8363                        // Check for updated system application.
8364                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8365                            if (onSd) {
8366                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8367                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8368                            }
8369                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8370                        } else {
8371                            if (onSd) {
8372                                // Install flag overrides everything.
8373                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8374                            }
8375                            // If current upgrade specifies particular preference
8376                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8377                                // Application explicitly specified internal.
8378                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8379                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8380                                // App explictly prefers external. Let policy decide
8381                            } else {
8382                                // Prefer previous location
8383                                if (isExternal(pkg)) {
8384                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8385                                }
8386                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8387                            }
8388                        }
8389                    } else {
8390                        // Invalid install. Return error code
8391                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8392                    }
8393                }
8394            }
8395            // All the special cases have been taken care of.
8396            // Return result based on recommended install location.
8397            if (onSd) {
8398                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8399            }
8400            return pkgLite.recommendedInstallLocation;
8401        }
8402
8403        private long getMemoryLowThreshold() {
8404            final DeviceStorageMonitorInternal
8405                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8406            if (dsm == null) {
8407                return 0L;
8408            }
8409            return dsm.getMemoryLowThreshold();
8410        }
8411
8412        /*
8413         * Invoke remote method to get package information and install
8414         * location values. Override install location based on default
8415         * policy if needed and then create install arguments based
8416         * on the install location.
8417         */
8418        public void handleStartCopy() throws RemoteException {
8419            int ret = PackageManager.INSTALL_SUCCEEDED;
8420            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8421            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8422            PackageInfoLite pkgLite = null;
8423
8424            if (onInt && onSd) {
8425                // Check if both bits are set.
8426                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8427                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8428            } else {
8429                final long lowThreshold = getMemoryLowThreshold();
8430                if (lowThreshold == 0L) {
8431                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8432                }
8433
8434                try {
8435                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
8436                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8437
8438                    final File packageFile;
8439                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
8440                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
8441                        if (mTempPackage != null) {
8442                            ParcelFileDescriptor out;
8443                            try {
8444                                out = ParcelFileDescriptor.open(mTempPackage,
8445                                        ParcelFileDescriptor.MODE_READ_WRITE);
8446                            } catch (FileNotFoundException e) {
8447                                out = null;
8448                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
8449                            }
8450
8451                            // Make a temporary file for decryption.
8452                            ret = mContainerService
8453                                    .copyResource(mPackageURI, encryptionParams, out);
8454                            IoUtils.closeQuietly(out);
8455
8456                            packageFile = mTempPackage;
8457
8458                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
8459                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
8460                                            | FileUtils.S_IROTH,
8461                                    -1, -1);
8462                        } else {
8463                            packageFile = null;
8464                        }
8465                    } else {
8466                        packageFile = new File(mPackageURI.getPath());
8467                    }
8468
8469                    if (packageFile != null) {
8470                        // Remote call to find out default install location
8471                        final String packageFilePath = packageFile.getAbsolutePath();
8472                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
8473                                lowThreshold);
8474
8475                        /*
8476                         * If we have too little free space, try to free cache
8477                         * before giving up.
8478                         */
8479                        if (pkgLite.recommendedInstallLocation
8480                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8481                            final long size = mContainerService.calculateInstalledSize(
8482                                    packageFilePath, isForwardLocked());
8483                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8484                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
8485                                        flags, lowThreshold);
8486                            }
8487                            /*
8488                             * The cache free must have deleted the file we
8489                             * downloaded to install.
8490                             *
8491                             * TODO: fix the "freeCache" call to not delete
8492                             *       the file we care about.
8493                             */
8494                            if (pkgLite.recommendedInstallLocation
8495                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8496                                pkgLite.recommendedInstallLocation
8497                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8498                            }
8499                        }
8500                    }
8501                } finally {
8502                    mContext.revokeUriPermission(mPackageURI,
8503                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8504                }
8505            }
8506
8507            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8508                int loc = pkgLite.recommendedInstallLocation;
8509                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8510                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8511                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8512                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8513                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8514                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8515                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8516                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8517                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8518                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8519                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8520                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8521                } else {
8522                    // Override with defaults if needed.
8523                    loc = installLocationPolicy(pkgLite, flags);
8524                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8525                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8526                    } else if (!onSd && !onInt) {
8527                        // Override install location with flags
8528                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8529                            // Set the flag to install on external media.
8530                            flags |= PackageManager.INSTALL_EXTERNAL;
8531                            flags &= ~PackageManager.INSTALL_INTERNAL;
8532                        } else {
8533                            // Make sure the flag for installing on external
8534                            // media is unset
8535                            flags |= PackageManager.INSTALL_INTERNAL;
8536                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8537                        }
8538                    }
8539                }
8540            }
8541
8542            final InstallArgs args = createInstallArgs(this);
8543            mArgs = args;
8544
8545            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8546                 /*
8547                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8548                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8549                 */
8550                int userIdentifier = getUser().getIdentifier();
8551                if (userIdentifier == UserHandle.USER_ALL
8552                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8553                    userIdentifier = UserHandle.USER_OWNER;
8554                }
8555
8556                /*
8557                 * Determine if we have any installed package verifiers. If we
8558                 * do, then we'll defer to them to verify the packages.
8559                 */
8560                final int requiredUid = mRequiredVerifierPackage == null ? -1
8561                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8562                if (requiredUid != -1 && isVerificationEnabled(flags)) {
8563                    final Intent verification = new Intent(
8564                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8565                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
8566                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8567
8568                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8569                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8570                            0 /* TODO: Which userId? */);
8571
8572                    if (DEBUG_VERIFY) {
8573                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8574                                + verification.toString() + " with " + pkgLite.verifiers.length
8575                                + " optional verifiers");
8576                    }
8577
8578                    final int verificationId = mPendingVerificationToken++;
8579
8580                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8581
8582                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8583                            installerPackageName);
8584
8585                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8586
8587                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8588                            pkgLite.packageName);
8589
8590                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8591                            pkgLite.versionCode);
8592
8593                    if (verificationParams != null) {
8594                        if (verificationParams.getVerificationURI() != null) {
8595                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8596                                 verificationParams.getVerificationURI());
8597                        }
8598                        if (verificationParams.getOriginatingURI() != null) {
8599                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8600                                  verificationParams.getOriginatingURI());
8601                        }
8602                        if (verificationParams.getReferrer() != null) {
8603                            verification.putExtra(Intent.EXTRA_REFERRER,
8604                                  verificationParams.getReferrer());
8605                        }
8606                        if (verificationParams.getOriginatingUid() >= 0) {
8607                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8608                                  verificationParams.getOriginatingUid());
8609                        }
8610                        if (verificationParams.getInstallerUid() >= 0) {
8611                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8612                                  verificationParams.getInstallerUid());
8613                        }
8614                    }
8615
8616                    final PackageVerificationState verificationState = new PackageVerificationState(
8617                            requiredUid, args);
8618
8619                    mPendingVerification.append(verificationId, verificationState);
8620
8621                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8622                            receivers, verificationState);
8623
8624                    /*
8625                     * If any sufficient verifiers were listed in the package
8626                     * manifest, attempt to ask them.
8627                     */
8628                    if (sufficientVerifiers != null) {
8629                        final int N = sufficientVerifiers.size();
8630                        if (N == 0) {
8631                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8632                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8633                        } else {
8634                            for (int i = 0; i < N; i++) {
8635                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8636
8637                                final Intent sufficientIntent = new Intent(verification);
8638                                sufficientIntent.setComponent(verifierComponent);
8639
8640                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8641                            }
8642                        }
8643                    }
8644
8645                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8646                            mRequiredVerifierPackage, receivers);
8647                    if (ret == PackageManager.INSTALL_SUCCEEDED
8648                            && mRequiredVerifierPackage != null) {
8649                        /*
8650                         * Send the intent to the required verification agent,
8651                         * but only start the verification timeout after the
8652                         * target BroadcastReceivers have run.
8653                         */
8654                        verification.setComponent(requiredVerifierComponent);
8655                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8656                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8657                                new BroadcastReceiver() {
8658                                    @Override
8659                                    public void onReceive(Context context, Intent intent) {
8660                                        final Message msg = mHandler
8661                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8662                                        msg.arg1 = verificationId;
8663                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8664                                    }
8665                                }, null, 0, null, null);
8666
8667                        /*
8668                         * We don't want the copy to proceed until verification
8669                         * succeeds, so null out this field.
8670                         */
8671                        mArgs = null;
8672                    }
8673                } else {
8674                    /*
8675                     * No package verification is enabled, so immediately start
8676                     * the remote call to initiate copy using temporary file.
8677                     */
8678                    ret = args.copyApk(mContainerService, true);
8679                }
8680            }
8681
8682            mRet = ret;
8683        }
8684
8685        @Override
8686        void handleReturnCode() {
8687            // If mArgs is null, then MCS couldn't be reached. When it
8688            // reconnects, it will try again to install. At that point, this
8689            // will succeed.
8690            if (mArgs != null) {
8691                processPendingInstall(mArgs, mRet);
8692
8693                if (mTempPackage != null) {
8694                    if (!mTempPackage.delete()) {
8695                        Slog.w(TAG, "Couldn't delete temporary file: " +
8696                                mTempPackage.getAbsolutePath());
8697                    }
8698                }
8699            }
8700        }
8701
8702        @Override
8703        void handleServiceError() {
8704            mArgs = createInstallArgs(this);
8705            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8706        }
8707
8708        public boolean isForwardLocked() {
8709            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8710        }
8711
8712        public Uri getPackageUri() {
8713            if (mTempPackage != null) {
8714                return Uri.fromFile(mTempPackage);
8715            } else {
8716                return mPackageURI;
8717            }
8718        }
8719    }
8720
8721    /*
8722     * Utility class used in movePackage api.
8723     * srcArgs and targetArgs are not set for invalid flags and make
8724     * sure to do null checks when invoking methods on them.
8725     * We probably want to return ErrorPrams for both failed installs
8726     * and moves.
8727     */
8728    class MoveParams extends HandlerParams {
8729        final IPackageMoveObserver observer;
8730        final int flags;
8731        final String packageName;
8732        final InstallArgs srcArgs;
8733        final InstallArgs targetArgs;
8734        int uid;
8735        int mRet;
8736
8737        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8738                String packageName, String dataDir, String instructionSet,
8739                int uid, UserHandle user) {
8740            super(user);
8741            this.srcArgs = srcArgs;
8742            this.observer = observer;
8743            this.flags = flags;
8744            this.packageName = packageName;
8745            this.uid = uid;
8746            if (srcArgs != null) {
8747                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8748                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet);
8749            } else {
8750                targetArgs = null;
8751            }
8752        }
8753
8754        @Override
8755        public String toString() {
8756            return "MoveParams{"
8757                + Integer.toHexString(System.identityHashCode(this))
8758                + " " + packageName + "}";
8759        }
8760
8761        public void handleStartCopy() throws RemoteException {
8762            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8763            // Check for storage space on target medium
8764            if (!targetArgs.checkFreeStorage(mContainerService)) {
8765                Log.w(TAG, "Insufficient storage to install");
8766                return;
8767            }
8768
8769            mRet = srcArgs.doPreCopy();
8770            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8771                return;
8772            }
8773
8774            mRet = targetArgs.copyApk(mContainerService, false);
8775            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8776                srcArgs.doPostCopy(uid);
8777                return;
8778            }
8779
8780            mRet = srcArgs.doPostCopy(uid);
8781            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8782                return;
8783            }
8784
8785            mRet = targetArgs.doPreInstall(mRet);
8786            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8787                return;
8788            }
8789
8790            if (DEBUG_SD_INSTALL) {
8791                StringBuilder builder = new StringBuilder();
8792                if (srcArgs != null) {
8793                    builder.append("src: ");
8794                    builder.append(srcArgs.getCodePath());
8795                }
8796                if (targetArgs != null) {
8797                    builder.append(" target : ");
8798                    builder.append(targetArgs.getCodePath());
8799                }
8800                Log.i(TAG, builder.toString());
8801            }
8802        }
8803
8804        @Override
8805        void handleReturnCode() {
8806            targetArgs.doPostInstall(mRet, uid);
8807            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8808            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8809                currentStatus = PackageManager.MOVE_SUCCEEDED;
8810            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8811                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8812            }
8813            processPendingMove(this, currentStatus);
8814        }
8815
8816        @Override
8817        void handleServiceError() {
8818            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8819        }
8820    }
8821
8822    /**
8823     * Used during creation of InstallArgs
8824     *
8825     * @param flags package installation flags
8826     * @return true if should be installed on external storage
8827     */
8828    private static boolean installOnSd(int flags) {
8829        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8830            return false;
8831        }
8832        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8833            return true;
8834        }
8835        return false;
8836    }
8837
8838    /**
8839     * Used during creation of InstallArgs
8840     *
8841     * @param flags package installation flags
8842     * @return true if should be installed as forward locked
8843     */
8844    private static boolean installForwardLocked(int flags) {
8845        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8846    }
8847
8848    private InstallArgs createInstallArgs(InstallParams params) {
8849        if (installOnSd(params.flags) || params.isForwardLocked()) {
8850            return new AsecInstallArgs(params);
8851        } else {
8852            return new FileInstallArgs(params);
8853        }
8854    }
8855
8856    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
8857            String nativeLibraryPath, String instructionSet) {
8858        final boolean isInAsec;
8859        if (installOnSd(flags)) {
8860            /* Apps on SD card are always in ASEC containers. */
8861            isInAsec = true;
8862        } else if (installForwardLocked(flags)
8863                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8864            /*
8865             * Forward-locked apps are only in ASEC containers if they're the
8866             * new style
8867             */
8868            isInAsec = true;
8869        } else {
8870            isInAsec = false;
8871        }
8872
8873        if (isInAsec) {
8874            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8875                    instructionSet, installOnSd(flags), installForwardLocked(flags));
8876        } else {
8877            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8878                    instructionSet);
8879        }
8880    }
8881
8882    // Used by package mover
8883    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir,
8884            String instructionSet) {
8885        if (installOnSd(flags) || installForwardLocked(flags)) {
8886            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
8887                    + AsecInstallArgs.RES_FILE_NAME);
8888            return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags),
8889                    installForwardLocked(flags));
8890        } else {
8891            return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet);
8892        }
8893    }
8894
8895    static abstract class InstallArgs {
8896        final IPackageInstallObserver observer;
8897        final IPackageInstallObserver2 observer2;
8898        // Always refers to PackageManager flags only
8899        final int flags;
8900        final Uri packageURI;
8901        final String installerPackageName;
8902        final ManifestDigest manifestDigest;
8903        final UserHandle user;
8904        final String instructionSet;
8905
8906        InstallArgs(Uri packageURI,
8907                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8908                int flags, String installerPackageName, ManifestDigest manifestDigest,
8909                UserHandle user, String instructionSet) {
8910            this.packageURI = packageURI;
8911            this.flags = flags;
8912            this.observer = observer;
8913            this.observer2 = observer2;
8914            this.installerPackageName = installerPackageName;
8915            this.manifestDigest = manifestDigest;
8916            this.user = user;
8917            this.instructionSet = instructionSet;
8918        }
8919
8920        abstract void createCopyFile();
8921        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8922        abstract int doPreInstall(int status);
8923        abstract boolean doRename(int status, String pkgName, String oldCodePath);
8924
8925        abstract int doPostInstall(int status, int uid);
8926        abstract String getCodePath();
8927        abstract String getResourcePath();
8928        abstract String getNativeLibraryPath();
8929        // Need installer lock especially for dex file removal.
8930        abstract void cleanUpResourcesLI();
8931        abstract boolean doPostDeleteLI(boolean delete);
8932        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
8933
8934        /**
8935         * Called before the source arguments are copied. This is used mostly
8936         * for MoveParams when it needs to read the source file to put it in the
8937         * destination.
8938         */
8939        int doPreCopy() {
8940            return PackageManager.INSTALL_SUCCEEDED;
8941        }
8942
8943        /**
8944         * Called after the source arguments are copied. This is used mostly for
8945         * MoveParams when it needs to read the source file to put it in the
8946         * destination.
8947         *
8948         * @return
8949         */
8950        int doPostCopy(int uid) {
8951            return PackageManager.INSTALL_SUCCEEDED;
8952        }
8953
8954        protected boolean isFwdLocked() {
8955            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8956        }
8957
8958        UserHandle getUser() {
8959            return user;
8960        }
8961    }
8962
8963    class FileInstallArgs extends InstallArgs {
8964        File installDir;
8965        String codeFileName;
8966        String resourceFileName;
8967        String libraryPath;
8968        boolean created = false;
8969
8970        FileInstallArgs(InstallParams params) {
8971            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
8972                    params.installerPackageName, params.getManifestDigest(),
8973                    params.getUser(), null /* instruction set */);
8974        }
8975
8976        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
8977                String instructionSet) {
8978            super(null, null, null, 0, null, null, null, instructionSet);
8979            File codeFile = new File(fullCodePath);
8980            installDir = codeFile.getParentFile();
8981            codeFileName = fullCodePath;
8982            resourceFileName = fullResourcePath;
8983            libraryPath = nativeLibraryPath;
8984        }
8985
8986        FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) {
8987            super(packageURI, null, null, 0, null, null, null, instructionSet);
8988            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8989            String apkName = getNextCodePath(null, pkgName, ".apk");
8990            codeFileName = new File(installDir, apkName + ".apk").getPath();
8991            resourceFileName = getResourcePathFromCodePath();
8992            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
8993        }
8994
8995        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
8996            final long lowThreshold;
8997
8998            final DeviceStorageMonitorInternal
8999                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9000            if (dsm == null) {
9001                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9002                lowThreshold = 0L;
9003            } else {
9004                if (dsm.isMemoryLow()) {
9005                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9006                    return false;
9007                }
9008
9009                lowThreshold = dsm.getMemoryLowThreshold();
9010            }
9011
9012            try {
9013                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9014                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9015                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
9016            } finally {
9017                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9018            }
9019        }
9020
9021        String getCodePath() {
9022            return codeFileName;
9023        }
9024
9025        void createCopyFile() {
9026            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9027            codeFileName = createTempPackageFile(installDir).getPath();
9028            resourceFileName = getResourcePathFromCodePath();
9029            libraryPath = getLibraryPathFromCodePath();
9030            created = true;
9031        }
9032
9033        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9034            if (temp) {
9035                // Generate temp file name
9036                createCopyFile();
9037            }
9038            // Get a ParcelFileDescriptor to write to the output file
9039            File codeFile = new File(codeFileName);
9040            if (!created) {
9041                try {
9042                    codeFile.createNewFile();
9043                    // Set permissions
9044                    if (!setPermissions()) {
9045                        // Failed setting permissions.
9046                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9047                    }
9048                } catch (IOException e) {
9049                   Slog.w(TAG, "Failed to create file " + codeFile);
9050                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9051                }
9052            }
9053            ParcelFileDescriptor out = null;
9054            try {
9055                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
9056            } catch (FileNotFoundException e) {
9057                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
9058                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9059            }
9060            // Copy the resource now
9061            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9062            try {
9063                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9064                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9065                ret = imcs.copyResource(packageURI, null, out);
9066            } finally {
9067                IoUtils.closeQuietly(out);
9068                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9069            }
9070
9071            if (isFwdLocked()) {
9072                final File destResourceFile = new File(getResourcePath());
9073
9074                // Copy the public files
9075                try {
9076                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
9077                } catch (IOException e) {
9078                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
9079                            + " forward-locked app.");
9080                    destResourceFile.delete();
9081                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9082                }
9083            }
9084
9085            final File nativeLibraryFile = new File(getNativeLibraryPath());
9086            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
9087            if (nativeLibraryFile.exists()) {
9088                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9089                nativeLibraryFile.delete();
9090            }
9091            try {
9092                int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile);
9093                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9094                    return copyRet;
9095                }
9096            } catch (IOException e) {
9097                Slog.e(TAG, "Copying native libraries failed", e);
9098                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9099            }
9100
9101            return ret;
9102        }
9103
9104        int doPreInstall(int status) {
9105            if (status != PackageManager.INSTALL_SUCCEEDED) {
9106                cleanUp();
9107            }
9108            return status;
9109        }
9110
9111        boolean doRename(int status, final String pkgName, String oldCodePath) {
9112            if (status != PackageManager.INSTALL_SUCCEEDED) {
9113                cleanUp();
9114                return false;
9115            } else {
9116                final File oldCodeFile = new File(getCodePath());
9117                final File oldResourceFile = new File(getResourcePath());
9118                final File oldLibraryFile = new File(getNativeLibraryPath());
9119
9120                // Rename APK file based on packageName
9121                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
9122                final File newCodeFile = new File(installDir, apkName + ".apk");
9123                if (!oldCodeFile.renameTo(newCodeFile)) {
9124                    return false;
9125                }
9126                codeFileName = newCodeFile.getPath();
9127
9128                // Rename public resource file if it's forward-locked.
9129                final File newResFile = new File(getResourcePathFromCodePath());
9130                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
9131                    return false;
9132                }
9133                resourceFileName = newResFile.getPath();
9134
9135                // Rename library path
9136                final File newLibraryFile = new File(getLibraryPathFromCodePath());
9137                if (newLibraryFile.exists()) {
9138                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
9139                    newLibraryFile.delete();
9140                }
9141                if (!oldLibraryFile.renameTo(newLibraryFile)) {
9142                    Slog.e(TAG, "Cannot rename native library directory "
9143                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
9144                    return false;
9145                }
9146                libraryPath = newLibraryFile.getPath();
9147
9148                // Attempt to set permissions
9149                if (!setPermissions()) {
9150                    return false;
9151                }
9152
9153                if (!SELinux.restorecon(newCodeFile)) {
9154                    return false;
9155                }
9156
9157                return true;
9158            }
9159        }
9160
9161        int doPostInstall(int status, int uid) {
9162            if (status != PackageManager.INSTALL_SUCCEEDED) {
9163                cleanUp();
9164            }
9165            return status;
9166        }
9167
9168        String getResourcePath() {
9169            return resourceFileName;
9170        }
9171
9172        private String getResourcePathFromCodePath() {
9173            final String codePath = getCodePath();
9174            if (isFwdLocked()) {
9175                final StringBuilder sb = new StringBuilder();
9176
9177                sb.append(mAppInstallDir.getPath());
9178                sb.append('/');
9179                sb.append(getApkName(codePath));
9180                sb.append(".zip");
9181
9182                /*
9183                 * If our APK is a temporary file, mark the resource as a
9184                 * temporary file as well so it can be cleaned up after
9185                 * catastrophic failure.
9186                 */
9187                if (codePath.endsWith(".tmp")) {
9188                    sb.append(".tmp");
9189                }
9190
9191                return sb.toString();
9192            } else {
9193                return codePath;
9194            }
9195        }
9196
9197        private String getLibraryPathFromCodePath() {
9198            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
9199        }
9200
9201        @Override
9202        String getNativeLibraryPath() {
9203            if (libraryPath == null) {
9204                libraryPath = getLibraryPathFromCodePath();
9205            }
9206            return libraryPath;
9207        }
9208
9209        private boolean cleanUp() {
9210            boolean ret = true;
9211            String sourceDir = getCodePath();
9212            String publicSourceDir = getResourcePath();
9213            if (sourceDir != null) {
9214                File sourceFile = new File(sourceDir);
9215                if (!sourceFile.exists()) {
9216                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
9217                    ret = false;
9218                }
9219                // Delete application's code and resources
9220                sourceFile.delete();
9221            }
9222            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
9223                final File publicSourceFile = new File(publicSourceDir);
9224                if (!publicSourceFile.exists()) {
9225                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
9226                }
9227                if (publicSourceFile.exists()) {
9228                    publicSourceFile.delete();
9229                }
9230            }
9231
9232            if (libraryPath != null) {
9233                File nativeLibraryFile = new File(libraryPath);
9234                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9235                if (!nativeLibraryFile.delete()) {
9236                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
9237                }
9238            }
9239
9240            return ret;
9241        }
9242
9243        void cleanUpResourcesLI() {
9244            String sourceDir = getCodePath();
9245            if (cleanUp()) {
9246                if (instructionSet == null) {
9247                    throw new IllegalStateException("instructionSet == null");
9248                }
9249                int retCode = mInstaller.rmdex(sourceDir, instructionSet);
9250                if (retCode < 0) {
9251                    Slog.w(TAG, "Couldn't remove dex file for package: "
9252                            +  " at location "
9253                            + sourceDir + ", retcode=" + retCode);
9254                    // we don't consider this to be a failure of the core package deletion
9255                }
9256            }
9257        }
9258
9259        private boolean setPermissions() {
9260            // TODO Do this in a more elegant way later on. for now just a hack
9261            if (!isFwdLocked()) {
9262                final int filePermissions =
9263                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
9264                    |FileUtils.S_IROTH;
9265                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
9266                if (retCode != 0) {
9267                    Slog.e(TAG, "Couldn't set new package file permissions for " +
9268                            getCodePath()
9269                            + ". The return code was: " + retCode);
9270                    // TODO Define new internal error
9271                    return false;
9272                }
9273                return true;
9274            }
9275            return true;
9276        }
9277
9278        boolean doPostDeleteLI(boolean delete) {
9279            // XXX err, shouldn't we respect the delete flag?
9280            cleanUpResourcesLI();
9281            return true;
9282        }
9283    }
9284
9285    private boolean isAsecExternal(String cid) {
9286        final String asecPath = PackageHelper.getSdFilesystem(cid);
9287        return !asecPath.startsWith(mAsecInternalPath);
9288    }
9289
9290    /**
9291     * Extract the MountService "container ID" from the full code path of an
9292     * .apk.
9293     */
9294    static String cidFromCodePath(String fullCodePath) {
9295        int eidx = fullCodePath.lastIndexOf("/");
9296        String subStr1 = fullCodePath.substring(0, eidx);
9297        int sidx = subStr1.lastIndexOf("/");
9298        return subStr1.substring(sidx+1, eidx);
9299    }
9300
9301    class AsecInstallArgs extends InstallArgs {
9302        static final String RES_FILE_NAME = "pkg.apk";
9303        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9304
9305        String cid;
9306        String packagePath;
9307        String resourcePath;
9308        String libraryPath;
9309
9310        AsecInstallArgs(InstallParams params) {
9311            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9312                    params.installerPackageName, params.getManifestDigest(),
9313                    params.getUser(), null /* instruction set */);
9314        }
9315
9316        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9317                String instructionSet, boolean isExternal, boolean isForwardLocked) {
9318            super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9319                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9320                    null, null, null, instructionSet);
9321            // Extract cid from fullCodePath
9322            int eidx = fullCodePath.lastIndexOf("/");
9323            String subStr1 = fullCodePath.substring(0, eidx);
9324            int sidx = subStr1.lastIndexOf("/");
9325            cid = subStr1.substring(sidx+1, eidx);
9326            setCachePath(subStr1);
9327        }
9328
9329        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
9330            super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
9331                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9332                    null, null, null, instructionSet);
9333            this.cid = cid;
9334            setCachePath(PackageHelper.getSdDir(cid));
9335        }
9336
9337        AsecInstallArgs(Uri packageURI, String cid, String instructionSet,
9338                boolean isExternal, boolean isForwardLocked) {
9339            super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9340                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9341                    null, null, null, instructionSet);
9342            this.cid = cid;
9343        }
9344
9345        void createCopyFile() {
9346            cid = getTempContainerId();
9347        }
9348
9349        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9350            try {
9351                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9352                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9353                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
9354            } finally {
9355                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9356            }
9357        }
9358
9359        private final boolean isExternal() {
9360            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9361        }
9362
9363        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9364            if (temp) {
9365                createCopyFile();
9366            } else {
9367                /*
9368                 * Pre-emptively destroy the container since it's destroyed if
9369                 * copying fails due to it existing anyway.
9370                 */
9371                PackageHelper.destroySdDir(cid);
9372            }
9373
9374            final String newCachePath;
9375            try {
9376                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9377                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9378                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
9379                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
9380            } finally {
9381                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9382            }
9383
9384            if (newCachePath != null) {
9385                setCachePath(newCachePath);
9386                return PackageManager.INSTALL_SUCCEEDED;
9387            } else {
9388                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9389            }
9390        }
9391
9392        @Override
9393        String getCodePath() {
9394            return packagePath;
9395        }
9396
9397        @Override
9398        String getResourcePath() {
9399            return resourcePath;
9400        }
9401
9402        @Override
9403        String getNativeLibraryPath() {
9404            return libraryPath;
9405        }
9406
9407        int doPreInstall(int status) {
9408            if (status != PackageManager.INSTALL_SUCCEEDED) {
9409                // Destroy container
9410                PackageHelper.destroySdDir(cid);
9411            } else {
9412                boolean mounted = PackageHelper.isContainerMounted(cid);
9413                if (!mounted) {
9414                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9415                            Process.SYSTEM_UID);
9416                    if (newCachePath != null) {
9417                        setCachePath(newCachePath);
9418                    } else {
9419                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9420                    }
9421                }
9422            }
9423            return status;
9424        }
9425
9426        boolean doRename(int status, final String pkgName,
9427                String oldCodePath) {
9428            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
9429            String newCachePath = null;
9430            if (PackageHelper.isContainerMounted(cid)) {
9431                // Unmount the container
9432                if (!PackageHelper.unMountSdDir(cid)) {
9433                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9434                    return false;
9435                }
9436            }
9437            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9438                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9439                        " which might be stale. Will try to clean up.");
9440                // Clean up the stale container and proceed to recreate.
9441                if (!PackageHelper.destroySdDir(newCacheId)) {
9442                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9443                    return false;
9444                }
9445                // Successfully cleaned up stale container. Try to rename again.
9446                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9447                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9448                            + " inspite of cleaning it up.");
9449                    return false;
9450                }
9451            }
9452            if (!PackageHelper.isContainerMounted(newCacheId)) {
9453                Slog.w(TAG, "Mounting container " + newCacheId);
9454                newCachePath = PackageHelper.mountSdDir(newCacheId,
9455                        getEncryptKey(), Process.SYSTEM_UID);
9456            } else {
9457                newCachePath = PackageHelper.getSdDir(newCacheId);
9458            }
9459            if (newCachePath == null) {
9460                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9461                return false;
9462            }
9463            Log.i(TAG, "Succesfully renamed " + cid +
9464                    " to " + newCacheId +
9465                    " at new path: " + newCachePath);
9466            cid = newCacheId;
9467            setCachePath(newCachePath);
9468            return true;
9469        }
9470
9471        private void setCachePath(String newCachePath) {
9472            File cachePath = new File(newCachePath);
9473            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
9474            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9475
9476            if (isFwdLocked()) {
9477                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9478            } else {
9479                resourcePath = packagePath;
9480            }
9481        }
9482
9483        int doPostInstall(int status, int uid) {
9484            if (status != PackageManager.INSTALL_SUCCEEDED) {
9485                cleanUp();
9486            } else {
9487                final int groupOwner;
9488                final String protectedFile;
9489                if (isFwdLocked()) {
9490                    groupOwner = UserHandle.getSharedAppGid(uid);
9491                    protectedFile = RES_FILE_NAME;
9492                } else {
9493                    groupOwner = -1;
9494                    protectedFile = null;
9495                }
9496
9497                if (uid < Process.FIRST_APPLICATION_UID
9498                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9499                    Slog.e(TAG, "Failed to finalize " + cid);
9500                    PackageHelper.destroySdDir(cid);
9501                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9502                }
9503
9504                boolean mounted = PackageHelper.isContainerMounted(cid);
9505                if (!mounted) {
9506                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9507                }
9508            }
9509            return status;
9510        }
9511
9512        private void cleanUp() {
9513            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9514
9515            // Destroy secure container
9516            PackageHelper.destroySdDir(cid);
9517        }
9518
9519        void cleanUpResourcesLI() {
9520            String sourceFile = getCodePath();
9521            // Remove dex file
9522            if (instructionSet == null) {
9523                throw new IllegalStateException("instructionSet == null");
9524            }
9525            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9526            if (retCode < 0) {
9527                Slog.w(TAG, "Couldn't remove dex file for package: "
9528                        + " at location "
9529                        + sourceFile.toString() + ", retcode=" + retCode);
9530                // we don't consider this to be a failure of the core package deletion
9531            }
9532            cleanUp();
9533        }
9534
9535        boolean matchContainer(String app) {
9536            if (cid.startsWith(app)) {
9537                return true;
9538            }
9539            return false;
9540        }
9541
9542        String getPackageName() {
9543            return getAsecPackageName(cid);
9544        }
9545
9546        boolean doPostDeleteLI(boolean delete) {
9547            boolean ret = false;
9548            boolean mounted = PackageHelper.isContainerMounted(cid);
9549            if (mounted) {
9550                // Unmount first
9551                ret = PackageHelper.unMountSdDir(cid);
9552            }
9553            if (ret && delete) {
9554                cleanUpResourcesLI();
9555            }
9556            return ret;
9557        }
9558
9559        @Override
9560        int doPreCopy() {
9561            if (isFwdLocked()) {
9562                if (!PackageHelper.fixSdPermissions(cid,
9563                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9564                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9565                }
9566            }
9567
9568            return PackageManager.INSTALL_SUCCEEDED;
9569        }
9570
9571        @Override
9572        int doPostCopy(int uid) {
9573            if (isFwdLocked()) {
9574                if (uid < Process.FIRST_APPLICATION_UID
9575                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9576                                RES_FILE_NAME)) {
9577                    Slog.e(TAG, "Failed to finalize " + cid);
9578                    PackageHelper.destroySdDir(cid);
9579                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9580                }
9581            }
9582
9583            return PackageManager.INSTALL_SUCCEEDED;
9584        }
9585    };
9586
9587    static String getAsecPackageName(String packageCid) {
9588        int idx = packageCid.lastIndexOf("-");
9589        if (idx == -1) {
9590            return packageCid;
9591        }
9592        return packageCid.substring(0, idx);
9593    }
9594
9595    // Utility method used to create code paths based on package name and available index.
9596    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9597        String idxStr = "";
9598        int idx = 1;
9599        // Fall back to default value of idx=1 if prefix is not
9600        // part of oldCodePath
9601        if (oldCodePath != null) {
9602            String subStr = oldCodePath;
9603            // Drop the suffix right away
9604            if (subStr.endsWith(suffix)) {
9605                subStr = subStr.substring(0, subStr.length() - suffix.length());
9606            }
9607            // If oldCodePath already contains prefix find out the
9608            // ending index to either increment or decrement.
9609            int sidx = subStr.lastIndexOf(prefix);
9610            if (sidx != -1) {
9611                subStr = subStr.substring(sidx + prefix.length());
9612                if (subStr != null) {
9613                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9614                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9615                    }
9616                    try {
9617                        idx = Integer.parseInt(subStr);
9618                        if (idx <= 1) {
9619                            idx++;
9620                        } else {
9621                            idx--;
9622                        }
9623                    } catch(NumberFormatException e) {
9624                    }
9625                }
9626            }
9627        }
9628        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9629        return prefix + idxStr;
9630    }
9631
9632    // Utility method used to ignore ADD/REMOVE events
9633    // by directory observer.
9634    private static boolean ignoreCodePath(String fullPathStr) {
9635        String apkName = getApkName(fullPathStr);
9636        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9637        if (idx != -1 && ((idx+1) < apkName.length())) {
9638            // Make sure the package ends with a numeral
9639            String version = apkName.substring(idx+1);
9640            try {
9641                Integer.parseInt(version);
9642                return true;
9643            } catch (NumberFormatException e) {}
9644        }
9645        return false;
9646    }
9647
9648    // Utility method that returns the relative package path with respect
9649    // to the installation directory. Like say for /data/data/com.test-1.apk
9650    // string com.test-1 is returned.
9651    static String getApkName(String codePath) {
9652        if (codePath == null) {
9653            return null;
9654        }
9655        int sidx = codePath.lastIndexOf("/");
9656        int eidx = codePath.lastIndexOf(".");
9657        if (eidx == -1) {
9658            eidx = codePath.length();
9659        } else if (eidx == 0) {
9660            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
9661            return null;
9662        }
9663        return codePath.substring(sidx+1, eidx);
9664    }
9665
9666    class PackageInstalledInfo {
9667        String name;
9668        int uid;
9669        // The set of users that originally had this package installed.
9670        int[] origUsers;
9671        // The set of users that now have this package installed.
9672        int[] newUsers;
9673        PackageParser.Package pkg;
9674        int returnCode;
9675        PackageRemovedInfo removedInfo;
9676
9677        // In some error cases we want to convey more info back to the observer
9678        String origPackage;
9679        String origPermission;
9680    }
9681
9682    /*
9683     * Install a non-existing package.
9684     */
9685    private void installNewPackageLI(PackageParser.Package pkg,
9686            int parseFlags, int scanMode, UserHandle user,
9687            String installerPackageName, PackageInstalledInfo res) {
9688        // Remember this for later, in case we need to rollback this install
9689        String pkgName = pkg.packageName;
9690
9691        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9692        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9693        synchronized(mPackages) {
9694            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9695                // A package with the same name is already installed, though
9696                // it has been renamed to an older name.  The package we
9697                // are trying to install should be installed as an update to
9698                // the existing one, but that has not been requested, so bail.
9699                Slog.w(TAG, "Attempt to re-install " + pkgName
9700                        + " without first uninstalling package running as "
9701                        + mSettings.mRenamedPackages.get(pkgName));
9702                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9703                return;
9704            }
9705            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
9706                // Don't allow installation over an existing package with the same name.
9707                Slog.w(TAG, "Attempt to re-install " + pkgName
9708                        + " without first uninstalling.");
9709                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9710                return;
9711            }
9712        }
9713        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9714        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9715                System.currentTimeMillis(), user);
9716        if (newPackage == null) {
9717            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9718            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9719                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9720            }
9721        } else {
9722            updateSettingsLI(newPackage,
9723                    installerPackageName,
9724                    null, null,
9725                    res);
9726            // delete the partially installed application. the data directory will have to be
9727            // restored if it was already existing
9728            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9729                // remove package from internal structures.  Note that we want deletePackageX to
9730                // delete the package data and cache directories that it created in
9731                // scanPackageLocked, unless those directories existed before we even tried to
9732                // install.
9733                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9734                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9735                                res.removedInfo, true);
9736            }
9737        }
9738    }
9739
9740    private void replacePackageLI(PackageParser.Package pkg,
9741            int parseFlags, int scanMode, UserHandle user,
9742            String installerPackageName, PackageInstalledInfo res) {
9743
9744        PackageParser.Package oldPackage;
9745        String pkgName = pkg.packageName;
9746        int[] allUsers;
9747        boolean[] perUserInstalled;
9748
9749        // First find the old package info and check signatures
9750        synchronized(mPackages) {
9751            oldPackage = mPackages.get(pkgName);
9752            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9753            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9754                    != PackageManager.SIGNATURE_MATCH) {
9755                Slog.w(TAG, "New package has a different signature: " + pkgName);
9756                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9757                return;
9758            }
9759
9760            // In case of rollback, remember per-user/profile install state
9761            PackageSetting ps = mSettings.mPackages.get(pkgName);
9762            allUsers = sUserManager.getUserIds();
9763            perUserInstalled = new boolean[allUsers.length];
9764            for (int i = 0; i < allUsers.length; i++) {
9765                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9766            }
9767        }
9768        boolean sysPkg = (isSystemApp(oldPackage));
9769        if (sysPkg) {
9770            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9771                    user, allUsers, perUserInstalled, installerPackageName, res);
9772        } else {
9773            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9774                    user, allUsers, perUserInstalled, installerPackageName, res);
9775        }
9776    }
9777
9778    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9779            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9780            int[] allUsers, boolean[] perUserInstalled,
9781            String installerPackageName, PackageInstalledInfo res) {
9782        PackageParser.Package newPackage = null;
9783        String pkgName = deletedPackage.packageName;
9784        boolean deletedPkg = true;
9785        boolean updatedSettings = false;
9786
9787        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9788                + deletedPackage);
9789        long origUpdateTime;
9790        if (pkg.mExtras != null) {
9791            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9792        } else {
9793            origUpdateTime = 0;
9794        }
9795
9796        // First delete the existing package while retaining the data directory
9797        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9798                res.removedInfo, true)) {
9799            // If the existing package wasn't successfully deleted
9800            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9801            deletedPkg = false;
9802        } else {
9803            // Successfully deleted the old package. Now proceed with re-installation
9804            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9805            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9806                    System.currentTimeMillis(), user);
9807            if (newPackage == null) {
9808                Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9809                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9810                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9811                }
9812            } else {
9813                updateSettingsLI(newPackage,
9814                        installerPackageName,
9815                        allUsers, perUserInstalled,
9816                        res);
9817                updatedSettings = true;
9818            }
9819        }
9820
9821        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9822            // remove package from internal structures.  Note that we want deletePackageX to
9823            // delete the package data and cache directories that it created in
9824            // scanPackageLocked, unless those directories existed before we even tried to
9825            // install.
9826            if(updatedSettings) {
9827                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9828                deletePackageLI(
9829                        pkgName, null, true, allUsers, perUserInstalled,
9830                        PackageManager.DELETE_KEEP_DATA,
9831                                res.removedInfo, true);
9832            }
9833            // Since we failed to install the new package we need to restore the old
9834            // package that we deleted.
9835            if(deletedPkg) {
9836                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9837                File restoreFile = new File(deletedPackage.mPath);
9838                // Parse old package
9839                boolean oldOnSd = isExternal(deletedPackage);
9840                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9841                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9842                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9843                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9844                        | SCAN_UPDATE_TIME;
9845                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9846                        origUpdateTime, null) == null) {
9847                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9848                    return;
9849                }
9850                // Restore of old package succeeded. Update permissions.
9851                // writer
9852                synchronized (mPackages) {
9853                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9854                            UPDATE_PERMISSIONS_ALL);
9855                    // can downgrade to reader
9856                    mSettings.writeLPr();
9857                }
9858                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9859            }
9860        }
9861    }
9862
9863    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9864            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9865            int[] allUsers, boolean[] perUserInstalled,
9866            String installerPackageName, PackageInstalledInfo res) {
9867        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9868                + ", old=" + deletedPackage);
9869        PackageParser.Package newPackage = null;
9870        boolean updatedSettings = false;
9871        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
9872                PackageParser.PARSE_IS_SYSTEM;
9873        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9874            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9875        }
9876        String packageName = deletedPackage.packageName;
9877        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9878        if (packageName == null) {
9879            Slog.w(TAG, "Attempt to delete null packageName.");
9880            return;
9881        }
9882        PackageParser.Package oldPkg;
9883        PackageSetting oldPkgSetting;
9884        // reader
9885        synchronized (mPackages) {
9886            oldPkg = mPackages.get(packageName);
9887            oldPkgSetting = mSettings.mPackages.get(packageName);
9888            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9889                    (oldPkgSetting == null)) {
9890                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
9891                return;
9892            }
9893        }
9894
9895        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9896
9897        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9898        res.removedInfo.removedPackage = packageName;
9899        // Remove existing system package
9900        removePackageLI(oldPkgSetting, true);
9901        // writer
9902        synchronized (mPackages) {
9903            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
9904                // We didn't need to disable the .apk as a current system package,
9905                // which means we are replacing another update that is already
9906                // installed.  We need to make sure to delete the older one's .apk.
9907                res.removedInfo.args = createInstallArgs(0,
9908                        deletedPackage.applicationInfo.sourceDir,
9909                        deletedPackage.applicationInfo.publicSourceDir,
9910                        deletedPackage.applicationInfo.nativeLibraryDir,
9911                        getAppInstructionSet(deletedPackage.applicationInfo));
9912            } else {
9913                res.removedInfo.args = null;
9914            }
9915        }
9916
9917        // Successfully disabled the old package. Now proceed with re-installation
9918        res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9919        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9920        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
9921        if (newPackage == null) {
9922            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9923            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9924                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9925            }
9926        } else {
9927            if (newPackage.mExtras != null) {
9928                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
9929                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
9930                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
9931
9932                // is the update attempting to change shared user? that isn't going to work...
9933                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
9934                    Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser
9935                            + " to " + newPkgSetting.sharedUser);
9936                    res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
9937                    updatedSettings = true;
9938                }
9939            }
9940
9941            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9942                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9943                updatedSettings = true;
9944            }
9945        }
9946
9947        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9948            // Re installation failed. Restore old information
9949            // Remove new pkg information
9950            if (newPackage != null) {
9951                removeInstalledPackageLI(newPackage, true);
9952            }
9953            // Add back the old system package
9954            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
9955            // Restore the old system information in Settings
9956            synchronized(mPackages) {
9957                if (updatedSettings) {
9958                    mSettings.enableSystemPackageLPw(packageName);
9959                    mSettings.setInstallerPackageName(packageName,
9960                            oldPkgSetting.installerPackageName);
9961                }
9962                mSettings.writeLPr();
9963            }
9964        }
9965    }
9966
9967    // Utility method used to move dex files during install.
9968    private int moveDexFilesLI(PackageParser.Package newPackage) {
9969        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
9970            final String instructionSet = getAppInstructionSet(newPackage.applicationInfo);
9971            int retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath,
9972                                             instructionSet);
9973            if (retCode != 0) {
9974                /*
9975                 * Programs may be lazily run through dexopt, so the
9976                 * source may not exist. However, something seems to
9977                 * have gone wrong, so note that dexopt needs to be
9978                 * run again and remove the source file. In addition,
9979                 * remove the target to make sure there isn't a stale
9980                 * file from a previous version of the package.
9981                 */
9982                newPackage.mDexOptNeeded = true;
9983                mInstaller.rmdex(newPackage.mScanPath, instructionSet);
9984                mInstaller.rmdex(newPackage.mPath, instructionSet);
9985            }
9986        }
9987        return PackageManager.INSTALL_SUCCEEDED;
9988    }
9989
9990    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
9991            int[] allUsers, boolean[] perUserInstalled,
9992            PackageInstalledInfo res) {
9993        String pkgName = newPackage.packageName;
9994        synchronized (mPackages) {
9995            //write settings. the installStatus will be incomplete at this stage.
9996            //note that the new package setting would have already been
9997            //added to mPackages. It hasn't been persisted yet.
9998            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
9999            mSettings.writeLPr();
10000        }
10001
10002        if ((res.returnCode = moveDexFilesLI(newPackage))
10003                != PackageManager.INSTALL_SUCCEEDED) {
10004            // Discontinue if moving dex files failed.
10005            return;
10006        }
10007
10008        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath);
10009
10010        synchronized (mPackages) {
10011            updatePermissionsLPw(newPackage.packageName, newPackage,
10012                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10013                            ? UPDATE_PERMISSIONS_ALL : 0));
10014            // For system-bundled packages, we assume that installing an upgraded version
10015            // of the package implies that the user actually wants to run that new code,
10016            // so we enable the package.
10017            if (isSystemApp(newPackage)) {
10018                // NB: implicit assumption that system package upgrades apply to all users
10019                if (DEBUG_INSTALL) {
10020                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10021                }
10022                PackageSetting ps = mSettings.mPackages.get(pkgName);
10023                if (ps != null) {
10024                    if (res.origUsers != null) {
10025                        for (int userHandle : res.origUsers) {
10026                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10027                                    userHandle, installerPackageName);
10028                        }
10029                    }
10030                    // Also convey the prior install/uninstall state
10031                    if (allUsers != null && perUserInstalled != null) {
10032                        for (int i = 0; i < allUsers.length; i++) {
10033                            if (DEBUG_INSTALL) {
10034                                Slog.d(TAG, "    user " + allUsers[i]
10035                                        + " => " + perUserInstalled[i]);
10036                            }
10037                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10038                        }
10039                        // these install state changes will be persisted in the
10040                        // upcoming call to mSettings.writeLPr().
10041                    }
10042                }
10043            }
10044            res.name = pkgName;
10045            res.uid = newPackage.applicationInfo.uid;
10046            res.pkg = newPackage;
10047            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10048            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10049            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10050            //to update install status
10051            mSettings.writeLPr();
10052        }
10053    }
10054
10055    private void installPackageLI(InstallArgs args,
10056            boolean newInstall, PackageInstalledInfo res) {
10057        int pFlags = args.flags;
10058        String installerPackageName = args.installerPackageName;
10059        File tmpPackageFile = new File(args.getCodePath());
10060        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10061        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10062        boolean replace = false;
10063        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10064                | (newInstall ? SCAN_NEW_INSTALL : 0);
10065        // Result object to be returned
10066        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10067
10068        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10069        // Retrieve PackageSettings and parse package
10070        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10071                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10072                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10073        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
10074        pp.setSeparateProcesses(mSeparateProcesses);
10075        final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
10076                null, mMetrics, parseFlags);
10077        if (pkg == null) {
10078            res.returnCode = pp.getParseError();
10079            return;
10080        }
10081        String pkgName = res.name = pkg.packageName;
10082        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10083            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10084                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
10085                return;
10086            }
10087        }
10088        if (!pp.collectCertificates(pkg, parseFlags)) {
10089            res.returnCode = pp.getParseError();
10090            return;
10091        }
10092
10093        /* If the installer passed in a manifest digest, compare it now. */
10094        if (args.manifestDigest != null) {
10095            if (DEBUG_INSTALL) {
10096                final String parsedManifest = pkg.manifestDigest == null ? "null"
10097                        : pkg.manifestDigest.toString();
10098                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10099                        + parsedManifest);
10100            }
10101
10102            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10103                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
10104                return;
10105            }
10106        } else if (DEBUG_INSTALL) {
10107            final String parsedManifest = pkg.manifestDigest == null
10108                    ? "null" : pkg.manifestDigest.toString();
10109            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10110        }
10111
10112        // Get rid of all references to package scan path via parser.
10113        pp = null;
10114        String oldCodePath = null;
10115        boolean systemApp = false;
10116        synchronized (mPackages) {
10117            // Check whether the newly-scanned package wants to define an already-defined perm
10118            int N = pkg.permissions.size();
10119            for (int i = 0; i < N; i++) {
10120                PackageParser.Permission perm = pkg.permissions.get(i);
10121                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10122                if (bp != null) {
10123                    // If the defining package is signed with our cert, it's okay.  This
10124                    // also includes the "updating the same package" case, of course.
10125                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10126                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10127                        Slog.w(TAG, "Package " + pkg.packageName
10128                                + " attempting to redeclare permission " + perm.info.name
10129                                + " already owned by " + bp.sourcePackage);
10130                        res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
10131                        res.origPermission = perm.info.name;
10132                        res.origPackage = bp.sourcePackage;
10133                        return;
10134                    }
10135                }
10136            }
10137
10138            // Check if installing already existing package
10139            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10140                String oldName = mSettings.mRenamedPackages.get(pkgName);
10141                if (pkg.mOriginalPackages != null
10142                        && pkg.mOriginalPackages.contains(oldName)
10143                        && mPackages.containsKey(oldName)) {
10144                    // This package is derived from an original package,
10145                    // and this device has been updating from that original
10146                    // name.  We must continue using the original name, so
10147                    // rename the new package here.
10148                    pkg.setPackageName(oldName);
10149                    pkgName = pkg.packageName;
10150                    replace = true;
10151                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10152                            + oldName + " pkgName=" + pkgName);
10153                } else if (mPackages.containsKey(pkgName)) {
10154                    // This package, under its official name, already exists
10155                    // on the device; we should replace it.
10156                    replace = true;
10157                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10158                }
10159            }
10160            PackageSetting ps = mSettings.mPackages.get(pkgName);
10161            if (ps != null) {
10162                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10163                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10164                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10165                    systemApp = (ps.pkg.applicationInfo.flags &
10166                            ApplicationInfo.FLAG_SYSTEM) != 0;
10167                }
10168                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10169            }
10170        }
10171
10172        if (systemApp && onSd) {
10173            // Disable updates to system apps on sdcard
10174            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
10175            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10176            return;
10177        }
10178
10179        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
10180            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10181            return;
10182        }
10183        // Set application objects path explicitly after the rename
10184        setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
10185        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
10186        if (replace) {
10187            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10188                    installerPackageName, res);
10189        } else {
10190            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10191                    installerPackageName, res);
10192        }
10193        synchronized (mPackages) {
10194            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10195            if (ps != null) {
10196                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10197            }
10198        }
10199    }
10200
10201    private static boolean isForwardLocked(PackageParser.Package pkg) {
10202        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10203    }
10204
10205
10206    private boolean isForwardLocked(PackageSetting ps) {
10207        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10208    }
10209
10210    private static boolean isExternal(PackageParser.Package pkg) {
10211        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10212    }
10213
10214    private static boolean isExternal(PackageSetting ps) {
10215        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10216    }
10217
10218    private static boolean isSystemApp(PackageParser.Package pkg) {
10219        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10220    }
10221
10222    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10223        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10224    }
10225
10226    private static boolean isSystemApp(ApplicationInfo info) {
10227        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10228    }
10229
10230    private static boolean isSystemApp(PackageSetting ps) {
10231        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10232    }
10233
10234    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10235        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10236    }
10237
10238    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10239        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10240    }
10241
10242    private int packageFlagsToInstallFlags(PackageSetting ps) {
10243        int installFlags = 0;
10244        if (isExternal(ps)) {
10245            installFlags |= PackageManager.INSTALL_EXTERNAL;
10246        }
10247        if (isForwardLocked(ps)) {
10248            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10249        }
10250        return installFlags;
10251    }
10252
10253    private void deleteTempPackageFiles() {
10254        final FilenameFilter filter = new FilenameFilter() {
10255            public boolean accept(File dir, String name) {
10256                return name.startsWith("vmdl") && name.endsWith(".tmp");
10257            }
10258        };
10259        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
10260        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
10261    }
10262
10263    private static final void deleteTempPackageFilesInDirectory(File directory,
10264            FilenameFilter filter) {
10265        final String[] tmpFilesList = directory.list(filter);
10266        if (tmpFilesList == null) {
10267            return;
10268        }
10269        for (int i = 0; i < tmpFilesList.length; i++) {
10270            final File tmpFile = new File(directory, tmpFilesList[i]);
10271            tmpFile.delete();
10272        }
10273    }
10274
10275    private File createTempPackageFile(File installDir) {
10276        File tmpPackageFile;
10277        try {
10278            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
10279        } catch (IOException e) {
10280            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
10281            return null;
10282        }
10283        try {
10284            FileUtils.setPermissions(
10285                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
10286                    -1, -1);
10287            if (!SELinux.restorecon(tmpPackageFile)) {
10288                return null;
10289            }
10290        } catch (IOException e) {
10291            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
10292            return null;
10293        }
10294        return tmpPackageFile;
10295    }
10296
10297    @Override
10298    public void deletePackageAsUser(final String packageName,
10299                                    final IPackageDeleteObserver observer,
10300                                    final int userId, final int flags) {
10301        mContext.enforceCallingOrSelfPermission(
10302                android.Manifest.permission.DELETE_PACKAGES, null);
10303        final int uid = Binder.getCallingUid();
10304        if (UserHandle.getUserId(uid) != userId) {
10305            mContext.enforceCallingPermission(
10306                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10307                    "deletePackage for user " + userId);
10308        }
10309        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10310            try {
10311                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10312            } catch (RemoteException re) {
10313            }
10314            return;
10315        }
10316
10317        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10318        // Queue up an async operation since the package deletion may take a little while.
10319        mHandler.post(new Runnable() {
10320            public void run() {
10321                mHandler.removeCallbacks(this);
10322                final int returnCode = deletePackageX(packageName, userId, flags);
10323                if (observer != null) {
10324                    try {
10325                        observer.packageDeleted(packageName, returnCode);
10326                    } catch (RemoteException e) {
10327                        Log.i(TAG, "Observer no longer exists.");
10328                    } //end catch
10329                } //end if
10330            } //end run
10331        });
10332    }
10333
10334    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10335        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10336                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10337        try {
10338            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10339                    || dpm.isDeviceOwner(packageName))) {
10340                return true;
10341            }
10342        } catch (RemoteException e) {
10343        }
10344        return false;
10345    }
10346
10347    /**
10348     *  This method is an internal method that could be get invoked either
10349     *  to delete an installed package or to clean up a failed installation.
10350     *  After deleting an installed package, a broadcast is sent to notify any
10351     *  listeners that the package has been installed. For cleaning up a failed
10352     *  installation, the broadcast is not necessary since the package's
10353     *  installation wouldn't have sent the initial broadcast either
10354     *  The key steps in deleting a package are
10355     *  deleting the package information in internal structures like mPackages,
10356     *  deleting the packages base directories through installd
10357     *  updating mSettings to reflect current status
10358     *  persisting settings for later use
10359     *  sending a broadcast if necessary
10360     */
10361    private int deletePackageX(String packageName, int userId, int flags) {
10362        final PackageRemovedInfo info = new PackageRemovedInfo();
10363        final boolean res;
10364
10365        if (isPackageDeviceAdmin(packageName, userId)) {
10366            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10367            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10368        }
10369
10370        boolean removedForAllUsers = false;
10371        boolean systemUpdate = false;
10372
10373        // for the uninstall-updates case and restricted profiles, remember the per-
10374        // userhandle installed state
10375        int[] allUsers;
10376        boolean[] perUserInstalled;
10377        synchronized (mPackages) {
10378            PackageSetting ps = mSettings.mPackages.get(packageName);
10379            allUsers = sUserManager.getUserIds();
10380            perUserInstalled = new boolean[allUsers.length];
10381            for (int i = 0; i < allUsers.length; i++) {
10382                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10383            }
10384        }
10385
10386        synchronized (mInstallLock) {
10387            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10388            res = deletePackageLI(packageName,
10389                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10390                            ? UserHandle.ALL : new UserHandle(userId),
10391                    true, allUsers, perUserInstalled,
10392                    flags | REMOVE_CHATTY, info, true);
10393            systemUpdate = info.isRemovedPackageSystemUpdate;
10394            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10395                removedForAllUsers = true;
10396            }
10397            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10398                    + " removedForAllUsers=" + removedForAllUsers);
10399        }
10400
10401        if (res) {
10402            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10403
10404            // If the removed package was a system update, the old system package
10405            // was re-enabled; we need to broadcast this information
10406            if (systemUpdate) {
10407                Bundle extras = new Bundle(1);
10408                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10409                        ? info.removedAppId : info.uid);
10410                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10411
10412                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10413                        extras, null, null, null);
10414                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10415                        extras, null, null, null);
10416                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10417                        null, packageName, null, null);
10418            }
10419        }
10420        // Force a gc here.
10421        Runtime.getRuntime().gc();
10422        // Delete the resources here after sending the broadcast to let
10423        // other processes clean up before deleting resources.
10424        if (info.args != null) {
10425            synchronized (mInstallLock) {
10426                info.args.doPostDeleteLI(true);
10427            }
10428        }
10429
10430        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10431    }
10432
10433    static class PackageRemovedInfo {
10434        String removedPackage;
10435        int uid = -1;
10436        int removedAppId = -1;
10437        int[] removedUsers = null;
10438        boolean isRemovedPackageSystemUpdate = false;
10439        // Clean up resources deleted packages.
10440        InstallArgs args = null;
10441
10442        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10443            Bundle extras = new Bundle(1);
10444            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10445            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10446            if (replacing) {
10447                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10448            }
10449            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10450            if (removedPackage != null) {
10451                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10452                        extras, null, null, removedUsers);
10453                if (fullRemove && !replacing) {
10454                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10455                            extras, null, null, removedUsers);
10456                }
10457            }
10458            if (removedAppId >= 0) {
10459                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10460                        removedUsers);
10461            }
10462        }
10463    }
10464
10465    /*
10466     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10467     * flag is not set, the data directory is removed as well.
10468     * make sure this flag is set for partially installed apps. If not its meaningless to
10469     * delete a partially installed application.
10470     */
10471    private void removePackageDataLI(PackageSetting ps,
10472            int[] allUserHandles, boolean[] perUserInstalled,
10473            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10474        String packageName = ps.name;
10475        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10476        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10477        // Retrieve object to delete permissions for shared user later on
10478        final PackageSetting deletedPs;
10479        // reader
10480        synchronized (mPackages) {
10481            deletedPs = mSettings.mPackages.get(packageName);
10482            if (outInfo != null) {
10483                outInfo.removedPackage = packageName;
10484                outInfo.removedUsers = deletedPs != null
10485                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10486                        : null;
10487            }
10488        }
10489        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10490            removeDataDirsLI(packageName);
10491            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10492        }
10493        // writer
10494        synchronized (mPackages) {
10495            if (deletedPs != null) {
10496                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10497                    if (outInfo != null) {
10498                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10499                    }
10500                    if (deletedPs != null) {
10501                        updatePermissionsLPw(deletedPs.name, null, 0);
10502                        if (deletedPs.sharedUser != null) {
10503                            // remove permissions associated with package
10504                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10505                        }
10506                    }
10507                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10508                }
10509                // make sure to preserve per-user disabled state if this removal was just
10510                // a downgrade of a system app to the factory package
10511                if (allUserHandles != null && perUserInstalled != null) {
10512                    if (DEBUG_REMOVE) {
10513                        Slog.d(TAG, "Propagating install state across downgrade");
10514                    }
10515                    for (int i = 0; i < allUserHandles.length; i++) {
10516                        if (DEBUG_REMOVE) {
10517                            Slog.d(TAG, "    user " + allUserHandles[i]
10518                                    + " => " + perUserInstalled[i]);
10519                        }
10520                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10521                    }
10522                }
10523            }
10524            // can downgrade to reader
10525            if (writeSettings) {
10526                // Save settings now
10527                mSettings.writeLPr();
10528            }
10529        }
10530        if (outInfo != null) {
10531            // A user ID was deleted here. Go through all users and remove it
10532            // from KeyStore.
10533            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10534        }
10535    }
10536
10537    static boolean locationIsPrivileged(File path) {
10538        try {
10539            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10540                    .getCanonicalPath();
10541            return path.getCanonicalPath().startsWith(privilegedAppDir);
10542        } catch (IOException e) {
10543            Slog.e(TAG, "Unable to access code path " + path);
10544        }
10545        return false;
10546    }
10547
10548    /*
10549     * Tries to delete system package.
10550     */
10551    private boolean deleteSystemPackageLI(PackageSetting newPs,
10552            int[] allUserHandles, boolean[] perUserInstalled,
10553            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10554        final boolean applyUserRestrictions
10555                = (allUserHandles != null) && (perUserInstalled != null);
10556        PackageSetting disabledPs = null;
10557        // Confirm if the system package has been updated
10558        // An updated system app can be deleted. This will also have to restore
10559        // the system pkg from system partition
10560        // reader
10561        synchronized (mPackages) {
10562            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10563        }
10564        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10565                + " disabledPs=" + disabledPs);
10566        if (disabledPs == null) {
10567            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10568            return false;
10569        } else if (DEBUG_REMOVE) {
10570            Slog.d(TAG, "Deleting system pkg from data partition");
10571        }
10572        if (DEBUG_REMOVE) {
10573            if (applyUserRestrictions) {
10574                Slog.d(TAG, "Remembering install states:");
10575                for (int i = 0; i < allUserHandles.length; i++) {
10576                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10577                }
10578            }
10579        }
10580        // Delete the updated package
10581        outInfo.isRemovedPackageSystemUpdate = true;
10582        if (disabledPs.versionCode < newPs.versionCode) {
10583            // Delete data for downgrades
10584            flags &= ~PackageManager.DELETE_KEEP_DATA;
10585        } else {
10586            // Preserve data by setting flag
10587            flags |= PackageManager.DELETE_KEEP_DATA;
10588        }
10589        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10590                allUserHandles, perUserInstalled, outInfo, writeSettings);
10591        if (!ret) {
10592            return false;
10593        }
10594        // writer
10595        synchronized (mPackages) {
10596            // Reinstate the old system package
10597            mSettings.enableSystemPackageLPw(newPs.name);
10598            // Remove any native libraries from the upgraded package.
10599            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10600        }
10601        // Install the system package
10602        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10603        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10604        if (locationIsPrivileged(disabledPs.codePath)) {
10605            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10606        }
10607        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10608                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
10609
10610        if (newPkg == null) {
10611            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10612                    + " with error:" + mLastScanError);
10613            return false;
10614        }
10615        // writer
10616        synchronized (mPackages) {
10617            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10618            setInternalAppNativeLibraryPath(newPkg, ps);
10619            updatePermissionsLPw(newPkg.packageName, newPkg,
10620                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10621            if (applyUserRestrictions) {
10622                if (DEBUG_REMOVE) {
10623                    Slog.d(TAG, "Propagating install state across reinstall");
10624                }
10625                for (int i = 0; i < allUserHandles.length; i++) {
10626                    if (DEBUG_REMOVE) {
10627                        Slog.d(TAG, "    user " + allUserHandles[i]
10628                                + " => " + perUserInstalled[i]);
10629                    }
10630                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10631                }
10632                // Regardless of writeSettings we need to ensure that this restriction
10633                // state propagation is persisted
10634                mSettings.writeAllUsersPackageRestrictionsLPr();
10635            }
10636            // can downgrade to reader here
10637            if (writeSettings) {
10638                mSettings.writeLPr();
10639            }
10640        }
10641        return true;
10642    }
10643
10644    private boolean deleteInstalledPackageLI(PackageSetting ps,
10645            boolean deleteCodeAndResources, int flags,
10646            int[] allUserHandles, boolean[] perUserInstalled,
10647            PackageRemovedInfo outInfo, boolean writeSettings) {
10648        if (outInfo != null) {
10649            outInfo.uid = ps.appId;
10650        }
10651
10652        // Delete package data from internal structures and also remove data if flag is set
10653        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10654
10655        // Delete application code and resources
10656        if (deleteCodeAndResources && (outInfo != null)) {
10657            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
10658                    ps.resourcePathString, ps.nativeLibraryPathString,
10659                    getAppInstructionSetFromSettings(ps));
10660        }
10661        return true;
10662    }
10663
10664    /*
10665     * This method handles package deletion in general
10666     */
10667    private boolean deletePackageLI(String packageName, UserHandle user,
10668            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10669            int flags, PackageRemovedInfo outInfo,
10670            boolean writeSettings) {
10671        if (packageName == null) {
10672            Slog.w(TAG, "Attempt to delete null packageName.");
10673            return false;
10674        }
10675        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10676        PackageSetting ps;
10677        boolean dataOnly = false;
10678        int removeUser = -1;
10679        int appId = -1;
10680        synchronized (mPackages) {
10681            ps = mSettings.mPackages.get(packageName);
10682            if (ps == null) {
10683                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10684                return false;
10685            }
10686            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10687                    && user.getIdentifier() != UserHandle.USER_ALL) {
10688                // The caller is asking that the package only be deleted for a single
10689                // user.  To do this, we just mark its uninstalled state and delete
10690                // its data.  If this is a system app, we only allow this to happen if
10691                // they have set the special DELETE_SYSTEM_APP which requests different
10692                // semantics than normal for uninstalling system apps.
10693                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10694                ps.setUserState(user.getIdentifier(),
10695                        COMPONENT_ENABLED_STATE_DEFAULT,
10696                        false, //installed
10697                        true,  //stopped
10698                        true,  //notLaunched
10699                        false, //blocked
10700                        null, null, null);
10701                if (!isSystemApp(ps)) {
10702                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10703                        // Other user still have this package installed, so all
10704                        // we need to do is clear this user's data and save that
10705                        // it is uninstalled.
10706                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10707                        removeUser = user.getIdentifier();
10708                        appId = ps.appId;
10709                        mSettings.writePackageRestrictionsLPr(removeUser);
10710                    } else {
10711                        // We need to set it back to 'installed' so the uninstall
10712                        // broadcasts will be sent correctly.
10713                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10714                        ps.setInstalled(true, user.getIdentifier());
10715                    }
10716                } else {
10717                    // This is a system app, so we assume that the
10718                    // other users still have this package installed, so all
10719                    // we need to do is clear this user's data and save that
10720                    // it is uninstalled.
10721                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10722                    removeUser = user.getIdentifier();
10723                    appId = ps.appId;
10724                    mSettings.writePackageRestrictionsLPr(removeUser);
10725                }
10726            }
10727        }
10728
10729        if (removeUser >= 0) {
10730            // From above, we determined that we are deleting this only
10731            // for a single user.  Continue the work here.
10732            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10733            if (outInfo != null) {
10734                outInfo.removedPackage = packageName;
10735                outInfo.removedAppId = appId;
10736                outInfo.removedUsers = new int[] {removeUser};
10737            }
10738            mInstaller.clearUserData(packageName, removeUser);
10739            removeKeystoreDataIfNeeded(removeUser, appId);
10740            schedulePackageCleaning(packageName, removeUser, false);
10741            return true;
10742        }
10743
10744        if (dataOnly) {
10745            // Delete application data first
10746            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10747            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10748            return true;
10749        }
10750
10751        boolean ret = false;
10752        mSettings.mKeySetManager.removeAppKeySetData(packageName);
10753        if (isSystemApp(ps)) {
10754            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10755            // When an updated system application is deleted we delete the existing resources as well and
10756            // fall back to existing code in system partition
10757            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10758                    flags, outInfo, writeSettings);
10759        } else {
10760            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10761            // Kill application pre-emptively especially for apps on sd.
10762            killApplication(packageName, ps.appId, "uninstall pkg");
10763            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10764                    allUserHandles, perUserInstalled,
10765                    outInfo, writeSettings);
10766        }
10767
10768        return ret;
10769    }
10770
10771    private final class ClearStorageConnection implements ServiceConnection {
10772        IMediaContainerService mContainerService;
10773
10774        @Override
10775        public void onServiceConnected(ComponentName name, IBinder service) {
10776            synchronized (this) {
10777                mContainerService = IMediaContainerService.Stub.asInterface(service);
10778                notifyAll();
10779            }
10780        }
10781
10782        @Override
10783        public void onServiceDisconnected(ComponentName name) {
10784        }
10785    }
10786
10787    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10788        final boolean mounted;
10789        if (Environment.isExternalStorageEmulated()) {
10790            mounted = true;
10791        } else {
10792            final String status = Environment.getExternalStorageState();
10793
10794            mounted = status.equals(Environment.MEDIA_MOUNTED)
10795                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10796        }
10797
10798        if (!mounted) {
10799            return;
10800        }
10801
10802        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10803        int[] users;
10804        if (userId == UserHandle.USER_ALL) {
10805            users = sUserManager.getUserIds();
10806        } else {
10807            users = new int[] { userId };
10808        }
10809        final ClearStorageConnection conn = new ClearStorageConnection();
10810        if (mContext.bindServiceAsUser(
10811                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10812            try {
10813                for (int curUser : users) {
10814                    long timeout = SystemClock.uptimeMillis() + 5000;
10815                    synchronized (conn) {
10816                        long now = SystemClock.uptimeMillis();
10817                        while (conn.mContainerService == null && now < timeout) {
10818                            try {
10819                                conn.wait(timeout - now);
10820                            } catch (InterruptedException e) {
10821                            }
10822                        }
10823                    }
10824                    if (conn.mContainerService == null) {
10825                        return;
10826                    }
10827
10828                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10829                    clearDirectory(conn.mContainerService,
10830                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10831                    if (allData) {
10832                        clearDirectory(conn.mContainerService,
10833                                userEnv.buildExternalStorageAppDataDirs(packageName));
10834                        clearDirectory(conn.mContainerService,
10835                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10836                    }
10837                }
10838            } finally {
10839                mContext.unbindService(conn);
10840            }
10841        }
10842    }
10843
10844    @Override
10845    public void clearApplicationUserData(final String packageName,
10846            final IPackageDataObserver observer, final int userId) {
10847        mContext.enforceCallingOrSelfPermission(
10848                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10849        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
10850        // Queue up an async operation since the package deletion may take a little while.
10851        mHandler.post(new Runnable() {
10852            public void run() {
10853                mHandler.removeCallbacks(this);
10854                final boolean succeeded;
10855                synchronized (mInstallLock) {
10856                    succeeded = clearApplicationUserDataLI(packageName, userId);
10857                }
10858                clearExternalStorageDataSync(packageName, userId, true);
10859                if (succeeded) {
10860                    // invoke DeviceStorageMonitor's update method to clear any notifications
10861                    DeviceStorageMonitorInternal
10862                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
10863                    if (dsm != null) {
10864                        dsm.checkMemory();
10865                    }
10866                }
10867                if(observer != null) {
10868                    try {
10869                        observer.onRemoveCompleted(packageName, succeeded);
10870                    } catch (RemoteException e) {
10871                        Log.i(TAG, "Observer no longer exists.");
10872                    }
10873                } //end if observer
10874            } //end run
10875        });
10876    }
10877
10878    private boolean clearApplicationUserDataLI(String packageName, int userId) {
10879        if (packageName == null) {
10880            Slog.w(TAG, "Attempt to delete null packageName.");
10881            return false;
10882        }
10883        PackageParser.Package p;
10884        boolean dataOnly = false;
10885        final int appId;
10886        synchronized (mPackages) {
10887            p = mPackages.get(packageName);
10888            if (p == null) {
10889                dataOnly = true;
10890                PackageSetting ps = mSettings.mPackages.get(packageName);
10891                if ((ps == null) || (ps.pkg == null)) {
10892                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10893                    return false;
10894                }
10895                p = ps.pkg;
10896            }
10897            if (!dataOnly) {
10898                // need to check this only for fully installed applications
10899                if (p == null) {
10900                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10901                    return false;
10902                }
10903                final ApplicationInfo applicationInfo = p.applicationInfo;
10904                if (applicationInfo == null) {
10905                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10906                    return false;
10907                }
10908            }
10909            if (p != null && p.applicationInfo != null) {
10910                appId = p.applicationInfo.uid;
10911            } else {
10912                appId = -1;
10913            }
10914        }
10915        int retCode = mInstaller.clearUserData(packageName, userId);
10916        if (retCode < 0) {
10917            Slog.w(TAG, "Couldn't remove cache files for package: "
10918                    + packageName);
10919            return false;
10920        }
10921        removeKeystoreDataIfNeeded(userId, appId);
10922        return true;
10923    }
10924
10925    /**
10926     * Remove entries from the keystore daemon. Will only remove it if the
10927     * {@code appId} is valid.
10928     */
10929    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
10930        if (appId < 0) {
10931            return;
10932        }
10933
10934        final KeyStore keyStore = KeyStore.getInstance();
10935        if (keyStore != null) {
10936            if (userId == UserHandle.USER_ALL) {
10937                for (final int individual : sUserManager.getUserIds()) {
10938                    keyStore.clearUid(UserHandle.getUid(individual, appId));
10939                }
10940            } else {
10941                keyStore.clearUid(UserHandle.getUid(userId, appId));
10942            }
10943        } else {
10944            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
10945        }
10946    }
10947
10948    @Override
10949    public void deleteApplicationCacheFiles(final String packageName,
10950            final IPackageDataObserver observer) {
10951        mContext.enforceCallingOrSelfPermission(
10952                android.Manifest.permission.DELETE_CACHE_FILES, null);
10953        // Queue up an async operation since the package deletion may take a little while.
10954        final int userId = UserHandle.getCallingUserId();
10955        mHandler.post(new Runnable() {
10956            public void run() {
10957                mHandler.removeCallbacks(this);
10958                final boolean succeded;
10959                synchronized (mInstallLock) {
10960                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
10961                }
10962                clearExternalStorageDataSync(packageName, userId, false);
10963                if(observer != null) {
10964                    try {
10965                        observer.onRemoveCompleted(packageName, succeded);
10966                    } catch (RemoteException e) {
10967                        Log.i(TAG, "Observer no longer exists.");
10968                    }
10969                } //end if observer
10970            } //end run
10971        });
10972    }
10973
10974    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
10975        if (packageName == null) {
10976            Slog.w(TAG, "Attempt to delete null packageName.");
10977            return false;
10978        }
10979        PackageParser.Package p;
10980        synchronized (mPackages) {
10981            p = mPackages.get(packageName);
10982        }
10983        if (p == null) {
10984            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10985            return false;
10986        }
10987        final ApplicationInfo applicationInfo = p.applicationInfo;
10988        if (applicationInfo == null) {
10989            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10990            return false;
10991        }
10992        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
10993        if (retCode < 0) {
10994            Slog.w(TAG, "Couldn't remove cache files for package: "
10995                       + packageName + " u" + userId);
10996            return false;
10997        }
10998        return true;
10999    }
11000
11001    @Override
11002    public void getPackageSizeInfo(final String packageName, int userHandle,
11003            final IPackageStatsObserver observer) {
11004        mContext.enforceCallingOrSelfPermission(
11005                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11006        if (packageName == null) {
11007            throw new IllegalArgumentException("Attempt to get size of null packageName");
11008        }
11009
11010        PackageStats stats = new PackageStats(packageName, userHandle);
11011
11012        /*
11013         * Queue up an async operation since the package measurement may take a
11014         * little while.
11015         */
11016        Message msg = mHandler.obtainMessage(INIT_COPY);
11017        msg.obj = new MeasureParams(stats, observer);
11018        mHandler.sendMessage(msg);
11019    }
11020
11021    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11022            PackageStats pStats) {
11023        if (packageName == null) {
11024            Slog.w(TAG, "Attempt to get size of null packageName.");
11025            return false;
11026        }
11027        PackageParser.Package p;
11028        boolean dataOnly = false;
11029        String libDirPath = null;
11030        String asecPath = null;
11031        PackageSetting ps = null;
11032        synchronized (mPackages) {
11033            p = mPackages.get(packageName);
11034            ps = mSettings.mPackages.get(packageName);
11035            if(p == null) {
11036                dataOnly = true;
11037                if((ps == null) || (ps.pkg == null)) {
11038                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11039                    return false;
11040                }
11041                p = ps.pkg;
11042            }
11043            if (ps != null) {
11044                libDirPath = ps.nativeLibraryPathString;
11045            }
11046            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11047                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
11048                if (secureContainerId != null) {
11049                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11050                }
11051            }
11052        }
11053        String publicSrcDir = null;
11054        if(!dataOnly) {
11055            final ApplicationInfo applicationInfo = p.applicationInfo;
11056            if (applicationInfo == null) {
11057                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11058                return false;
11059            }
11060            if (isForwardLocked(p)) {
11061                publicSrcDir = applicationInfo.publicSourceDir;
11062            }
11063        }
11064        int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath,
11065                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
11066                pStats);
11067        if (res < 0) {
11068            return false;
11069        }
11070
11071        // Fix-up for forward-locked applications in ASEC containers.
11072        if (!isExternal(p)) {
11073            pStats.codeSize += pStats.externalCodeSize;
11074            pStats.externalCodeSize = 0L;
11075        }
11076
11077        return true;
11078    }
11079
11080
11081    @Override
11082    public void addPackageToPreferred(String packageName) {
11083        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11084    }
11085
11086    @Override
11087    public void removePackageFromPreferred(String packageName) {
11088        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11089    }
11090
11091    @Override
11092    public List<PackageInfo> getPreferredPackages(int flags) {
11093        return new ArrayList<PackageInfo>();
11094    }
11095
11096    private int getUidTargetSdkVersionLockedLPr(int uid) {
11097        Object obj = mSettings.getUserIdLPr(uid);
11098        if (obj instanceof SharedUserSetting) {
11099            final SharedUserSetting sus = (SharedUserSetting) obj;
11100            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11101            final Iterator<PackageSetting> it = sus.packages.iterator();
11102            while (it.hasNext()) {
11103                final PackageSetting ps = it.next();
11104                if (ps.pkg != null) {
11105                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11106                    if (v < vers) vers = v;
11107                }
11108            }
11109            return vers;
11110        } else if (obj instanceof PackageSetting) {
11111            final PackageSetting ps = (PackageSetting) obj;
11112            if (ps.pkg != null) {
11113                return ps.pkg.applicationInfo.targetSdkVersion;
11114            }
11115        }
11116        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11117    }
11118
11119    @Override
11120    public void addPreferredActivity(IntentFilter filter, int match,
11121            ComponentName[] set, ComponentName activity, int userId) {
11122        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11123    }
11124
11125    private void addPreferredActivityInternal(IntentFilter filter, int match,
11126            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11127        // writer
11128        int callingUid = Binder.getCallingUid();
11129        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11130        if (filter.countActions() == 0) {
11131            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11132            return;
11133        }
11134        synchronized (mPackages) {
11135            if (mContext.checkCallingOrSelfPermission(
11136                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11137                    != PackageManager.PERMISSION_GRANTED) {
11138                if (getUidTargetSdkVersionLockedLPr(callingUid)
11139                        < Build.VERSION_CODES.FROYO) {
11140                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11141                            + callingUid);
11142                    return;
11143                }
11144                mContext.enforceCallingOrSelfPermission(
11145                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11146            }
11147
11148            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11149            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11150            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11151                    new PreferredActivity(filter, match, set, activity, always));
11152            mSettings.writePackageRestrictionsLPr(userId);
11153        }
11154    }
11155
11156    @Override
11157    public void replacePreferredActivity(IntentFilter filter, int match,
11158            ComponentName[] set, ComponentName activity) {
11159        if (filter.countActions() != 1) {
11160            throw new IllegalArgumentException(
11161                    "replacePreferredActivity expects filter to have only 1 action.");
11162        }
11163        if (filter.countDataAuthorities() != 0
11164                || filter.countDataPaths() != 0
11165                || filter.countDataSchemes() > 1
11166                || filter.countDataTypes() != 0) {
11167            throw new IllegalArgumentException(
11168                    "replacePreferredActivity expects filter to have no data authorities, " +
11169                    "paths, or types; and at most one scheme.");
11170        }
11171        synchronized (mPackages) {
11172            if (mContext.checkCallingOrSelfPermission(
11173                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11174                    != PackageManager.PERMISSION_GRANTED) {
11175                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11176                        < Build.VERSION_CODES.FROYO) {
11177                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11178                            + Binder.getCallingUid());
11179                    return;
11180                }
11181                mContext.enforceCallingOrSelfPermission(
11182                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11183            }
11184
11185            final int callingUserId = UserHandle.getCallingUserId();
11186            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11187            if (pir != null) {
11188                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11189                if (filter.countDataSchemes() == 1) {
11190                    Uri.Builder builder = new Uri.Builder();
11191                    builder.scheme(filter.getDataScheme(0));
11192                    intent.setData(builder.build());
11193                }
11194                List<PreferredActivity> matches = pir.queryIntent(
11195                        intent, null, true, callingUserId);
11196                if (DEBUG_PREFERRED) {
11197                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11198                }
11199                for (int i = 0; i < matches.size(); i++) {
11200                    PreferredActivity pa = matches.get(i);
11201                    if (DEBUG_PREFERRED) {
11202                        Slog.i(TAG, "Removing preferred activity "
11203                                + pa.mPref.mComponent + ":");
11204                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11205                    }
11206                    pir.removeFilter(pa);
11207                }
11208            }
11209            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11210        }
11211    }
11212
11213    @Override
11214    public void clearPackagePreferredActivities(String packageName) {
11215        final int uid = Binder.getCallingUid();
11216        // writer
11217        synchronized (mPackages) {
11218            PackageParser.Package pkg = mPackages.get(packageName);
11219            if (pkg == null || pkg.applicationInfo.uid != uid) {
11220                if (mContext.checkCallingOrSelfPermission(
11221                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11222                        != PackageManager.PERMISSION_GRANTED) {
11223                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11224                            < Build.VERSION_CODES.FROYO) {
11225                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11226                                + Binder.getCallingUid());
11227                        return;
11228                    }
11229                    mContext.enforceCallingOrSelfPermission(
11230                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11231                }
11232            }
11233
11234            int user = UserHandle.getCallingUserId();
11235            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11236                mSettings.writePackageRestrictionsLPr(user);
11237                scheduleWriteSettingsLocked();
11238            }
11239        }
11240    }
11241
11242    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11243    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11244        ArrayList<PreferredActivity> removed = null;
11245        boolean changed = false;
11246        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11247            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11248            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11249            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11250                continue;
11251            }
11252            Iterator<PreferredActivity> it = pir.filterIterator();
11253            while (it.hasNext()) {
11254                PreferredActivity pa = it.next();
11255                // Mark entry for removal only if it matches the package name
11256                // and the entry is of type "always".
11257                if (packageName == null ||
11258                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11259                                && pa.mPref.mAlways)) {
11260                    if (removed == null) {
11261                        removed = new ArrayList<PreferredActivity>();
11262                    }
11263                    removed.add(pa);
11264                }
11265            }
11266            if (removed != null) {
11267                for (int j=0; j<removed.size(); j++) {
11268                    PreferredActivity pa = removed.get(j);
11269                    pir.removeFilter(pa);
11270                }
11271                changed = true;
11272            }
11273        }
11274        return changed;
11275    }
11276
11277    @Override
11278    public void resetPreferredActivities(int userId) {
11279        mContext.enforceCallingOrSelfPermission(
11280                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11281        // writer
11282        synchronized (mPackages) {
11283            int user = UserHandle.getCallingUserId();
11284            clearPackagePreferredActivitiesLPw(null, user);
11285            mSettings.readDefaultPreferredAppsLPw(this, user);
11286            mSettings.writePackageRestrictionsLPr(user);
11287            scheduleWriteSettingsLocked();
11288        }
11289    }
11290
11291    @Override
11292    public int getPreferredActivities(List<IntentFilter> outFilters,
11293            List<ComponentName> outActivities, String packageName) {
11294
11295        int num = 0;
11296        final int userId = UserHandle.getCallingUserId();
11297        // reader
11298        synchronized (mPackages) {
11299            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11300            if (pir != null) {
11301                final Iterator<PreferredActivity> it = pir.filterIterator();
11302                while (it.hasNext()) {
11303                    final PreferredActivity pa = it.next();
11304                    if (packageName == null
11305                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11306                                    && pa.mPref.mAlways)) {
11307                        if (outFilters != null) {
11308                            outFilters.add(new IntentFilter(pa));
11309                        }
11310                        if (outActivities != null) {
11311                            outActivities.add(pa.mPref.mComponent);
11312                        }
11313                    }
11314                }
11315            }
11316        }
11317
11318        return num;
11319    }
11320
11321    @Override
11322    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11323            int userId) {
11324        int callingUid = Binder.getCallingUid();
11325        if (callingUid != Process.SYSTEM_UID) {
11326            throw new SecurityException(
11327                    "addPersistentPreferredActivity can only be run by the system");
11328        }
11329        if (filter.countActions() == 0) {
11330            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11331            return;
11332        }
11333        synchronized (mPackages) {
11334            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11335                    " :");
11336            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11337            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11338                    new PersistentPreferredActivity(filter, activity));
11339            mSettings.writePackageRestrictionsLPr(userId);
11340        }
11341    }
11342
11343    @Override
11344    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11345        int callingUid = Binder.getCallingUid();
11346        if (callingUid != Process.SYSTEM_UID) {
11347            throw new SecurityException(
11348                    "clearPackagePersistentPreferredActivities can only be run by the system");
11349        }
11350        ArrayList<PersistentPreferredActivity> removed = null;
11351        boolean changed = false;
11352        synchronized (mPackages) {
11353            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11354                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11355                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11356                        .valueAt(i);
11357                if (userId != thisUserId) {
11358                    continue;
11359                }
11360                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11361                while (it.hasNext()) {
11362                    PersistentPreferredActivity ppa = it.next();
11363                    // Mark entry for removal only if it matches the package name.
11364                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11365                        if (removed == null) {
11366                            removed = new ArrayList<PersistentPreferredActivity>();
11367                        }
11368                        removed.add(ppa);
11369                    }
11370                }
11371                if (removed != null) {
11372                    for (int j=0; j<removed.size(); j++) {
11373                        PersistentPreferredActivity ppa = removed.get(j);
11374                        ppir.removeFilter(ppa);
11375                    }
11376                    changed = true;
11377                }
11378            }
11379
11380            if (changed) {
11381                mSettings.writePackageRestrictionsLPr(userId);
11382            }
11383        }
11384    }
11385
11386    @Override
11387    public void addForwardingIntentFilter(IntentFilter filter, boolean removable, int userIdOrig,
11388            int userIdDest) {
11389        mContext.enforceCallingOrSelfPermission(
11390                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11391        if (filter.countActions() == 0) {
11392            Slog.w(TAG, "Cannot set a forwarding intent filter with no filter actions");
11393            return;
11394        }
11395        synchronized (mPackages) {
11396            mSettings.editForwardingIntentResolverLPw(userIdOrig).addFilter(
11397                    new ForwardingIntentFilter(filter, removable, userIdDest));
11398            mSettings.writePackageRestrictionsLPr(userIdOrig);
11399        }
11400    }
11401
11402    @Override
11403    public void clearForwardingIntentFilters(int userIdOrig) {
11404        mContext.enforceCallingOrSelfPermission(
11405                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11406        synchronized (mPackages) {
11407            ForwardingIntentResolver fir = mSettings.editForwardingIntentResolverLPw(userIdOrig);
11408            HashSet<ForwardingIntentFilter> set =
11409                    new HashSet<ForwardingIntentFilter>(fir.filterSet());
11410            for (ForwardingIntentFilter fif : set) {
11411                if (fif.isRemovable()) fir.removeFilter(fif);
11412            }
11413            mSettings.writePackageRestrictionsLPr(userIdOrig);
11414        }
11415    }
11416
11417    @Override
11418    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11419        Intent intent = new Intent(Intent.ACTION_MAIN);
11420        intent.addCategory(Intent.CATEGORY_HOME);
11421
11422        final int callingUserId = UserHandle.getCallingUserId();
11423        List<ResolveInfo> list = queryIntentActivities(intent, null,
11424                PackageManager.GET_META_DATA, callingUserId);
11425        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11426                true, false, false, callingUserId);
11427
11428        allHomeCandidates.clear();
11429        if (list != null) {
11430            for (ResolveInfo ri : list) {
11431                allHomeCandidates.add(ri);
11432            }
11433        }
11434        return (preferred == null || preferred.activityInfo == null)
11435                ? null
11436                : new ComponentName(preferred.activityInfo.packageName,
11437                        preferred.activityInfo.name);
11438    }
11439
11440    @Override
11441    public void setApplicationEnabledSetting(String appPackageName,
11442            int newState, int flags, int userId, String callingPackage) {
11443        if (!sUserManager.exists(userId)) return;
11444        if (callingPackage == null) {
11445            callingPackage = Integer.toString(Binder.getCallingUid());
11446        }
11447        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11448    }
11449
11450    @Override
11451    public void setComponentEnabledSetting(ComponentName componentName,
11452            int newState, int flags, int userId) {
11453        if (!sUserManager.exists(userId)) return;
11454        setEnabledSetting(componentName.getPackageName(),
11455                componentName.getClassName(), newState, flags, userId, null);
11456    }
11457
11458    private void setEnabledSetting(final String packageName, String className, int newState,
11459            final int flags, int userId, String callingPackage) {
11460        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11461              || newState == COMPONENT_ENABLED_STATE_ENABLED
11462              || newState == COMPONENT_ENABLED_STATE_DISABLED
11463              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11464              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11465            throw new IllegalArgumentException("Invalid new component state: "
11466                    + newState);
11467        }
11468        PackageSetting pkgSetting;
11469        final int uid = Binder.getCallingUid();
11470        final int permission = mContext.checkCallingOrSelfPermission(
11471                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11472        enforceCrossUserPermission(uid, userId, false, "set enabled");
11473        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11474        boolean sendNow = false;
11475        boolean isApp = (className == null);
11476        String componentName = isApp ? packageName : className;
11477        int packageUid = -1;
11478        ArrayList<String> components;
11479
11480        // writer
11481        synchronized (mPackages) {
11482            pkgSetting = mSettings.mPackages.get(packageName);
11483            if (pkgSetting == null) {
11484                if (className == null) {
11485                    throw new IllegalArgumentException(
11486                            "Unknown package: " + packageName);
11487                }
11488                throw new IllegalArgumentException(
11489                        "Unknown component: " + packageName
11490                        + "/" + className);
11491            }
11492            // Allow root and verify that userId is not being specified by a different user
11493            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11494                throw new SecurityException(
11495                        "Permission Denial: attempt to change component state from pid="
11496                        + Binder.getCallingPid()
11497                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11498            }
11499            if (className == null) {
11500                // We're dealing with an application/package level state change
11501                if (pkgSetting.getEnabled(userId) == newState) {
11502                    // Nothing to do
11503                    return;
11504                }
11505                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11506                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11507                    // Don't care about who enables an app.
11508                    callingPackage = null;
11509                }
11510                pkgSetting.setEnabled(newState, userId, callingPackage);
11511                // pkgSetting.pkg.mSetEnabled = newState;
11512            } else {
11513                // We're dealing with a component level state change
11514                // First, verify that this is a valid class name.
11515                PackageParser.Package pkg = pkgSetting.pkg;
11516                if (pkg == null || !pkg.hasComponentClassName(className)) {
11517                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11518                        throw new IllegalArgumentException("Component class " + className
11519                                + " does not exist in " + packageName);
11520                    } else {
11521                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11522                                + className + " does not exist in " + packageName);
11523                    }
11524                }
11525                switch (newState) {
11526                case COMPONENT_ENABLED_STATE_ENABLED:
11527                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11528                        return;
11529                    }
11530                    break;
11531                case COMPONENT_ENABLED_STATE_DISABLED:
11532                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11533                        return;
11534                    }
11535                    break;
11536                case COMPONENT_ENABLED_STATE_DEFAULT:
11537                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11538                        return;
11539                    }
11540                    break;
11541                default:
11542                    Slog.e(TAG, "Invalid new component state: " + newState);
11543                    return;
11544                }
11545            }
11546            mSettings.writePackageRestrictionsLPr(userId);
11547            components = mPendingBroadcasts.get(userId, packageName);
11548            final boolean newPackage = components == null;
11549            if (newPackage) {
11550                components = new ArrayList<String>();
11551            }
11552            if (!components.contains(componentName)) {
11553                components.add(componentName);
11554            }
11555            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11556                sendNow = true;
11557                // Purge entry from pending broadcast list if another one exists already
11558                // since we are sending one right away.
11559                mPendingBroadcasts.remove(userId, packageName);
11560            } else {
11561                if (newPackage) {
11562                    mPendingBroadcasts.put(userId, packageName, components);
11563                }
11564                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11565                    // Schedule a message
11566                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11567                }
11568            }
11569        }
11570
11571        long callingId = Binder.clearCallingIdentity();
11572        try {
11573            if (sendNow) {
11574                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11575                sendPackageChangedBroadcast(packageName,
11576                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11577            }
11578        } finally {
11579            Binder.restoreCallingIdentity(callingId);
11580        }
11581    }
11582
11583    private void sendPackageChangedBroadcast(String packageName,
11584            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11585        if (DEBUG_INSTALL)
11586            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11587                    + componentNames);
11588        Bundle extras = new Bundle(4);
11589        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11590        String nameList[] = new String[componentNames.size()];
11591        componentNames.toArray(nameList);
11592        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11593        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11594        extras.putInt(Intent.EXTRA_UID, packageUid);
11595        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11596                new int[] {UserHandle.getUserId(packageUid)});
11597    }
11598
11599    @Override
11600    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11601        if (!sUserManager.exists(userId)) return;
11602        final int uid = Binder.getCallingUid();
11603        final int permission = mContext.checkCallingOrSelfPermission(
11604                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11605        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11606        enforceCrossUserPermission(uid, userId, true, "stop package");
11607        // writer
11608        synchronized (mPackages) {
11609            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11610                    uid, userId)) {
11611                scheduleWritePackageRestrictionsLocked(userId);
11612            }
11613        }
11614    }
11615
11616    @Override
11617    public String getInstallerPackageName(String packageName) {
11618        // reader
11619        synchronized (mPackages) {
11620            return mSettings.getInstallerPackageNameLPr(packageName);
11621        }
11622    }
11623
11624    @Override
11625    public int getApplicationEnabledSetting(String packageName, int userId) {
11626        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11627        int uid = Binder.getCallingUid();
11628        enforceCrossUserPermission(uid, userId, false, "get enabled");
11629        // reader
11630        synchronized (mPackages) {
11631            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11632        }
11633    }
11634
11635    @Override
11636    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11637        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11638        int uid = Binder.getCallingUid();
11639        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11640        // reader
11641        synchronized (mPackages) {
11642            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11643        }
11644    }
11645
11646    @Override
11647    public void enterSafeMode() {
11648        enforceSystemOrRoot("Only the system can request entering safe mode");
11649
11650        if (!mSystemReady) {
11651            mSafeMode = true;
11652        }
11653    }
11654
11655    @Override
11656    public void systemReady() {
11657        mSystemReady = true;
11658
11659        // Read the compatibilty setting when the system is ready.
11660        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11661                mContext.getContentResolver(),
11662                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11663        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11664        if (DEBUG_SETTINGS) {
11665            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11666        }
11667
11668        synchronized (mPackages) {
11669            // Verify that all of the preferred activity components actually
11670            // exist.  It is possible for applications to be updated and at
11671            // that point remove a previously declared activity component that
11672            // had been set as a preferred activity.  We try to clean this up
11673            // the next time we encounter that preferred activity, but it is
11674            // possible for the user flow to never be able to return to that
11675            // situation so here we do a sanity check to make sure we haven't
11676            // left any junk around.
11677            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11678            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11679                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11680                removed.clear();
11681                for (PreferredActivity pa : pir.filterSet()) {
11682                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11683                        removed.add(pa);
11684                    }
11685                }
11686                if (removed.size() > 0) {
11687                    for (int j=0; j<removed.size(); j++) {
11688                        PreferredActivity pa = removed.get(i);
11689                        Slog.w(TAG, "Removing dangling preferred activity: "
11690                                + pa.mPref.mComponent);
11691                        pir.removeFilter(pa);
11692                    }
11693                    mSettings.writePackageRestrictionsLPr(
11694                            mSettings.mPreferredActivities.keyAt(i));
11695                }
11696            }
11697        }
11698        sUserManager.systemReady();
11699    }
11700
11701    @Override
11702    public boolean isSafeMode() {
11703        return mSafeMode;
11704    }
11705
11706    @Override
11707    public boolean hasSystemUidErrors() {
11708        return mHasSystemUidErrors;
11709    }
11710
11711    static String arrayToString(int[] array) {
11712        StringBuffer buf = new StringBuffer(128);
11713        buf.append('[');
11714        if (array != null) {
11715            for (int i=0; i<array.length; i++) {
11716                if (i > 0) buf.append(", ");
11717                buf.append(array[i]);
11718            }
11719        }
11720        buf.append(']');
11721        return buf.toString();
11722    }
11723
11724    static class DumpState {
11725        public static final int DUMP_LIBS = 1 << 0;
11726
11727        public static final int DUMP_FEATURES = 1 << 1;
11728
11729        public static final int DUMP_RESOLVERS = 1 << 2;
11730
11731        public static final int DUMP_PERMISSIONS = 1 << 3;
11732
11733        public static final int DUMP_PACKAGES = 1 << 4;
11734
11735        public static final int DUMP_SHARED_USERS = 1 << 5;
11736
11737        public static final int DUMP_MESSAGES = 1 << 6;
11738
11739        public static final int DUMP_PROVIDERS = 1 << 7;
11740
11741        public static final int DUMP_VERIFIERS = 1 << 8;
11742
11743        public static final int DUMP_PREFERRED = 1 << 9;
11744
11745        public static final int DUMP_PREFERRED_XML = 1 << 10;
11746
11747        public static final int DUMP_KEYSETS = 1 << 11;
11748
11749        public static final int DUMP_VERSION = 1 << 12;
11750
11751        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11752
11753        private int mTypes;
11754
11755        private int mOptions;
11756
11757        private boolean mTitlePrinted;
11758
11759        private SharedUserSetting mSharedUser;
11760
11761        public boolean isDumping(int type) {
11762            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11763                return true;
11764            }
11765
11766            return (mTypes & type) != 0;
11767        }
11768
11769        public void setDump(int type) {
11770            mTypes |= type;
11771        }
11772
11773        public boolean isOptionEnabled(int option) {
11774            return (mOptions & option) != 0;
11775        }
11776
11777        public void setOptionEnabled(int option) {
11778            mOptions |= option;
11779        }
11780
11781        public boolean onTitlePrinted() {
11782            final boolean printed = mTitlePrinted;
11783            mTitlePrinted = true;
11784            return printed;
11785        }
11786
11787        public boolean getTitlePrinted() {
11788            return mTitlePrinted;
11789        }
11790
11791        public void setTitlePrinted(boolean enabled) {
11792            mTitlePrinted = enabled;
11793        }
11794
11795        public SharedUserSetting getSharedUser() {
11796            return mSharedUser;
11797        }
11798
11799        public void setSharedUser(SharedUserSetting user) {
11800            mSharedUser = user;
11801        }
11802    }
11803
11804    @Override
11805    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11806        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
11807                != PackageManager.PERMISSION_GRANTED) {
11808            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11809                    + Binder.getCallingPid()
11810                    + ", uid=" + Binder.getCallingUid()
11811                    + " without permission "
11812                    + android.Manifest.permission.DUMP);
11813            return;
11814        }
11815
11816        DumpState dumpState = new DumpState();
11817        boolean fullPreferred = false;
11818        boolean checkin = false;
11819
11820        String packageName = null;
11821
11822        int opti = 0;
11823        while (opti < args.length) {
11824            String opt = args[opti];
11825            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11826                break;
11827            }
11828            opti++;
11829            if ("-a".equals(opt)) {
11830                // Right now we only know how to print all.
11831            } else if ("-h".equals(opt)) {
11832                pw.println("Package manager dump options:");
11833                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
11834                pw.println("    --checkin: dump for a checkin");
11835                pw.println("    -f: print details of intent filters");
11836                pw.println("    -h: print this help");
11837                pw.println("  cmd may be one of:");
11838                pw.println("    l[ibraries]: list known shared libraries");
11839                pw.println("    f[ibraries]: list device features");
11840                pw.println("    r[esolvers]: dump intent resolvers");
11841                pw.println("    perm[issions]: dump permissions");
11842                pw.println("    pref[erred]: print preferred package settings");
11843                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
11844                pw.println("    prov[iders]: dump content providers");
11845                pw.println("    p[ackages]: dump installed packages");
11846                pw.println("    s[hared-users]: dump shared user IDs");
11847                pw.println("    m[essages]: print collected runtime messages");
11848                pw.println("    v[erifiers]: print package verifier info");
11849                pw.println("    version: print database version info");
11850                pw.println("    <package.name>: info about given package");
11851                pw.println("    k[eysets]: print known keysets");
11852                return;
11853            } else if ("--checkin".equals(opt)) {
11854                checkin = true;
11855            } else if ("-f".equals(opt)) {
11856                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11857            } else {
11858                pw.println("Unknown argument: " + opt + "; use -h for help");
11859            }
11860        }
11861
11862        // Is the caller requesting to dump a particular piece of data?
11863        if (opti < args.length) {
11864            String cmd = args[opti];
11865            opti++;
11866            // Is this a package name?
11867            if ("android".equals(cmd) || cmd.contains(".")) {
11868                packageName = cmd;
11869                // When dumping a single package, we always dump all of its
11870                // filter information since the amount of data will be reasonable.
11871                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11872            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
11873                dumpState.setDump(DumpState.DUMP_LIBS);
11874            } else if ("f".equals(cmd) || "features".equals(cmd)) {
11875                dumpState.setDump(DumpState.DUMP_FEATURES);
11876            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
11877                dumpState.setDump(DumpState.DUMP_RESOLVERS);
11878            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
11879                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
11880            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
11881                dumpState.setDump(DumpState.DUMP_PREFERRED);
11882            } else if ("preferred-xml".equals(cmd)) {
11883                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
11884                if (opti < args.length && "--full".equals(args[opti])) {
11885                    fullPreferred = true;
11886                    opti++;
11887                }
11888            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
11889                dumpState.setDump(DumpState.DUMP_PACKAGES);
11890            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
11891                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
11892            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
11893                dumpState.setDump(DumpState.DUMP_PROVIDERS);
11894            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
11895                dumpState.setDump(DumpState.DUMP_MESSAGES);
11896            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
11897                dumpState.setDump(DumpState.DUMP_VERIFIERS);
11898            } else if ("version".equals(cmd)) {
11899                dumpState.setDump(DumpState.DUMP_VERSION);
11900            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
11901                dumpState.setDump(DumpState.DUMP_KEYSETS);
11902            }
11903        }
11904
11905        if (checkin) {
11906            pw.println("vers,1");
11907        }
11908
11909        // reader
11910        synchronized (mPackages) {
11911            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
11912                if (!checkin) {
11913                    if (dumpState.onTitlePrinted())
11914                        pw.println();
11915                    pw.println("Database versions:");
11916                    pw.print("  SDK Version:");
11917                    pw.print(" internal=");
11918                    pw.print(mSettings.mInternalSdkPlatform);
11919                    pw.print(" external=");
11920                    pw.println(mSettings.mExternalSdkPlatform);
11921                    pw.print("  DB Version:");
11922                    pw.print(" internal=");
11923                    pw.print(mSettings.mInternalDatabaseVersion);
11924                    pw.print(" external=");
11925                    pw.println(mSettings.mExternalDatabaseVersion);
11926                }
11927            }
11928
11929            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
11930                if (!checkin) {
11931                    if (dumpState.onTitlePrinted())
11932                        pw.println();
11933                    pw.println("Verifiers:");
11934                    pw.print("  Required: ");
11935                    pw.print(mRequiredVerifierPackage);
11936                    pw.print(" (uid=");
11937                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
11938                    pw.println(")");
11939                } else if (mRequiredVerifierPackage != null) {
11940                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
11941                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
11942                }
11943            }
11944
11945            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
11946                boolean printedHeader = false;
11947                final Iterator<String> it = mSharedLibraries.keySet().iterator();
11948                while (it.hasNext()) {
11949                    String name = it.next();
11950                    SharedLibraryEntry ent = mSharedLibraries.get(name);
11951                    if (!checkin) {
11952                        if (!printedHeader) {
11953                            if (dumpState.onTitlePrinted())
11954                                pw.println();
11955                            pw.println("Libraries:");
11956                            printedHeader = true;
11957                        }
11958                        pw.print("  ");
11959                    } else {
11960                        pw.print("lib,");
11961                    }
11962                    pw.print(name);
11963                    if (!checkin) {
11964                        pw.print(" -> ");
11965                    }
11966                    if (ent.path != null) {
11967                        if (!checkin) {
11968                            pw.print("(jar) ");
11969                            pw.print(ent.path);
11970                        } else {
11971                            pw.print(",jar,");
11972                            pw.print(ent.path);
11973                        }
11974                    } else {
11975                        if (!checkin) {
11976                            pw.print("(apk) ");
11977                            pw.print(ent.apk);
11978                        } else {
11979                            pw.print(",apk,");
11980                            pw.print(ent.apk);
11981                        }
11982                    }
11983                    pw.println();
11984                }
11985            }
11986
11987            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
11988                if (dumpState.onTitlePrinted())
11989                    pw.println();
11990                if (!checkin) {
11991                    pw.println("Features:");
11992                }
11993                Iterator<String> it = mAvailableFeatures.keySet().iterator();
11994                while (it.hasNext()) {
11995                    String name = it.next();
11996                    if (!checkin) {
11997                        pw.print("  ");
11998                    } else {
11999                        pw.print("feat,");
12000                    }
12001                    pw.println(name);
12002                }
12003            }
12004
12005            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12006                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12007                        : "Activity Resolver Table:", "  ", packageName,
12008                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12009                    dumpState.setTitlePrinted(true);
12010                }
12011                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12012                        : "Receiver Resolver Table:", "  ", packageName,
12013                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12014                    dumpState.setTitlePrinted(true);
12015                }
12016                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12017                        : "Service Resolver Table:", "  ", packageName,
12018                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12019                    dumpState.setTitlePrinted(true);
12020                }
12021                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12022                        : "Provider Resolver Table:", "  ", packageName,
12023                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12024                    dumpState.setTitlePrinted(true);
12025                }
12026            }
12027
12028            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12029                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12030                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12031                    int user = mSettings.mPreferredActivities.keyAt(i);
12032                    if (pir.dump(pw,
12033                            dumpState.getTitlePrinted()
12034                                ? "\nPreferred Activities User " + user + ":"
12035                                : "Preferred Activities User " + user + ":", "  ",
12036                            packageName, true)) {
12037                        dumpState.setTitlePrinted(true);
12038                    }
12039                }
12040            }
12041
12042            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12043                pw.flush();
12044                FileOutputStream fout = new FileOutputStream(fd);
12045                BufferedOutputStream str = new BufferedOutputStream(fout);
12046                XmlSerializer serializer = new FastXmlSerializer();
12047                try {
12048                    serializer.setOutput(str, "utf-8");
12049                    serializer.startDocument(null, true);
12050                    serializer.setFeature(
12051                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12052                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12053                    serializer.endDocument();
12054                    serializer.flush();
12055                } catch (IllegalArgumentException e) {
12056                    pw.println("Failed writing: " + e);
12057                } catch (IllegalStateException e) {
12058                    pw.println("Failed writing: " + e);
12059                } catch (IOException e) {
12060                    pw.println("Failed writing: " + e);
12061                }
12062            }
12063
12064            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12065                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12066            }
12067
12068            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12069                boolean printedSomething = false;
12070                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12071                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12072                        continue;
12073                    }
12074                    if (!printedSomething) {
12075                        if (dumpState.onTitlePrinted())
12076                            pw.println();
12077                        pw.println("Registered ContentProviders:");
12078                        printedSomething = true;
12079                    }
12080                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12081                    pw.print("    "); pw.println(p.toString());
12082                }
12083                printedSomething = false;
12084                for (Map.Entry<String, PackageParser.Provider> entry :
12085                        mProvidersByAuthority.entrySet()) {
12086                    PackageParser.Provider p = entry.getValue();
12087                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12088                        continue;
12089                    }
12090                    if (!printedSomething) {
12091                        if (dumpState.onTitlePrinted())
12092                            pw.println();
12093                        pw.println("ContentProvider Authorities:");
12094                        printedSomething = true;
12095                    }
12096                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12097                    pw.print("    "); pw.println(p.toString());
12098                    if (p.info != null && p.info.applicationInfo != null) {
12099                        final String appInfo = p.info.applicationInfo.toString();
12100                        pw.print("      applicationInfo="); pw.println(appInfo);
12101                    }
12102                }
12103            }
12104
12105            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12106                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
12107            }
12108
12109            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12110                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12111            }
12112
12113            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12114                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12115            }
12116
12117            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12118                if (dumpState.onTitlePrinted())
12119                    pw.println();
12120                mSettings.dumpReadMessagesLPr(pw, dumpState);
12121
12122                pw.println();
12123                pw.println("Package warning messages:");
12124                final File fname = getSettingsProblemFile();
12125                FileInputStream in = null;
12126                try {
12127                    in = new FileInputStream(fname);
12128                    final int avail = in.available();
12129                    final byte[] data = new byte[avail];
12130                    in.read(data);
12131                    pw.print(new String(data));
12132                } catch (FileNotFoundException e) {
12133                } catch (IOException e) {
12134                } finally {
12135                    if (in != null) {
12136                        try {
12137                            in.close();
12138                        } catch (IOException e) {
12139                        }
12140                    }
12141                }
12142            }
12143        }
12144    }
12145
12146    // ------- apps on sdcard specific code -------
12147    static final boolean DEBUG_SD_INSTALL = false;
12148
12149    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12150
12151    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12152
12153    private boolean mMediaMounted = false;
12154
12155    private String getEncryptKey() {
12156        try {
12157            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12158                    SD_ENCRYPTION_KEYSTORE_NAME);
12159            if (sdEncKey == null) {
12160                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12161                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12162                if (sdEncKey == null) {
12163                    Slog.e(TAG, "Failed to create encryption keys");
12164                    return null;
12165                }
12166            }
12167            return sdEncKey;
12168        } catch (NoSuchAlgorithmException nsae) {
12169            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12170            return null;
12171        } catch (IOException ioe) {
12172            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12173            return null;
12174        }
12175
12176    }
12177
12178    /* package */static String getTempContainerId() {
12179        int tmpIdx = 1;
12180        String list[] = PackageHelper.getSecureContainerList();
12181        if (list != null) {
12182            for (final String name : list) {
12183                // Ignore null and non-temporary container entries
12184                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12185                    continue;
12186                }
12187
12188                String subStr = name.substring(mTempContainerPrefix.length());
12189                try {
12190                    int cid = Integer.parseInt(subStr);
12191                    if (cid >= tmpIdx) {
12192                        tmpIdx = cid + 1;
12193                    }
12194                } catch (NumberFormatException e) {
12195                }
12196            }
12197        }
12198        return mTempContainerPrefix + tmpIdx;
12199    }
12200
12201    /*
12202     * Update media status on PackageManager.
12203     */
12204    @Override
12205    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12206        int callingUid = Binder.getCallingUid();
12207        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12208            throw new SecurityException("Media status can only be updated by the system");
12209        }
12210        // reader; this apparently protects mMediaMounted, but should probably
12211        // be a different lock in that case.
12212        synchronized (mPackages) {
12213            Log.i(TAG, "Updating external media status from "
12214                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12215                    + (mediaStatus ? "mounted" : "unmounted"));
12216            if (DEBUG_SD_INSTALL)
12217                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12218                        + ", mMediaMounted=" + mMediaMounted);
12219            if (mediaStatus == mMediaMounted) {
12220                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12221                        : 0, -1);
12222                mHandler.sendMessage(msg);
12223                return;
12224            }
12225            mMediaMounted = mediaStatus;
12226        }
12227        // Queue up an async operation since the package installation may take a
12228        // little while.
12229        mHandler.post(new Runnable() {
12230            public void run() {
12231                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12232            }
12233        });
12234    }
12235
12236    /**
12237     * Called by MountService when the initial ASECs to scan are available.
12238     * Should block until all the ASEC containers are finished being scanned.
12239     */
12240    public void scanAvailableAsecs() {
12241        updateExternalMediaStatusInner(true, false, false);
12242        if (mShouldRestoreconData) {
12243            SELinuxMMAC.setRestoreconDone();
12244            mShouldRestoreconData = false;
12245        }
12246    }
12247
12248    /*
12249     * Collect information of applications on external media, map them against
12250     * existing containers and update information based on current mount status.
12251     * Please note that we always have to report status if reportStatus has been
12252     * set to true especially when unloading packages.
12253     */
12254    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12255            boolean externalStorage) {
12256        // Collection of uids
12257        int uidArr[] = null;
12258        // Collection of stale containers
12259        HashSet<String> removeCids = new HashSet<String>();
12260        // Collection of packages on external media with valid containers.
12261        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12262        // Get list of secure containers.
12263        final String list[] = PackageHelper.getSecureContainerList();
12264        if (list == null || list.length == 0) {
12265            Log.i(TAG, "No secure containers on sdcard");
12266        } else {
12267            // Process list of secure containers and categorize them
12268            // as active or stale based on their package internal state.
12269            int uidList[] = new int[list.length];
12270            int num = 0;
12271            // reader
12272            synchronized (mPackages) {
12273                for (String cid : list) {
12274                    if (DEBUG_SD_INSTALL)
12275                        Log.i(TAG, "Processing container " + cid);
12276                    String pkgName = getAsecPackageName(cid);
12277                    if (pkgName == null) {
12278                        if (DEBUG_SD_INSTALL)
12279                            Log.i(TAG, "Container : " + cid + " stale");
12280                        removeCids.add(cid);
12281                        continue;
12282                    }
12283                    if (DEBUG_SD_INSTALL)
12284                        Log.i(TAG, "Looking for pkg : " + pkgName);
12285
12286                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12287                    if (ps == null) {
12288                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12289                        removeCids.add(cid);
12290                        continue;
12291                    }
12292
12293                    /*
12294                     * Skip packages that are not external if we're unmounting
12295                     * external storage.
12296                     */
12297                    if (externalStorage && !isMounted && !isExternal(ps)) {
12298                        continue;
12299                    }
12300
12301                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12302                            getAppInstructionSetFromSettings(ps),
12303                            isForwardLocked(ps));
12304                    // The package status is changed only if the code path
12305                    // matches between settings and the container id.
12306                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12307                        if (DEBUG_SD_INSTALL) {
12308                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12309                                    + " at code path: " + ps.codePathString);
12310                        }
12311
12312                        // We do have a valid package installed on sdcard
12313                        processCids.put(args, ps.codePathString);
12314                        final int uid = ps.appId;
12315                        if (uid != -1) {
12316                            uidList[num++] = uid;
12317                        }
12318                    } else {
12319                        Log.i(TAG, "Deleting stale container for " + cid);
12320                        removeCids.add(cid);
12321                    }
12322                }
12323            }
12324
12325            if (num > 0) {
12326                // Sort uid list
12327                Arrays.sort(uidList, 0, num);
12328                // Throw away duplicates
12329                uidArr = new int[num];
12330                uidArr[0] = uidList[0];
12331                int di = 0;
12332                for (int i = 1; i < num; i++) {
12333                    if (uidList[i - 1] != uidList[i]) {
12334                        uidArr[di++] = uidList[i];
12335                    }
12336                }
12337            }
12338        }
12339        // Process packages with valid entries.
12340        if (isMounted) {
12341            if (DEBUG_SD_INSTALL)
12342                Log.i(TAG, "Loading packages");
12343            loadMediaPackages(processCids, uidArr, removeCids);
12344            startCleaningPackages();
12345        } else {
12346            if (DEBUG_SD_INSTALL)
12347                Log.i(TAG, "Unloading packages");
12348            unloadMediaPackages(processCids, uidArr, reportStatus);
12349        }
12350    }
12351
12352   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12353           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12354        int size = pkgList.size();
12355        if (size > 0) {
12356            // Send broadcasts here
12357            Bundle extras = new Bundle();
12358            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12359                    .toArray(new String[size]));
12360            if (uidArr != null) {
12361                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12362            }
12363            if (replacing) {
12364                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12365            }
12366            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12367                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12368            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12369        }
12370    }
12371
12372   /*
12373     * Look at potentially valid container ids from processCids If package
12374     * information doesn't match the one on record or package scanning fails,
12375     * the cid is added to list of removeCids. We currently don't delete stale
12376     * containers.
12377     */
12378   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12379            HashSet<String> removeCids) {
12380        ArrayList<String> pkgList = new ArrayList<String>();
12381        Set<AsecInstallArgs> keys = processCids.keySet();
12382        boolean doGc = false;
12383        for (AsecInstallArgs args : keys) {
12384            String codePath = processCids.get(args);
12385            if (DEBUG_SD_INSTALL)
12386                Log.i(TAG, "Loading container : " + args.cid);
12387            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12388            try {
12389                // Make sure there are no container errors first.
12390                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12391                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12392                            + " when installing from sdcard");
12393                    continue;
12394                }
12395                // Check code path here.
12396                if (codePath == null || !codePath.equals(args.getCodePath())) {
12397                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12398                            + " does not match one in settings " + codePath);
12399                    continue;
12400                }
12401                // Parse package
12402                int parseFlags = mDefParseFlags;
12403                if (args.isExternal()) {
12404                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12405                }
12406                if (args.isFwdLocked()) {
12407                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12408                }
12409
12410                doGc = true;
12411                synchronized (mInstallLock) {
12412                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
12413                            0, 0, null);
12414                    // Scan the package
12415                    if (pkg != null) {
12416                        /*
12417                         * TODO why is the lock being held? doPostInstall is
12418                         * called in other places without the lock. This needs
12419                         * to be straightened out.
12420                         */
12421                        // writer
12422                        synchronized (mPackages) {
12423                            retCode = PackageManager.INSTALL_SUCCEEDED;
12424                            pkgList.add(pkg.packageName);
12425                            // Post process args
12426                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12427                                    pkg.applicationInfo.uid);
12428                        }
12429                    } else {
12430                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12431                    }
12432                }
12433
12434            } finally {
12435                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12436                    // Don't destroy container here. Wait till gc clears things
12437                    // up.
12438                    removeCids.add(args.cid);
12439                }
12440            }
12441        }
12442        // writer
12443        synchronized (mPackages) {
12444            // If the platform SDK has changed since the last time we booted,
12445            // we need to re-grant app permission to catch any new ones that
12446            // appear. This is really a hack, and means that apps can in some
12447            // cases get permissions that the user didn't initially explicitly
12448            // allow... it would be nice to have some better way to handle
12449            // this situation.
12450            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12451            if (regrantPermissions)
12452                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12453                        + mSdkVersion + "; regranting permissions for external storage");
12454            mSettings.mExternalSdkPlatform = mSdkVersion;
12455
12456            // Make sure group IDs have been assigned, and any permission
12457            // changes in other apps are accounted for
12458            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12459                    | (regrantPermissions
12460                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12461                            : 0));
12462
12463            mSettings.updateExternalDatabaseVersion();
12464
12465            // can downgrade to reader
12466            // Persist settings
12467            mSettings.writeLPr();
12468        }
12469        // Send a broadcast to let everyone know we are done processing
12470        if (pkgList.size() > 0) {
12471            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12472        }
12473        // Force gc to avoid any stale parser references that we might have.
12474        if (doGc) {
12475            Runtime.getRuntime().gc();
12476        }
12477        // List stale containers and destroy stale temporary containers.
12478        if (removeCids != null) {
12479            for (String cid : removeCids) {
12480                if (cid.startsWith(mTempContainerPrefix)) {
12481                    Log.i(TAG, "Destroying stale temporary container " + cid);
12482                    PackageHelper.destroySdDir(cid);
12483                } else {
12484                    Log.w(TAG, "Container " + cid + " is stale");
12485               }
12486           }
12487        }
12488    }
12489
12490   /*
12491     * Utility method to unload a list of specified containers
12492     */
12493    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12494        // Just unmount all valid containers.
12495        for (AsecInstallArgs arg : cidArgs) {
12496            synchronized (mInstallLock) {
12497                arg.doPostDeleteLI(false);
12498           }
12499       }
12500   }
12501
12502    /*
12503     * Unload packages mounted on external media. This involves deleting package
12504     * data from internal structures, sending broadcasts about diabled packages,
12505     * gc'ing to free up references, unmounting all secure containers
12506     * corresponding to packages on external media, and posting a
12507     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12508     * that we always have to post this message if status has been requested no
12509     * matter what.
12510     */
12511    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12512            final boolean reportStatus) {
12513        if (DEBUG_SD_INSTALL)
12514            Log.i(TAG, "unloading media packages");
12515        ArrayList<String> pkgList = new ArrayList<String>();
12516        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12517        final Set<AsecInstallArgs> keys = processCids.keySet();
12518        for (AsecInstallArgs args : keys) {
12519            String pkgName = args.getPackageName();
12520            if (DEBUG_SD_INSTALL)
12521                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12522            // Delete package internally
12523            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12524            synchronized (mInstallLock) {
12525                boolean res = deletePackageLI(pkgName, null, false, null, null,
12526                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12527                if (res) {
12528                    pkgList.add(pkgName);
12529                } else {
12530                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12531                    failedList.add(args);
12532                }
12533            }
12534        }
12535
12536        // reader
12537        synchronized (mPackages) {
12538            // We didn't update the settings after removing each package;
12539            // write them now for all packages.
12540            mSettings.writeLPr();
12541        }
12542
12543        // We have to absolutely send UPDATED_MEDIA_STATUS only
12544        // after confirming that all the receivers processed the ordered
12545        // broadcast when packages get disabled, force a gc to clean things up.
12546        // and unload all the containers.
12547        if (pkgList.size() > 0) {
12548            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12549                    new IIntentReceiver.Stub() {
12550                public void performReceive(Intent intent, int resultCode, String data,
12551                        Bundle extras, boolean ordered, boolean sticky,
12552                        int sendingUser) throws RemoteException {
12553                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12554                            reportStatus ? 1 : 0, 1, keys);
12555                    mHandler.sendMessage(msg);
12556                }
12557            });
12558        } else {
12559            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12560                    keys);
12561            mHandler.sendMessage(msg);
12562        }
12563    }
12564
12565    /** Binder call */
12566    @Override
12567    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12568            final int flags) {
12569        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12570        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12571        int returnCode = PackageManager.MOVE_SUCCEEDED;
12572        int currFlags = 0;
12573        int newFlags = 0;
12574        // reader
12575        synchronized (mPackages) {
12576            PackageParser.Package pkg = mPackages.get(packageName);
12577            if (pkg == null) {
12578                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12579            } else {
12580                // Disable moving fwd locked apps and system packages
12581                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12582                    Slog.w(TAG, "Cannot move system application");
12583                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12584                } else if (pkg.mOperationPending) {
12585                    Slog.w(TAG, "Attempt to move package which has pending operations");
12586                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12587                } else {
12588                    // Find install location first
12589                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12590                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12591                        Slog.w(TAG, "Ambigous flags specified for move location.");
12592                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12593                    } else {
12594                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12595                                : PackageManager.INSTALL_INTERNAL;
12596                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12597                                : PackageManager.INSTALL_INTERNAL;
12598
12599                        if (newFlags == currFlags) {
12600                            Slog.w(TAG, "No move required. Trying to move to same location");
12601                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12602                        } else {
12603                            if (isForwardLocked(pkg)) {
12604                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12605                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12606                            }
12607                        }
12608                    }
12609                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12610                        pkg.mOperationPending = true;
12611                    }
12612                }
12613            }
12614
12615            /*
12616             * TODO this next block probably shouldn't be inside the lock. We
12617             * can't guarantee these won't change after this is fired off
12618             * anyway.
12619             */
12620            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12621                processPendingMove(new MoveParams(null, observer, 0, packageName, null,
12622                        null, -1, user),
12623                        returnCode);
12624            } else {
12625                Message msg = mHandler.obtainMessage(INIT_COPY);
12626                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
12627                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
12628                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir,
12629                        instructionSet);
12630                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12631                        pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user);
12632                msg.obj = mp;
12633                mHandler.sendMessage(msg);
12634            }
12635        }
12636    }
12637
12638    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12639        // Queue up an async operation since the package deletion may take a
12640        // little while.
12641        mHandler.post(new Runnable() {
12642            public void run() {
12643                // TODO fix this; this does nothing.
12644                mHandler.removeCallbacks(this);
12645                int returnCode = currentStatus;
12646                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12647                    int uidArr[] = null;
12648                    ArrayList<String> pkgList = null;
12649                    synchronized (mPackages) {
12650                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12651                        if (pkg == null) {
12652                            Slog.w(TAG, " Package " + mp.packageName
12653                                    + " doesn't exist. Aborting move");
12654                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12655                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
12656                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12657                                    + mp.srcArgs.getCodePath() + " to "
12658                                    + pkg.applicationInfo.sourceDir
12659                                    + " Aborting move and returning error");
12660                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12661                        } else {
12662                            uidArr = new int[] {
12663                                pkg.applicationInfo.uid
12664                            };
12665                            pkgList = new ArrayList<String>();
12666                            pkgList.add(mp.packageName);
12667                        }
12668                    }
12669                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12670                        // Send resources unavailable broadcast
12671                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12672                        // Update package code and resource paths
12673                        synchronized (mInstallLock) {
12674                            synchronized (mPackages) {
12675                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12676                                // Recheck for package again.
12677                                if (pkg == null) {
12678                                    Slog.w(TAG, " Package " + mp.packageName
12679                                            + " doesn't exist. Aborting move");
12680                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12681                                } else if (!mp.srcArgs.getCodePath().equals(
12682                                        pkg.applicationInfo.sourceDir)) {
12683                                    Slog.w(TAG, "Package " + mp.packageName
12684                                            + " code path changed from " + mp.srcArgs.getCodePath()
12685                                            + " to " + pkg.applicationInfo.sourceDir
12686                                            + " Aborting move and returning error");
12687                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12688                                } else {
12689                                    final String oldCodePath = pkg.mPath;
12690                                    final String newCodePath = mp.targetArgs.getCodePath();
12691                                    final String newResPath = mp.targetArgs.getResourcePath();
12692                                    final String newNativePath = mp.targetArgs
12693                                            .getNativeLibraryPath();
12694
12695                                    final File newNativeDir = new File(newNativePath);
12696
12697                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12698                                        // NOTE: We do not report any errors from the APK scan and library
12699                                        // copy at this point.
12700                                        NativeLibraryHelper.ApkHandle handle =
12701                                                new NativeLibraryHelper.ApkHandle(newCodePath);
12702                                        final int abi = NativeLibraryHelper.findSupportedAbi(
12703                                                handle, Build.SUPPORTED_ABIS);
12704                                        if (abi >= 0) {
12705                                            NativeLibraryHelper.copyNativeBinariesIfNeededLI(
12706                                                    handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
12707                                        }
12708                                        handle.close();
12709                                    }
12710                                    final int[] users = sUserManager.getUserIds();
12711                                    for (int user : users) {
12712                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
12713                                                newNativePath, user) < 0) {
12714                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12715                                        }
12716                                    }
12717
12718                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12719                                        pkg.mPath = newCodePath;
12720                                        // Move dex files around
12721                                        if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
12722                                            // Moving of dex files failed. Set
12723                                            // error code and abort move.
12724                                            pkg.mPath = pkg.mScanPath;
12725                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12726                                        }
12727                                    }
12728
12729                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12730                                        pkg.mScanPath = newCodePath;
12731                                        pkg.applicationInfo.sourceDir = newCodePath;
12732                                        pkg.applicationInfo.publicSourceDir = newResPath;
12733                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
12734                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
12735                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
12736                                        ps.codePathString = ps.codePath.getPath();
12737                                        ps.resourcePath = new File(
12738                                                pkg.applicationInfo.publicSourceDir);
12739                                        ps.resourcePathString = ps.resourcePath.getPath();
12740                                        ps.nativeLibraryPathString = newNativePath;
12741                                        // Set the application info flag
12742                                        // correctly.
12743                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
12744                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12745                                        } else {
12746                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12747                                        }
12748                                        ps.setFlags(pkg.applicationInfo.flags);
12749                                        mAppDirs.remove(oldCodePath);
12750                                        mAppDirs.put(newCodePath, pkg);
12751                                        // Persist settings
12752                                        mSettings.writeLPr();
12753                                    }
12754                                }
12755                            }
12756                        }
12757                        // Send resources available broadcast
12758                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12759                    }
12760                }
12761                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12762                    // Clean up failed installation
12763                    if (mp.targetArgs != null) {
12764                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
12765                                -1);
12766                    }
12767                } else {
12768                    // Force a gc to clear things up.
12769                    Runtime.getRuntime().gc();
12770                    // Delete older code
12771                    synchronized (mInstallLock) {
12772                        mp.srcArgs.doPostDeleteLI(true);
12773                    }
12774                }
12775
12776                // Allow more operations on this file if we didn't fail because
12777                // an operation was already pending for this package.
12778                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
12779                    synchronized (mPackages) {
12780                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12781                        if (pkg != null) {
12782                            pkg.mOperationPending = false;
12783                       }
12784                   }
12785                }
12786
12787                IPackageMoveObserver observer = mp.observer;
12788                if (observer != null) {
12789                    try {
12790                        observer.packageMoved(mp.packageName, returnCode);
12791                    } catch (RemoteException e) {
12792                        Log.i(TAG, "Observer no longer exists.");
12793                    }
12794                }
12795            }
12796        });
12797    }
12798
12799    @Override
12800    public boolean setInstallLocation(int loc) {
12801        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12802                null);
12803        if (getInstallLocation() == loc) {
12804            return true;
12805        }
12806        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12807                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12808            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12809                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12810            return true;
12811        }
12812        return false;
12813   }
12814
12815    @Override
12816    public int getInstallLocation() {
12817        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12818                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12819                PackageHelper.APP_INSTALL_AUTO);
12820    }
12821
12822    /** Called by UserManagerService */
12823    void cleanUpUserLILPw(int userHandle) {
12824        mDirtyUsers.remove(userHandle);
12825        mSettings.removeUserLPr(userHandle);
12826        mPendingBroadcasts.remove(userHandle);
12827        if (mInstaller != null) {
12828            // Technically, we shouldn't be doing this with the package lock
12829            // held.  However, this is very rare, and there is already so much
12830            // other disk I/O going on, that we'll let it slide for now.
12831            mInstaller.removeUserDataDirs(userHandle);
12832        }
12833    }
12834
12835    /** Called by UserManagerService */
12836    void createNewUserLILPw(int userHandle, File path) {
12837        if (mInstaller != null) {
12838            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12839        }
12840    }
12841
12842    @Override
12843    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12844        mContext.enforceCallingOrSelfPermission(
12845                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12846                "Only package verification agents can read the verifier device identity");
12847
12848        synchronized (mPackages) {
12849            return mSettings.getVerifierDeviceIdentityLPw();
12850        }
12851    }
12852
12853    @Override
12854    public void setPermissionEnforced(String permission, boolean enforced) {
12855        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
12856        if (READ_EXTERNAL_STORAGE.equals(permission)) {
12857            synchronized (mPackages) {
12858                if (mSettings.mReadExternalStorageEnforced == null
12859                        || mSettings.mReadExternalStorageEnforced != enforced) {
12860                    mSettings.mReadExternalStorageEnforced = enforced;
12861                    mSettings.writeLPr();
12862                }
12863            }
12864            // kill any non-foreground processes so we restart them and
12865            // grant/revoke the GID.
12866            final IActivityManager am = ActivityManagerNative.getDefault();
12867            if (am != null) {
12868                final long token = Binder.clearCallingIdentity();
12869                try {
12870                    am.killProcessesBelowForeground("setPermissionEnforcement");
12871                } catch (RemoteException e) {
12872                } finally {
12873                    Binder.restoreCallingIdentity(token);
12874                }
12875            }
12876        } else {
12877            throw new IllegalArgumentException("No selective enforcement for " + permission);
12878        }
12879    }
12880
12881    @Override
12882    @Deprecated
12883    public boolean isPermissionEnforced(String permission) {
12884        return true;
12885    }
12886
12887    @Override
12888    public boolean isStorageLow() {
12889        final long token = Binder.clearCallingIdentity();
12890        try {
12891            final DeviceStorageMonitorInternal
12892                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12893            if (dsm != null) {
12894                return dsm.isMemoryLow();
12895            } else {
12896                return false;
12897            }
12898        } finally {
12899            Binder.restoreCallingIdentity(token);
12900        }
12901    }
12902}
12903