PackageManagerService.java revision 6422abef786632e53337c6c298ffa64f7ddf4d90
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.Certificate;
161import java.security.cert.CertificateEncodingException;
162import java.security.cert.CertificateException;
163import java.text.SimpleDateFormat;
164import java.util.ArrayList;
165import java.util.Arrays;
166import java.util.Collection;
167import java.util.Collections;
168import java.util.Comparator;
169import java.util.Date;
170import java.util.HashMap;
171import java.util.HashSet;
172import java.util.Iterator;
173import java.util.List;
174import java.util.Map;
175import java.util.Set;
176import java.util.concurrent.atomic.AtomicBoolean;
177import java.util.concurrent.atomic.AtomicLong;
178
179import dalvik.system.DexFile;
180import dalvik.system.StaleDexCacheError;
181import dalvik.system.VMRuntime;
182import libcore.io.IoUtils;
183
184/**
185 * Keep track of all those .apks everywhere.
186 *
187 * This is very central to the platform's security; please run the unit
188 * tests whenever making modifications here:
189 *
190mmm frameworks/base/tests/AndroidTests
191adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
192adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
193 *
194 * {@hide}
195 */
196public class PackageManagerService extends IPackageManager.Stub {
197    static final String TAG = "PackageManager";
198    static final boolean DEBUG_SETTINGS = false;
199    static final boolean DEBUG_PREFERRED = false;
200    static final boolean DEBUG_UPGRADE = false;
201    private static final boolean DEBUG_INSTALL = false;
202    private static final boolean DEBUG_REMOVE = false;
203    private static final boolean DEBUG_BROADCASTS = false;
204    private static final boolean DEBUG_SHOW_INFO = false;
205    private static final boolean DEBUG_PACKAGE_INFO = false;
206    private static final boolean DEBUG_INTENT_MATCHING = false;
207    private static final boolean DEBUG_PACKAGE_SCANNING = false;
208    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
209    private static final boolean DEBUG_VERIFY = false;
210    private static final boolean DEBUG_DEXOPT = false;
211
212    private static final int RADIO_UID = Process.PHONE_UID;
213    private static final int LOG_UID = Process.LOG_UID;
214    private static final int NFC_UID = Process.NFC_UID;
215    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
216    private static final int SHELL_UID = Process.SHELL_UID;
217
218    // Cap the size of permission trees that 3rd party apps can define
219    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
220
221    private static final int REMOVE_EVENTS =
222        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
223    private static final int ADD_EVENTS =
224        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
225
226    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
227    // Suffix used during package installation when copying/moving
228    // package apks to install directory.
229    private static final String INSTALL_PACKAGE_SUFFIX = "-";
230
231    static final int SCAN_MONITOR = 1<<0;
232    static final int SCAN_NO_DEX = 1<<1;
233    static final int SCAN_FORCE_DEX = 1<<2;
234    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
235    static final int SCAN_NEW_INSTALL = 1<<4;
236    static final int SCAN_NO_PATHS = 1<<5;
237    static final int SCAN_UPDATE_TIME = 1<<6;
238    static final int SCAN_DEFER_DEX = 1<<7;
239    static final int SCAN_BOOTING = 1<<8;
240    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
241    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
242
243    static final int REMOVE_CHATTY = 1<<16;
244
245    /**
246     * Timeout (in milliseconds) after which the watchdog should declare that
247     * our handler thread is wedged.  The usual default for such things is one
248     * minute but we sometimes do very lengthy I/O operations on this thread,
249     * such as installing multi-gigabyte applications, so ours needs to be longer.
250     */
251    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
252
253    /**
254     * Whether verification is enabled by default.
255     */
256    private static final boolean DEFAULT_VERIFY_ENABLE = true;
257
258    /**
259     * The default maximum time to wait for the verification agent to return in
260     * milliseconds.
261     */
262    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
263
264    /**
265     * The default response for package verification timeout.
266     *
267     * This can be either PackageManager.VERIFICATION_ALLOW or
268     * PackageManager.VERIFICATION_REJECT.
269     */
270    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
271
272    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
273
274    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
275            DEFAULT_CONTAINER_PACKAGE,
276            "com.android.defcontainer.DefaultContainerService");
277
278    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
279
280    private static final String LIB_DIR_NAME = "lib";
281    private static final String LIB64_DIR_NAME = "lib64";
282
283    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
284
285    static final String mTempContainerPrefix = "smdl2tmp";
286
287    private static String sPreferredInstructionSet;
288
289    final ServiceThread mHandlerThread;
290
291    private static final String IDMAP_PREFIX = "/data/resource-cache/";
292    private static final String IDMAP_SUFFIX = "@idmap";
293
294    final PackageHandler mHandler;
295
296    final int mSdkVersion = Build.VERSION.SDK_INT;
297
298    final Context mContext;
299    final boolean mFactoryTest;
300    final boolean mOnlyCore;
301    final DisplayMetrics mMetrics;
302    final int mDefParseFlags;
303    final String[] mSeparateProcesses;
304
305    // This is where all application persistent data goes.
306    final File mAppDataDir;
307
308    // This is where all application persistent data goes for secondary users.
309    final File mUserAppDataDir;
310
311    /** The location for ASEC container files on internal storage. */
312    final String mAsecInternalPath;
313
314    // This is the object monitoring the framework dir.
315    final FileObserver mFrameworkInstallObserver;
316
317    // This is the object monitoring the system app dir.
318    final FileObserver mSystemInstallObserver;
319
320    // This is the object monitoring the privileged system app dir.
321    final FileObserver mPrivilegedInstallObserver;
322
323    // This is the object monitoring the vendor app dir.
324    final FileObserver mVendorInstallObserver;
325
326    // This is the object monitoring the vendor overlay package dir.
327    final FileObserver mVendorOverlayInstallObserver;
328
329    // This is the object monitoring the OEM app dir.
330    final FileObserver mOemInstallObserver;
331
332    // This is the object monitoring mAppInstallDir.
333    final FileObserver mAppInstallObserver;
334
335    // This is the object monitoring mDrmAppPrivateInstallDir.
336    final FileObserver mDrmAppInstallObserver;
337
338    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
339    // LOCK HELD.  Can be called with mInstallLock held.
340    final Installer mInstaller;
341
342    final File mAppInstallDir;
343
344    /**
345     * Directory to which applications installed internally have native
346     * libraries copied.
347     */
348    private File mAppLibInstallDir;
349
350    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
351    // apps.
352    final File mDrmAppPrivateInstallDir;
353
354    // ----------------------------------------------------------------
355
356    // Lock for state used when installing and doing other long running
357    // operations.  Methods that must be called with this lock held have
358    // the suffix "LI".
359    final Object mInstallLock = new Object();
360
361    // These are the directories in the 3rd party applications installed dir
362    // that we have currently loaded packages from.  Keys are the application's
363    // installed zip file (absolute codePath), and values are Package.
364    final HashMap<String, PackageParser.Package> mAppDirs =
365            new HashMap<String, PackageParser.Package>();
366
367    // Information for the parser to write more useful error messages.
368    int mLastScanError;
369
370    // ----------------------------------------------------------------
371
372    // Keys are String (package name), values are Package.  This also serves
373    // as the lock for the global state.  Methods that must be called with
374    // this lock held have the prefix "LP".
375    final HashMap<String, PackageParser.Package> mPackages =
376            new HashMap<String, PackageParser.Package>();
377
378    // Tracks available target package names -> overlay package paths.
379    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
380        new HashMap<String, HashMap<String, PackageParser.Package>>();
381
382    final Settings mSettings;
383    boolean mRestoredSettings;
384
385    // Group-ids that are given to all packages as read from etc/permissions/*.xml.
386    int[] mGlobalGids;
387
388    // These are the built-in uid -> permission mappings that were read from the
389    // etc/permissions.xml file.
390    final SparseArray<HashSet<String>> mSystemPermissions =
391            new SparseArray<HashSet<String>>();
392
393    static final class SharedLibraryEntry {
394        final String path;
395        final String apk;
396
397        SharedLibraryEntry(String _path, String _apk) {
398            path = _path;
399            apk = _apk;
400        }
401    }
402
403    // These are the built-in shared libraries that were read from the
404    // etc/permissions.xml file.
405    final HashMap<String, SharedLibraryEntry> mSharedLibraries
406            = new HashMap<String, SharedLibraryEntry>();
407
408    // Temporary for building the final shared libraries for an .apk.
409    String[] mTmpSharedLibraries = null;
410
411    // These are the features this devices supports that were read from the
412    // etc/permissions.xml file.
413    final HashMap<String, FeatureInfo> mAvailableFeatures =
414            new HashMap<String, FeatureInfo>();
415
416    // If mac_permissions.xml was found for seinfo labeling.
417    boolean mFoundPolicyFile;
418
419    // If a recursive restorecon of /data/data/<pkg> is needed.
420    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
421
422    // All available activities, for your resolving pleasure.
423    final ActivityIntentResolver mActivities =
424            new ActivityIntentResolver();
425
426    // All available receivers, for your resolving pleasure.
427    final ActivityIntentResolver mReceivers =
428            new ActivityIntentResolver();
429
430    // All available services, for your resolving pleasure.
431    final ServiceIntentResolver mServices = new ServiceIntentResolver();
432
433    // All available providers, for your resolving pleasure.
434    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
435
436    // Mapping from provider base names (first directory in content URI codePath)
437    // to the provider information.
438    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
439            new HashMap<String, PackageParser.Provider>();
440
441    // Mapping from instrumentation class names to info about them.
442    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
443            new HashMap<ComponentName, PackageParser.Instrumentation>();
444
445    // Mapping from permission names to info about them.
446    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
447            new HashMap<String, PackageParser.PermissionGroup>();
448
449    // Packages whose data we have transfered into another package, thus
450    // should no longer exist.
451    final HashSet<String> mTransferedPackages = new HashSet<String>();
452
453    // Broadcast actions that are only available to the system.
454    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
455
456    /** List of packages waiting for verification. */
457    final SparseArray<PackageVerificationState> mPendingVerification
458            = new SparseArray<PackageVerificationState>();
459
460    HashSet<PackageParser.Package> mDeferredDexOpt = null;
461
462    /** Token for keys in mPendingVerification. */
463    private int mPendingVerificationToken = 0;
464
465    boolean mSystemReady;
466    boolean mSafeMode;
467    boolean mHasSystemUidErrors;
468
469    ApplicationInfo mAndroidApplication;
470    final ActivityInfo mResolveActivity = new ActivityInfo();
471    final ResolveInfo mResolveInfo = new ResolveInfo();
472    ComponentName mResolveComponentName;
473    PackageParser.Package mPlatformPackage;
474    ComponentName mCustomResolverComponentName;
475
476    boolean mResolverReplaced = false;
477
478    // Set of pending broadcasts for aggregating enable/disable of components.
479    static class PendingPackageBroadcasts {
480        // for each user id, a map of <package name -> components within that package>
481        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
482
483        public PendingPackageBroadcasts() {
484            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
485        }
486
487        public ArrayList<String> get(int userId, String packageName) {
488            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
489            return packages.get(packageName);
490        }
491
492        public void put(int userId, String packageName, ArrayList<String> components) {
493            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
494            packages.put(packageName, components);
495        }
496
497        public void remove(int userId, String packageName) {
498            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
499            if (packages != null) {
500                packages.remove(packageName);
501            }
502        }
503
504        public void remove(int userId) {
505            mUidMap.remove(userId);
506        }
507
508        public int userIdCount() {
509            return mUidMap.size();
510        }
511
512        public int userIdAt(int n) {
513            return mUidMap.keyAt(n);
514        }
515
516        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
517            return mUidMap.get(userId);
518        }
519
520        public int size() {
521            // total number of pending broadcast entries across all userIds
522            int num = 0;
523            for (int i = 0; i< mUidMap.size(); i++) {
524                num += mUidMap.valueAt(i).size();
525            }
526            return num;
527        }
528
529        public void clear() {
530            mUidMap.clear();
531        }
532
533        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
534            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
535            if (map == null) {
536                map = new HashMap<String, ArrayList<String>>();
537                mUidMap.put(userId, map);
538            }
539            return map;
540        }
541    }
542    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
543
544    // Service Connection to remote media container service to copy
545    // package uri's from external media onto secure containers
546    // or internal storage.
547    private IMediaContainerService mContainerService = null;
548
549    static final int SEND_PENDING_BROADCAST = 1;
550    static final int MCS_BOUND = 3;
551    static final int END_COPY = 4;
552    static final int INIT_COPY = 5;
553    static final int MCS_UNBIND = 6;
554    static final int START_CLEANING_PACKAGE = 7;
555    static final int FIND_INSTALL_LOC = 8;
556    static final int POST_INSTALL = 9;
557    static final int MCS_RECONNECT = 10;
558    static final int MCS_GIVE_UP = 11;
559    static final int UPDATED_MEDIA_STATUS = 12;
560    static final int WRITE_SETTINGS = 13;
561    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
562    static final int PACKAGE_VERIFIED = 15;
563    static final int CHECK_PENDING_VERIFICATION = 16;
564
565    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
566
567    // Delay time in millisecs
568    static final int BROADCAST_DELAY = 10 * 1000;
569
570    static UserManagerService sUserManager;
571
572    // Stores a list of users whose package restrictions file needs to be updated
573    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
574
575    final private DefaultContainerConnection mDefContainerConn =
576            new DefaultContainerConnection();
577    class DefaultContainerConnection implements ServiceConnection {
578        public void onServiceConnected(ComponentName name, IBinder service) {
579            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
580            IMediaContainerService imcs =
581                IMediaContainerService.Stub.asInterface(service);
582            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
583        }
584
585        public void onServiceDisconnected(ComponentName name) {
586            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
587        }
588    };
589
590    // Recordkeeping of restore-after-install operations that are currently in flight
591    // between the Package Manager and the Backup Manager
592    class PostInstallData {
593        public InstallArgs args;
594        public PackageInstalledInfo res;
595
596        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
597            args = _a;
598            res = _r;
599        }
600    };
601    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
602    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
603
604    private final String mRequiredVerifierPackage;
605
606    private final PackageUsage mPackageUsage = new PackageUsage();
607
608    private class PackageUsage {
609        private static final int WRITE_INTERVAL
610            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
611
612        private final Object mFileLock = new Object();
613        private final AtomicLong mLastWritten = new AtomicLong(0);
614        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
615
616        void write(boolean force) {
617            if (force) {
618                write();
619                return;
620            }
621            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
622                && !DEBUG_DEXOPT) {
623                return;
624            }
625            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
626                new Thread("PackageUsage_DiskWriter") {
627                    public void run() {
628                        try {
629                            write(true);
630                        } finally {
631                            mBackgroundWriteRunning.set(false);
632                        }
633                    }
634                }.start();
635            }
636        }
637
638        private void write() {
639            synchronized (mPackages) {
640                synchronized (mFileLock) {
641                    AtomicFile file = getFile();
642                    FileOutputStream f = null;
643                    try {
644                        f = file.startWrite();
645                        BufferedOutputStream out = new BufferedOutputStream(f);
646                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
647                        StringBuilder sb = new StringBuilder();
648                        for (PackageParser.Package pkg : mPackages.values()) {
649                            if (pkg.mLastPackageUsageTimeInMills == 0) {
650                                continue;
651                            }
652                            sb.setLength(0);
653                            sb.append(pkg.packageName);
654                            sb.append(' ');
655                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
656                            sb.append('\n');
657                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
658                        }
659                        out.flush();
660                        file.finishWrite(f);
661                    } catch (IOException e) {
662                        if (f != null) {
663                            file.failWrite(f);
664                        }
665                        Log.e(TAG, "Failed to write package usage times", e);
666                    }
667                }
668            }
669            mLastWritten.set(SystemClock.elapsedRealtime());
670        }
671
672        void readLP() {
673            synchronized (mFileLock) {
674                AtomicFile file = getFile();
675                BufferedInputStream in = null;
676                try {
677                    in = new BufferedInputStream(file.openRead());
678                    StringBuffer sb = new StringBuffer();
679                    while (true) {
680                        String packageName = readToken(in, sb, ' ');
681                        if (packageName == null) {
682                            break;
683                        }
684                        String timeInMillisString = readToken(in, sb, '\n');
685                        if (timeInMillisString == null) {
686                            throw new IOException("Failed to find last usage time for package "
687                                                  + packageName);
688                        }
689                        PackageParser.Package pkg = mPackages.get(packageName);
690                        if (pkg == null) {
691                            continue;
692                        }
693                        long timeInMillis;
694                        try {
695                            timeInMillis = Long.parseLong(timeInMillisString.toString());
696                        } catch (NumberFormatException e) {
697                            throw new IOException("Failed to parse " + timeInMillisString
698                                                  + " as a long.", e);
699                        }
700                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
701                    }
702                } catch (FileNotFoundException expected) {
703                } catch (IOException e) {
704                    Log.w(TAG, "Failed to read package usage times", e);
705                } finally {
706                    IoUtils.closeQuietly(in);
707                }
708            }
709            mLastWritten.set(SystemClock.elapsedRealtime());
710        }
711
712        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
713                throws IOException {
714            sb.setLength(0);
715            while (true) {
716                int ch = in.read();
717                if (ch == -1) {
718                    if (sb.length() == 0) {
719                        return null;
720                    }
721                    throw new IOException("Unexpected EOF");
722                }
723                if (ch == endOfToken) {
724                    return sb.toString();
725                }
726                sb.append((char)ch);
727            }
728        }
729
730        private AtomicFile getFile() {
731            File dataDir = Environment.getDataDirectory();
732            File systemDir = new File(dataDir, "system");
733            File fname = new File(systemDir, "package-usage.list");
734            return new AtomicFile(fname);
735        }
736    }
737
738    class PackageHandler extends Handler {
739        private boolean mBound = false;
740        final ArrayList<HandlerParams> mPendingInstalls =
741            new ArrayList<HandlerParams>();
742
743        private boolean connectToService() {
744            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
745                    " DefaultContainerService");
746            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
747            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
748            if (mContext.bindServiceAsUser(service, mDefContainerConn,
749                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
750                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
751                mBound = true;
752                return true;
753            }
754            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
755            return false;
756        }
757
758        private void disconnectService() {
759            mContainerService = null;
760            mBound = false;
761            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
762            mContext.unbindService(mDefContainerConn);
763            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
764        }
765
766        PackageHandler(Looper looper) {
767            super(looper);
768        }
769
770        public void handleMessage(Message msg) {
771            try {
772                doHandleMessage(msg);
773            } finally {
774                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
775            }
776        }
777
778        void doHandleMessage(Message msg) {
779            switch (msg.what) {
780                case INIT_COPY: {
781                    HandlerParams params = (HandlerParams) msg.obj;
782                    int idx = mPendingInstalls.size();
783                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
784                    // If a bind was already initiated we dont really
785                    // need to do anything. The pending install
786                    // will be processed later on.
787                    if (!mBound) {
788                        // If this is the only one pending we might
789                        // have to bind to the service again.
790                        if (!connectToService()) {
791                            Slog.e(TAG, "Failed to bind to media container service");
792                            params.serviceError();
793                            return;
794                        } else {
795                            // Once we bind to the service, the first
796                            // pending request will be processed.
797                            mPendingInstalls.add(idx, params);
798                        }
799                    } else {
800                        mPendingInstalls.add(idx, params);
801                        // Already bound to the service. Just make
802                        // sure we trigger off processing the first request.
803                        if (idx == 0) {
804                            mHandler.sendEmptyMessage(MCS_BOUND);
805                        }
806                    }
807                    break;
808                }
809                case MCS_BOUND: {
810                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
811                    if (msg.obj != null) {
812                        mContainerService = (IMediaContainerService) msg.obj;
813                    }
814                    if (mContainerService == null) {
815                        // Something seriously wrong. Bail out
816                        Slog.e(TAG, "Cannot bind to media container service");
817                        for (HandlerParams params : mPendingInstalls) {
818                            // Indicate service bind error
819                            params.serviceError();
820                        }
821                        mPendingInstalls.clear();
822                    } else if (mPendingInstalls.size() > 0) {
823                        HandlerParams params = mPendingInstalls.get(0);
824                        if (params != null) {
825                            if (params.startCopy()) {
826                                // We are done...  look for more work or to
827                                // go idle.
828                                if (DEBUG_SD_INSTALL) Log.i(TAG,
829                                        "Checking for more work or unbind...");
830                                // Delete pending install
831                                if (mPendingInstalls.size() > 0) {
832                                    mPendingInstalls.remove(0);
833                                }
834                                if (mPendingInstalls.size() == 0) {
835                                    if (mBound) {
836                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
837                                                "Posting delayed MCS_UNBIND");
838                                        removeMessages(MCS_UNBIND);
839                                        Message ubmsg = obtainMessage(MCS_UNBIND);
840                                        // Unbind after a little delay, to avoid
841                                        // continual thrashing.
842                                        sendMessageDelayed(ubmsg, 10000);
843                                    }
844                                } else {
845                                    // There are more pending requests in queue.
846                                    // Just post MCS_BOUND message to trigger processing
847                                    // of next pending install.
848                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
849                                            "Posting MCS_BOUND for next work");
850                                    mHandler.sendEmptyMessage(MCS_BOUND);
851                                }
852                            }
853                        }
854                    } else {
855                        // Should never happen ideally.
856                        Slog.w(TAG, "Empty queue");
857                    }
858                    break;
859                }
860                case MCS_RECONNECT: {
861                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
862                    if (mPendingInstalls.size() > 0) {
863                        if (mBound) {
864                            disconnectService();
865                        }
866                        if (!connectToService()) {
867                            Slog.e(TAG, "Failed to bind to media container service");
868                            for (HandlerParams params : mPendingInstalls) {
869                                // Indicate service bind error
870                                params.serviceError();
871                            }
872                            mPendingInstalls.clear();
873                        }
874                    }
875                    break;
876                }
877                case MCS_UNBIND: {
878                    // If there is no actual work left, then time to unbind.
879                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
880
881                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
882                        if (mBound) {
883                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
884
885                            disconnectService();
886                        }
887                    } else if (mPendingInstalls.size() > 0) {
888                        // There are more pending requests in queue.
889                        // Just post MCS_BOUND message to trigger processing
890                        // of next pending install.
891                        mHandler.sendEmptyMessage(MCS_BOUND);
892                    }
893
894                    break;
895                }
896                case MCS_GIVE_UP: {
897                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
898                    mPendingInstalls.remove(0);
899                    break;
900                }
901                case SEND_PENDING_BROADCAST: {
902                    String packages[];
903                    ArrayList<String> components[];
904                    int size = 0;
905                    int uids[];
906                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
907                    synchronized (mPackages) {
908                        if (mPendingBroadcasts == null) {
909                            return;
910                        }
911                        size = mPendingBroadcasts.size();
912                        if (size <= 0) {
913                            // Nothing to be done. Just return
914                            return;
915                        }
916                        packages = new String[size];
917                        components = new ArrayList[size];
918                        uids = new int[size];
919                        int i = 0;  // filling out the above arrays
920
921                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
922                            int packageUserId = mPendingBroadcasts.userIdAt(n);
923                            Iterator<Map.Entry<String, ArrayList<String>>> it
924                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
925                                            .entrySet().iterator();
926                            while (it.hasNext() && i < size) {
927                                Map.Entry<String, ArrayList<String>> ent = it.next();
928                                packages[i] = ent.getKey();
929                                components[i] = ent.getValue();
930                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
931                                uids[i] = (ps != null)
932                                        ? UserHandle.getUid(packageUserId, ps.appId)
933                                        : -1;
934                                i++;
935                            }
936                        }
937                        size = i;
938                        mPendingBroadcasts.clear();
939                    }
940                    // Send broadcasts
941                    for (int i = 0; i < size; i++) {
942                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
943                    }
944                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
945                    break;
946                }
947                case START_CLEANING_PACKAGE: {
948                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
949                    final String packageName = (String)msg.obj;
950                    final int userId = msg.arg1;
951                    final boolean andCode = msg.arg2 != 0;
952                    synchronized (mPackages) {
953                        if (userId == UserHandle.USER_ALL) {
954                            int[] users = sUserManager.getUserIds();
955                            for (int user : users) {
956                                mSettings.addPackageToCleanLPw(
957                                        new PackageCleanItem(user, packageName, andCode));
958                            }
959                        } else {
960                            mSettings.addPackageToCleanLPw(
961                                    new PackageCleanItem(userId, packageName, andCode));
962                        }
963                    }
964                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
965                    startCleaningPackages();
966                } break;
967                case POST_INSTALL: {
968                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
969                    PostInstallData data = mRunningInstalls.get(msg.arg1);
970                    mRunningInstalls.delete(msg.arg1);
971                    boolean deleteOld = false;
972
973                    if (data != null) {
974                        InstallArgs args = data.args;
975                        PackageInstalledInfo res = data.res;
976
977                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
978                            res.removedInfo.sendBroadcast(false, true, false);
979                            Bundle extras = new Bundle(1);
980                            extras.putInt(Intent.EXTRA_UID, res.uid);
981                            // Determine the set of users who are adding this
982                            // package for the first time vs. those who are seeing
983                            // an update.
984                            int[] firstUsers;
985                            int[] updateUsers = new int[0];
986                            if (res.origUsers == null || res.origUsers.length == 0) {
987                                firstUsers = res.newUsers;
988                            } else {
989                                firstUsers = new int[0];
990                                for (int i=0; i<res.newUsers.length; i++) {
991                                    int user = res.newUsers[i];
992                                    boolean isNew = true;
993                                    for (int j=0; j<res.origUsers.length; j++) {
994                                        if (res.origUsers[j] == user) {
995                                            isNew = false;
996                                            break;
997                                        }
998                                    }
999                                    if (isNew) {
1000                                        int[] newFirst = new int[firstUsers.length+1];
1001                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1002                                                firstUsers.length);
1003                                        newFirst[firstUsers.length] = user;
1004                                        firstUsers = newFirst;
1005                                    } else {
1006                                        int[] newUpdate = new int[updateUsers.length+1];
1007                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1008                                                updateUsers.length);
1009                                        newUpdate[updateUsers.length] = user;
1010                                        updateUsers = newUpdate;
1011                                    }
1012                                }
1013                            }
1014                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1015                                    res.pkg.applicationInfo.packageName,
1016                                    extras, null, null, firstUsers);
1017                            final boolean update = res.removedInfo.removedPackage != null;
1018                            if (update) {
1019                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1020                            }
1021                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1022                                    res.pkg.applicationInfo.packageName,
1023                                    extras, null, null, updateUsers);
1024                            if (update) {
1025                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1026                                        res.pkg.applicationInfo.packageName,
1027                                        extras, null, null, updateUsers);
1028                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1029                                        null, null,
1030                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1031
1032                                // treat asec-hosted packages like removable media on upgrade
1033                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1034                                    if (DEBUG_INSTALL) {
1035                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1036                                                + " is ASEC-hosted -> AVAILABLE");
1037                                    }
1038                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1039                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1040                                    pkgList.add(res.pkg.applicationInfo.packageName);
1041                                    sendResourcesChangedBroadcast(true, true,
1042                                            pkgList,uidArray, null);
1043                                }
1044                            }
1045                            if (res.removedInfo.args != null) {
1046                                // Remove the replaced package's older resources safely now
1047                                deleteOld = true;
1048                            }
1049
1050                            // Log current value of "unknown sources" setting
1051                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1052                                getUnknownSourcesSettings());
1053                        }
1054                        // Force a gc to clear up things
1055                        Runtime.getRuntime().gc();
1056                        // We delete after a gc for applications  on sdcard.
1057                        if (deleteOld) {
1058                            synchronized (mInstallLock) {
1059                                res.removedInfo.args.doPostDeleteLI(true);
1060                            }
1061                        }
1062                        if (args.observer != null) {
1063                            try {
1064                                args.observer.packageInstalled(res.name, res.returnCode);
1065                            } catch (RemoteException e) {
1066                                Slog.i(TAG, "Observer no longer exists.");
1067                            }
1068                        }
1069                        if (args.observer2 != null) {
1070                            try {
1071                                Bundle extras = extrasForInstallResult(res);
1072                                args.observer2.packageInstalled(res.name, extras, res.returnCode);
1073                            } catch (RemoteException e) {
1074                                Slog.i(TAG, "Observer no longer exists.");
1075                            }
1076                        }
1077                    } else {
1078                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1079                    }
1080                } break;
1081                case UPDATED_MEDIA_STATUS: {
1082                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1083                    boolean reportStatus = msg.arg1 == 1;
1084                    boolean doGc = msg.arg2 == 1;
1085                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1086                    if (doGc) {
1087                        // Force a gc to clear up stale containers.
1088                        Runtime.getRuntime().gc();
1089                    }
1090                    if (msg.obj != null) {
1091                        @SuppressWarnings("unchecked")
1092                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1093                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1094                        // Unload containers
1095                        unloadAllContainers(args);
1096                    }
1097                    if (reportStatus) {
1098                        try {
1099                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1100                            PackageHelper.getMountService().finishMediaUpdate();
1101                        } catch (RemoteException e) {
1102                            Log.e(TAG, "MountService not running?");
1103                        }
1104                    }
1105                } break;
1106                case WRITE_SETTINGS: {
1107                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1108                    synchronized (mPackages) {
1109                        removeMessages(WRITE_SETTINGS);
1110                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1111                        mSettings.writeLPr();
1112                        mDirtyUsers.clear();
1113                    }
1114                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1115                } break;
1116                case WRITE_PACKAGE_RESTRICTIONS: {
1117                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1118                    synchronized (mPackages) {
1119                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1120                        for (int userId : mDirtyUsers) {
1121                            mSettings.writePackageRestrictionsLPr(userId);
1122                        }
1123                        mDirtyUsers.clear();
1124                    }
1125                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1126                } break;
1127                case CHECK_PENDING_VERIFICATION: {
1128                    final int verificationId = msg.arg1;
1129                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1130
1131                    if ((state != null) && !state.timeoutExtended()) {
1132                        final InstallArgs args = state.getInstallArgs();
1133                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
1134                        mPendingVerification.remove(verificationId);
1135
1136                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1137
1138                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1139                            Slog.i(TAG, "Continuing with installation of "
1140                                    + args.packageURI.toString());
1141                            state.setVerifierResponse(Binder.getCallingUid(),
1142                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1143                            broadcastPackageVerified(verificationId, args.packageURI,
1144                                    PackageManager.VERIFICATION_ALLOW,
1145                                    state.getInstallArgs().getUser());
1146                            try {
1147                                ret = args.copyApk(mContainerService, true);
1148                            } catch (RemoteException e) {
1149                                Slog.e(TAG, "Could not contact the ContainerService");
1150                            }
1151                        } else {
1152                            broadcastPackageVerified(verificationId, args.packageURI,
1153                                    PackageManager.VERIFICATION_REJECT,
1154                                    state.getInstallArgs().getUser());
1155                        }
1156
1157                        processPendingInstall(args, ret);
1158                        mHandler.sendEmptyMessage(MCS_UNBIND);
1159                    }
1160                    break;
1161                }
1162                case PACKAGE_VERIFIED: {
1163                    final int verificationId = msg.arg1;
1164
1165                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1166                    if (state == null) {
1167                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1168                        break;
1169                    }
1170
1171                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1172
1173                    state.setVerifierResponse(response.callerUid, response.code);
1174
1175                    if (state.isVerificationComplete()) {
1176                        mPendingVerification.remove(verificationId);
1177
1178                        final InstallArgs args = state.getInstallArgs();
1179
1180                        int ret;
1181                        if (state.isInstallAllowed()) {
1182                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1183                            broadcastPackageVerified(verificationId, args.packageURI,
1184                                    response.code, state.getInstallArgs().getUser());
1185                            try {
1186                                ret = args.copyApk(mContainerService, true);
1187                            } catch (RemoteException e) {
1188                                Slog.e(TAG, "Could not contact the ContainerService");
1189                            }
1190                        } else {
1191                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1192                        }
1193
1194                        processPendingInstall(args, ret);
1195
1196                        mHandler.sendEmptyMessage(MCS_UNBIND);
1197                    }
1198
1199                    break;
1200                }
1201            }
1202        }
1203    }
1204
1205    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1206        Bundle extras = null;
1207        switch (res.returnCode) {
1208            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1209                extras = new Bundle();
1210                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1211                        res.origPermission);
1212                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1213                        res.origPackage);
1214                break;
1215            }
1216        }
1217        return extras;
1218    }
1219
1220    void scheduleWriteSettingsLocked() {
1221        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1222            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1223        }
1224    }
1225
1226    void scheduleWritePackageRestrictionsLocked(int userId) {
1227        if (!sUserManager.exists(userId)) return;
1228        mDirtyUsers.add(userId);
1229        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1230            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1231        }
1232    }
1233
1234    public static final IPackageManager main(Context context, Installer installer,
1235            boolean factoryTest, boolean onlyCore) {
1236        PackageManagerService m = new PackageManagerService(context, installer,
1237                factoryTest, onlyCore);
1238        ServiceManager.addService("package", m);
1239        return m;
1240    }
1241
1242    static String[] splitString(String str, char sep) {
1243        int count = 1;
1244        int i = 0;
1245        while ((i=str.indexOf(sep, i)) >= 0) {
1246            count++;
1247            i++;
1248        }
1249
1250        String[] res = new String[count];
1251        i=0;
1252        count = 0;
1253        int lastI=0;
1254        while ((i=str.indexOf(sep, i)) >= 0) {
1255            res[count] = str.substring(lastI, i);
1256            count++;
1257            i++;
1258            lastI = i;
1259        }
1260        res[count] = str.substring(lastI, str.length());
1261        return res;
1262    }
1263
1264    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1265        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1266                Context.DISPLAY_SERVICE);
1267        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1268    }
1269
1270    public PackageManagerService(Context context, Installer installer,
1271            boolean factoryTest, boolean onlyCore) {
1272        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1273                SystemClock.uptimeMillis());
1274
1275        if (mSdkVersion <= 0) {
1276            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1277        }
1278
1279        mContext = context;
1280        mFactoryTest = factoryTest;
1281        mOnlyCore = onlyCore;
1282        mMetrics = new DisplayMetrics();
1283        mSettings = new Settings(context);
1284        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1285                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1286        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1287                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1288        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1289                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1290        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1291                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1292        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1293                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1294        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1295                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1296
1297        String separateProcesses = SystemProperties.get("debug.separate_processes");
1298        if (separateProcesses != null && separateProcesses.length() > 0) {
1299            if ("*".equals(separateProcesses)) {
1300                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1301                mSeparateProcesses = null;
1302                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1303            } else {
1304                mDefParseFlags = 0;
1305                mSeparateProcesses = separateProcesses.split(",");
1306                Slog.w(TAG, "Running with debug.separate_processes: "
1307                        + separateProcesses);
1308            }
1309        } else {
1310            mDefParseFlags = 0;
1311            mSeparateProcesses = null;
1312        }
1313
1314        mInstaller = installer;
1315
1316        getDefaultDisplayMetrics(context, mMetrics);
1317
1318        synchronized (mInstallLock) {
1319        // writer
1320        synchronized (mPackages) {
1321            mHandlerThread = new ServiceThread(TAG,
1322                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1323            mHandlerThread.start();
1324            mHandler = new PackageHandler(mHandlerThread.getLooper());
1325            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1326
1327            File dataDir = Environment.getDataDirectory();
1328            mAppDataDir = new File(dataDir, "data");
1329            mAppInstallDir = new File(dataDir, "app");
1330            mAppLibInstallDir = new File(dataDir, "app-lib");
1331            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1332            mUserAppDataDir = new File(dataDir, "user");
1333            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1334
1335            sUserManager = new UserManagerService(context, this,
1336                    mInstallLock, mPackages);
1337
1338            // Read permissions and features from system
1339            readPermissions(Environment.buildPath(
1340                    Environment.getRootDirectory(), "etc", "permissions"), false);
1341            // Only read features from OEM
1342            readPermissions(Environment.buildPath(
1343                    Environment.getOemDirectory(), "etc", "permissions"), true);
1344
1345            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1346
1347            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1348                    mSdkVersion, mOnlyCore);
1349
1350            String customResolverActivity = Resources.getSystem().getString(
1351                    R.string.config_customResolverActivity);
1352            if (TextUtils.isEmpty(customResolverActivity)) {
1353                customResolverActivity = null;
1354            } else {
1355                mCustomResolverComponentName = ComponentName.unflattenFromString(
1356                        customResolverActivity);
1357            }
1358
1359            long startTime = SystemClock.uptimeMillis();
1360
1361            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1362                    startTime);
1363
1364            // Set flag to monitor and not change apk file paths when
1365            // scanning install directories.
1366            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1367
1368            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1369
1370            /**
1371             * Add everything in the in the boot class path to the
1372             * list of process files because dexopt will have been run
1373             * if necessary during zygote startup.
1374             */
1375            String bootClassPath = System.getProperty("java.boot.class.path");
1376            if (bootClassPath != null) {
1377                String[] paths = splitString(bootClassPath, ':');
1378                for (int i=0; i<paths.length; i++) {
1379                    alreadyDexOpted.add(paths[i]);
1380                }
1381            } else {
1382                Slog.w(TAG, "No BOOTCLASSPATH found!");
1383            }
1384
1385            boolean didDexOptLibraryOrTool = false;
1386
1387            final List<String> instructionSets = getAllInstructionSets();
1388
1389            /**
1390             * Ensure all external libraries have had dexopt run on them.
1391             */
1392            if (mSharedLibraries.size() > 0) {
1393                // NOTE: For now, we're compiling these system "shared libraries"
1394                // (and framework jars) into all available architectures. It's possible
1395                // to compile them only when we come across an app that uses them (there's
1396                // already logic for that in scanPackageLI) but that adds some complexity.
1397                for (String instructionSet : instructionSets) {
1398                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1399                        final String lib = libEntry.path;
1400                        if (lib == null) {
1401                            continue;
1402                        }
1403
1404                        try {
1405                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1406                                alreadyDexOpted.add(lib);
1407
1408                                // The list of "shared libraries" we have at this point is
1409                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1410                                didDexOptLibraryOrTool = true;
1411                            }
1412                        } catch (FileNotFoundException e) {
1413                            Slog.w(TAG, "Library not found: " + lib);
1414                        } catch (IOException e) {
1415                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1416                                    + e.getMessage());
1417                        }
1418                    }
1419                }
1420            }
1421
1422            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1423
1424            // Gross hack for now: we know this file doesn't contain any
1425            // code, so don't dexopt it to avoid the resulting log spew.
1426            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1427
1428            // Gross hack for now: we know this file is only part of
1429            // the boot class path for art, so don't dexopt it to
1430            // avoid the resulting log spew.
1431            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1432
1433            /**
1434             * And there are a number of commands implemented in Java, which
1435             * we currently need to do the dexopt on so that they can be
1436             * run from a non-root shell.
1437             */
1438            String[] frameworkFiles = frameworkDir.list();
1439            if (frameworkFiles != null) {
1440                // TODO: We could compile these only for the most preferred ABI. We should
1441                // first double check that the dex files for these commands are not referenced
1442                // by other system apps.
1443                for (String instructionSet : instructionSets) {
1444                    for (int i=0; i<frameworkFiles.length; i++) {
1445                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1446                        String path = libPath.getPath();
1447                        // Skip the file if we already did it.
1448                        if (alreadyDexOpted.contains(path)) {
1449                            continue;
1450                        }
1451                        // Skip the file if it is not a type we want to dexopt.
1452                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1453                            continue;
1454                        }
1455                        try {
1456                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1457                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1458                                didDexOptLibraryOrTool = true;
1459                            }
1460                        } catch (FileNotFoundException e) {
1461                            Slog.w(TAG, "Jar not found: " + path);
1462                        } catch (IOException e) {
1463                            Slog.w(TAG, "Exception reading jar: " + path, e);
1464                        }
1465                    }
1466                }
1467            }
1468
1469            if (didDexOptLibraryOrTool) {
1470                pruneDexFiles(new File(dataDir, "dalvik-cache"));
1471            }
1472
1473            // Collect vendor overlay packages.
1474            // (Do this before scanning any apps.)
1475            // For security and version matching reason, only consider
1476            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1477            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1478            mVendorOverlayInstallObserver = new AppDirObserver(
1479                vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1480            mVendorOverlayInstallObserver.startWatching();
1481            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1482                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1483
1484            // Find base frameworks (resource packages without code).
1485            mFrameworkInstallObserver = new AppDirObserver(
1486                frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1487            mFrameworkInstallObserver.startWatching();
1488            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1489                    | PackageParser.PARSE_IS_SYSTEM_DIR
1490                    | PackageParser.PARSE_IS_PRIVILEGED,
1491                    scanMode | SCAN_NO_DEX, 0);
1492
1493            // Collected privileged system packages.
1494            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1495            mPrivilegedInstallObserver = new AppDirObserver(
1496                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1497            mPrivilegedInstallObserver.startWatching();
1498                scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1499                        | PackageParser.PARSE_IS_SYSTEM_DIR
1500                        | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1501
1502            // Collect ordinary system packages.
1503            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1504            mSystemInstallObserver = new AppDirObserver(
1505                systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1506            mSystemInstallObserver.startWatching();
1507            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1508                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1509
1510            // Collect all vendor packages.
1511            File vendorAppDir = new File("/vendor/app");
1512            try {
1513                vendorAppDir = vendorAppDir.getCanonicalFile();
1514            } catch (IOException e) {
1515                // failed to look up canonical path, continue with original one
1516            }
1517            mVendorInstallObserver = new AppDirObserver(
1518                vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1519            mVendorInstallObserver.startWatching();
1520            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1521                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1522
1523            // Collect all OEM packages.
1524            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1525            mOemInstallObserver = new AppDirObserver(
1526                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1527            mOemInstallObserver.startWatching();
1528            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1529                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1530
1531            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1532            mInstaller.moveFiles();
1533
1534            // Prune any system packages that no longer exist.
1535            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1536            if (!mOnlyCore) {
1537                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1538                while (psit.hasNext()) {
1539                    PackageSetting ps = psit.next();
1540
1541                    /*
1542                     * If this is not a system app, it can't be a
1543                     * disable system app.
1544                     */
1545                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1546                        continue;
1547                    }
1548
1549                    /*
1550                     * If the package is scanned, it's not erased.
1551                     */
1552                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1553                    if (scannedPkg != null) {
1554                        /*
1555                         * If the system app is both scanned and in the
1556                         * disabled packages list, then it must have been
1557                         * added via OTA. Remove it from the currently
1558                         * scanned package so the previously user-installed
1559                         * application can be scanned.
1560                         */
1561                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1562                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1563                                    + "; removing system app");
1564                            removePackageLI(ps, true);
1565                        }
1566
1567                        continue;
1568                    }
1569
1570                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1571                        psit.remove();
1572                        String msg = "System package " + ps.name
1573                                + " no longer exists; wiping its data";
1574                        reportSettingsProblem(Log.WARN, msg);
1575                        removeDataDirsLI(ps.name);
1576                    } else {
1577                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1578                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1579                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1580                        }
1581                    }
1582                }
1583            }
1584
1585            //look for any incomplete package installations
1586            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1587            //clean up list
1588            for(int i = 0; i < deletePkgsList.size(); i++) {
1589                //clean up here
1590                cleanupInstallFailedPackage(deletePkgsList.get(i));
1591            }
1592            //delete tmp files
1593            deleteTempPackageFiles();
1594
1595            // Remove any shared userIDs that have no associated packages
1596            mSettings.pruneSharedUsersLPw();
1597
1598            if (!mOnlyCore) {
1599                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1600                        SystemClock.uptimeMillis());
1601                mAppInstallObserver = new AppDirObserver(
1602                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1603                mAppInstallObserver.startWatching();
1604                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1605
1606                mDrmAppInstallObserver = new AppDirObserver(
1607                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1608                mDrmAppInstallObserver.startWatching();
1609                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1610                        scanMode, 0);
1611
1612                /**
1613                 * Remove disable package settings for any updated system
1614                 * apps that were removed via an OTA. If they're not a
1615                 * previously-updated app, remove them completely.
1616                 * Otherwise, just revoke their system-level permissions.
1617                 */
1618                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1619                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1620                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1621
1622                    String msg;
1623                    if (deletedPkg == null) {
1624                        msg = "Updated system package " + deletedAppName
1625                                + " no longer exists; wiping its data";
1626                        removeDataDirsLI(deletedAppName);
1627                    } else {
1628                        msg = "Updated system app + " + deletedAppName
1629                                + " no longer present; removing system privileges for "
1630                                + deletedAppName;
1631
1632                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1633
1634                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1635                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1636                    }
1637                    reportSettingsProblem(Log.WARN, msg);
1638                }
1639            } else {
1640                mAppInstallObserver = null;
1641                mDrmAppInstallObserver = null;
1642            }
1643
1644            // Now that we know all of the shared libraries, update all clients to have
1645            // the correct library paths.
1646            updateAllSharedLibrariesLPw();
1647
1648            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1649                adjustCpuAbisForSharedUserLPw(setting.packages, true /* do dexopt */,
1650                        false /* force dexopt */, false /* defer dexopt */);
1651            }
1652
1653            // Now that we know all the packages we are keeping,
1654            // read and update their last usage times.
1655            mPackageUsage.readLP();
1656
1657            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1658                    SystemClock.uptimeMillis());
1659            Slog.i(TAG, "Time to scan packages: "
1660                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1661                    + " seconds");
1662
1663            // If the platform SDK has changed since the last time we booted,
1664            // we need to re-grant app permission to catch any new ones that
1665            // appear.  This is really a hack, and means that apps can in some
1666            // cases get permissions that the user didn't initially explicitly
1667            // allow...  it would be nice to have some better way to handle
1668            // this situation.
1669            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1670                    != mSdkVersion;
1671            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1672                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1673                    + "; regranting permissions for internal storage");
1674            mSettings.mInternalSdkPlatform = mSdkVersion;
1675
1676            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1677                    | (regrantPermissions
1678                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1679                            : 0));
1680
1681            // If this is the first boot, and it is a normal boot, then
1682            // we need to initialize the default preferred apps.
1683            if (!mRestoredSettings && !onlyCore) {
1684                mSettings.readDefaultPreferredAppsLPw(this, 0);
1685            }
1686
1687            // All the changes are done during package scanning.
1688            mSettings.updateInternalDatabaseVersion();
1689
1690            // can downgrade to reader
1691            mSettings.writeLPr();
1692
1693            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1694                    SystemClock.uptimeMillis());
1695
1696            // Now after opening every single application zip, make sure they
1697            // are all flushed.  Not really needed, but keeps things nice and
1698            // tidy.
1699            Runtime.getRuntime().gc();
1700
1701            mRequiredVerifierPackage = getRequiredVerifierLPr();
1702        } // synchronized (mPackages)
1703        } // synchronized (mInstallLock)
1704    }
1705
1706    private static void pruneDexFiles(File cacheDir) {
1707        // If we had to do a dexopt of one of the previous
1708        // things, then something on the system has changed.
1709        // Consider this significant, and wipe away all other
1710        // existing dexopt files to ensure we don't leave any
1711        // dangling around.
1712        //
1713        // Additionally, delete all dex files from the root directory
1714        // since there shouldn't be any there anyway.
1715        //
1716        // Note: This isn't as good an indicator as it used to be. It
1717        // used to include the boot classpath but at some point
1718        // DexFile.isDexOptNeeded started returning false for the boot
1719        // class path files in all cases. It is very possible in a
1720        // small maintenance release update that the library and tool
1721        // jars may be unchanged but APK could be removed resulting in
1722        // unused dalvik-cache files.
1723        File[] files = cacheDir.listFiles();
1724        if (files != null) {
1725            for (File file : files) {
1726                if (!file.isDirectory()) {
1727                    Slog.i(TAG, "Pruning dalvik file: " + file.getAbsolutePath());
1728                    file.delete();
1729                } else {
1730                    File[] subDirList = file.listFiles();
1731                    if (subDirList != null) {
1732                        for (File subDirFile : subDirList) {
1733                            final String fn = subDirFile.getName();
1734                            if (fn.startsWith("data@app@") || fn.startsWith("data@app-private@")) {
1735                                Slog.i(TAG, "Pruning dalvik file: " + fn);
1736                                subDirFile.delete();
1737                            }
1738                        }
1739                    }
1740                }
1741            }
1742        }
1743    }
1744
1745    public boolean isFirstBoot() {
1746        return !mRestoredSettings;
1747    }
1748
1749    public boolean isOnlyCoreApps() {
1750        return mOnlyCore;
1751    }
1752
1753    private String getRequiredVerifierLPr() {
1754        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1755        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1756                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1757
1758        String requiredVerifier = null;
1759
1760        final int N = receivers.size();
1761        for (int i = 0; i < N; i++) {
1762            final ResolveInfo info = receivers.get(i);
1763
1764            if (info.activityInfo == null) {
1765                continue;
1766            }
1767
1768            final String packageName = info.activityInfo.packageName;
1769
1770            final PackageSetting ps = mSettings.mPackages.get(packageName);
1771            if (ps == null) {
1772                continue;
1773            }
1774
1775            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1776            if (!gp.grantedPermissions
1777                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1778                continue;
1779            }
1780
1781            if (requiredVerifier != null) {
1782                throw new RuntimeException("There can be only one required verifier");
1783            }
1784
1785            requiredVerifier = packageName;
1786        }
1787
1788        return requiredVerifier;
1789    }
1790
1791    @Override
1792    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1793            throws RemoteException {
1794        try {
1795            return super.onTransact(code, data, reply, flags);
1796        } catch (RuntimeException e) {
1797            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1798                Slog.wtf(TAG, "Package Manager Crash", e);
1799            }
1800            throw e;
1801        }
1802    }
1803
1804    void cleanupInstallFailedPackage(PackageSetting ps) {
1805        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1806        removeDataDirsLI(ps.name);
1807        if (ps.codePath != null) {
1808            if (!ps.codePath.delete()) {
1809                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1810            }
1811        }
1812        if (ps.resourcePath != null) {
1813            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1814                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1815            }
1816        }
1817        mSettings.removePackageLPw(ps.name);
1818    }
1819
1820    void readPermissions(File libraryDir, boolean onlyFeatures) {
1821        // Read permissions from .../etc/permission directory.
1822        if (!libraryDir.exists() || !libraryDir.isDirectory()) {
1823            Slog.w(TAG, "No directory " + libraryDir + ", skipping");
1824            return;
1825        }
1826        if (!libraryDir.canRead()) {
1827            Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
1828            return;
1829        }
1830
1831        // Iterate over the files in the directory and scan .xml files
1832        for (File f : libraryDir.listFiles()) {
1833            // We'll read platform.xml last
1834            if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1835                continue;
1836            }
1837
1838            if (!f.getPath().endsWith(".xml")) {
1839                Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
1840                continue;
1841            }
1842            if (!f.canRead()) {
1843                Slog.w(TAG, "Permissions library file " + f + " cannot be read");
1844                continue;
1845            }
1846
1847            readPermissionsFromXml(f, onlyFeatures);
1848        }
1849
1850        // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1851        final File permFile = new File(Environment.getRootDirectory(),
1852                "etc/permissions/platform.xml");
1853        readPermissionsFromXml(permFile, onlyFeatures);
1854    }
1855
1856    private void readPermissionsFromXml(File permFile, boolean onlyFeatures) {
1857        FileReader permReader = null;
1858        try {
1859            permReader = new FileReader(permFile);
1860        } catch (FileNotFoundException e) {
1861            Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
1862            return;
1863        }
1864
1865        try {
1866            XmlPullParser parser = Xml.newPullParser();
1867            parser.setInput(permReader);
1868
1869            XmlUtils.beginDocument(parser, "permissions");
1870
1871            while (true) {
1872                XmlUtils.nextElement(parser);
1873                if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1874                    break;
1875                }
1876
1877                String name = parser.getName();
1878                if ("group".equals(name) && !onlyFeatures) {
1879                    String gidStr = parser.getAttributeValue(null, "gid");
1880                    if (gidStr != null) {
1881                        int gid = Process.getGidForName(gidStr);
1882                        mGlobalGids = appendInt(mGlobalGids, gid);
1883                    } else {
1884                        Slog.w(TAG, "<group> without gid at "
1885                                + parser.getPositionDescription());
1886                    }
1887
1888                    XmlUtils.skipCurrentTag(parser);
1889                    continue;
1890                } else if ("permission".equals(name) && !onlyFeatures) {
1891                    String perm = parser.getAttributeValue(null, "name");
1892                    if (perm == null) {
1893                        Slog.w(TAG, "<permission> without name at "
1894                                + parser.getPositionDescription());
1895                        XmlUtils.skipCurrentTag(parser);
1896                        continue;
1897                    }
1898                    perm = perm.intern();
1899                    readPermission(parser, perm);
1900
1901                } else if ("assign-permission".equals(name) && !onlyFeatures) {
1902                    String perm = parser.getAttributeValue(null, "name");
1903                    if (perm == null) {
1904                        Slog.w(TAG, "<assign-permission> without name at "
1905                                + parser.getPositionDescription());
1906                        XmlUtils.skipCurrentTag(parser);
1907                        continue;
1908                    }
1909                    String uidStr = parser.getAttributeValue(null, "uid");
1910                    if (uidStr == null) {
1911                        Slog.w(TAG, "<assign-permission> without uid at "
1912                                + parser.getPositionDescription());
1913                        XmlUtils.skipCurrentTag(parser);
1914                        continue;
1915                    }
1916                    int uid = Process.getUidForName(uidStr);
1917                    if (uid < 0) {
1918                        Slog.w(TAG, "<assign-permission> with unknown uid \""
1919                                + uidStr + "\" at "
1920                                + parser.getPositionDescription());
1921                        XmlUtils.skipCurrentTag(parser);
1922                        continue;
1923                    }
1924                    perm = perm.intern();
1925                    HashSet<String> perms = mSystemPermissions.get(uid);
1926                    if (perms == null) {
1927                        perms = new HashSet<String>();
1928                        mSystemPermissions.put(uid, perms);
1929                    }
1930                    perms.add(perm);
1931                    XmlUtils.skipCurrentTag(parser);
1932
1933                } else if ("library".equals(name) && !onlyFeatures) {
1934                    String lname = parser.getAttributeValue(null, "name");
1935                    String lfile = parser.getAttributeValue(null, "file");
1936                    if (lname == null) {
1937                        Slog.w(TAG, "<library> without name at "
1938                                + parser.getPositionDescription());
1939                    } else if (lfile == null) {
1940                        Slog.w(TAG, "<library> without file at "
1941                                + parser.getPositionDescription());
1942                    } else {
1943                        //Log.i(TAG, "Got library " + lname + " in " + lfile);
1944                        mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null));
1945                    }
1946                    XmlUtils.skipCurrentTag(parser);
1947                    continue;
1948
1949                } else if ("feature".equals(name)) {
1950                    String fname = parser.getAttributeValue(null, "name");
1951                    if (fname == null) {
1952                        Slog.w(TAG, "<feature> without name at "
1953                                + parser.getPositionDescription());
1954                    } else {
1955                        //Log.i(TAG, "Got feature " + fname);
1956                        FeatureInfo fi = new FeatureInfo();
1957                        fi.name = fname;
1958                        mAvailableFeatures.put(fname, fi);
1959                    }
1960                    XmlUtils.skipCurrentTag(parser);
1961                    continue;
1962
1963                } else {
1964                    XmlUtils.skipCurrentTag(parser);
1965                    continue;
1966                }
1967
1968            }
1969            permReader.close();
1970        } catch (XmlPullParserException e) {
1971            Slog.w(TAG, "Got execption parsing permissions.", e);
1972        } catch (IOException e) {
1973            Slog.w(TAG, "Got execption parsing permissions.", e);
1974        }
1975    }
1976
1977    void readPermission(XmlPullParser parser, String name)
1978            throws IOException, XmlPullParserException {
1979
1980        name = name.intern();
1981
1982        BasePermission bp = mSettings.mPermissions.get(name);
1983        if (bp == null) {
1984            bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1985            mSettings.mPermissions.put(name, bp);
1986        }
1987        int outerDepth = parser.getDepth();
1988        int type;
1989        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1990               && (type != XmlPullParser.END_TAG
1991                       || parser.getDepth() > outerDepth)) {
1992            if (type == XmlPullParser.END_TAG
1993                    || type == XmlPullParser.TEXT) {
1994                continue;
1995            }
1996
1997            String tagName = parser.getName();
1998            if ("group".equals(tagName)) {
1999                String gidStr = parser.getAttributeValue(null, "gid");
2000                if (gidStr != null) {
2001                    int gid = Process.getGidForName(gidStr);
2002                    bp.gids = appendInt(bp.gids, gid);
2003                } else {
2004                    Slog.w(TAG, "<group> without gid at "
2005                            + parser.getPositionDescription());
2006                }
2007            }
2008            XmlUtils.skipCurrentTag(parser);
2009        }
2010    }
2011
2012    static int[] appendInts(int[] cur, int[] add) {
2013        if (add == null) return cur;
2014        if (cur == null) return add;
2015        final int N = add.length;
2016        for (int i=0; i<N; i++) {
2017            cur = appendInt(cur, add[i]);
2018        }
2019        return cur;
2020    }
2021
2022    static int[] removeInts(int[] cur, int[] rem) {
2023        if (rem == null) return cur;
2024        if (cur == null) return cur;
2025        final int N = rem.length;
2026        for (int i=0; i<N; i++) {
2027            cur = removeInt(cur, rem[i]);
2028        }
2029        return cur;
2030    }
2031
2032    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2033        if (!sUserManager.exists(userId)) return null;
2034        final PackageSetting ps = (PackageSetting) p.mExtras;
2035        if (ps == null) {
2036            return null;
2037        }
2038        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2039        final PackageUserState state = ps.readUserState(userId);
2040        return PackageParser.generatePackageInfo(p, gp.gids, flags,
2041                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
2042                state, userId);
2043    }
2044
2045    public boolean isPackageAvailable(String packageName, int userId) {
2046        if (!sUserManager.exists(userId)) return false;
2047        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
2048        synchronized (mPackages) {
2049            PackageParser.Package p = mPackages.get(packageName);
2050            if (p != null) {
2051                final PackageSetting ps = (PackageSetting) p.mExtras;
2052                if (ps != null) {
2053                    final PackageUserState state = ps.readUserState(userId);
2054                    if (state != null) {
2055                        return PackageParser.isAvailable(state);
2056                    }
2057                }
2058            }
2059        }
2060        return false;
2061    }
2062
2063    @Override
2064    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2065        if (!sUserManager.exists(userId)) return null;
2066        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
2067        // reader
2068        synchronized (mPackages) {
2069            PackageParser.Package p = mPackages.get(packageName);
2070            if (DEBUG_PACKAGE_INFO)
2071                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2072            if (p != null) {
2073                return generatePackageInfo(p, flags, userId);
2074            }
2075            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2076                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2077            }
2078        }
2079        return null;
2080    }
2081
2082    public String[] currentToCanonicalPackageNames(String[] names) {
2083        String[] out = new String[names.length];
2084        // reader
2085        synchronized (mPackages) {
2086            for (int i=names.length-1; i>=0; i--) {
2087                PackageSetting ps = mSettings.mPackages.get(names[i]);
2088                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2089            }
2090        }
2091        return out;
2092    }
2093
2094    public String[] canonicalToCurrentPackageNames(String[] names) {
2095        String[] out = new String[names.length];
2096        // reader
2097        synchronized (mPackages) {
2098            for (int i=names.length-1; i>=0; i--) {
2099                String cur = mSettings.mRenamedPackages.get(names[i]);
2100                out[i] = cur != null ? cur : names[i];
2101            }
2102        }
2103        return out;
2104    }
2105
2106    @Override
2107    public int getPackageUid(String packageName, int userId) {
2108        if (!sUserManager.exists(userId)) return -1;
2109        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
2110        // reader
2111        synchronized (mPackages) {
2112            PackageParser.Package p = mPackages.get(packageName);
2113            if(p != null) {
2114                return UserHandle.getUid(userId, p.applicationInfo.uid);
2115            }
2116            PackageSetting ps = mSettings.mPackages.get(packageName);
2117            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2118                return -1;
2119            }
2120            p = ps.pkg;
2121            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2122        }
2123    }
2124
2125    @Override
2126    public int[] getPackageGids(String packageName) {
2127        // reader
2128        synchronized (mPackages) {
2129            PackageParser.Package p = mPackages.get(packageName);
2130            if (DEBUG_PACKAGE_INFO)
2131                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2132            if (p != null) {
2133                final PackageSetting ps = (PackageSetting)p.mExtras;
2134                return ps.getGids();
2135            }
2136        }
2137        // stupid thing to indicate an error.
2138        return new int[0];
2139    }
2140
2141    static final PermissionInfo generatePermissionInfo(
2142            BasePermission bp, int flags) {
2143        if (bp.perm != null) {
2144            return PackageParser.generatePermissionInfo(bp.perm, flags);
2145        }
2146        PermissionInfo pi = new PermissionInfo();
2147        pi.name = bp.name;
2148        pi.packageName = bp.sourcePackage;
2149        pi.nonLocalizedLabel = bp.name;
2150        pi.protectionLevel = bp.protectionLevel;
2151        return pi;
2152    }
2153
2154    public PermissionInfo getPermissionInfo(String name, int flags) {
2155        // reader
2156        synchronized (mPackages) {
2157            final BasePermission p = mSettings.mPermissions.get(name);
2158            if (p != null) {
2159                return generatePermissionInfo(p, flags);
2160            }
2161            return null;
2162        }
2163    }
2164
2165    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2166        // reader
2167        synchronized (mPackages) {
2168            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2169            for (BasePermission p : mSettings.mPermissions.values()) {
2170                if (group == null) {
2171                    if (p.perm == null || p.perm.info.group == null) {
2172                        out.add(generatePermissionInfo(p, flags));
2173                    }
2174                } else {
2175                    if (p.perm != null && group.equals(p.perm.info.group)) {
2176                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2177                    }
2178                }
2179            }
2180
2181            if (out.size() > 0) {
2182                return out;
2183            }
2184            return mPermissionGroups.containsKey(group) ? out : null;
2185        }
2186    }
2187
2188    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2189        // reader
2190        synchronized (mPackages) {
2191            return PackageParser.generatePermissionGroupInfo(
2192                    mPermissionGroups.get(name), flags);
2193        }
2194    }
2195
2196    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2197        // reader
2198        synchronized (mPackages) {
2199            final int N = mPermissionGroups.size();
2200            ArrayList<PermissionGroupInfo> out
2201                    = new ArrayList<PermissionGroupInfo>(N);
2202            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2203                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2204            }
2205            return out;
2206        }
2207    }
2208
2209    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2210            int userId) {
2211        if (!sUserManager.exists(userId)) return null;
2212        PackageSetting ps = mSettings.mPackages.get(packageName);
2213        if (ps != null) {
2214            if (ps.pkg == null) {
2215                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2216                        flags, userId);
2217                if (pInfo != null) {
2218                    return pInfo.applicationInfo;
2219                }
2220                return null;
2221            }
2222            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2223                    ps.readUserState(userId), userId);
2224        }
2225        return null;
2226    }
2227
2228    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2229            int userId) {
2230        if (!sUserManager.exists(userId)) return null;
2231        PackageSetting ps = mSettings.mPackages.get(packageName);
2232        if (ps != null) {
2233            PackageParser.Package pkg = ps.pkg;
2234            if (pkg == null) {
2235                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2236                    return null;
2237                }
2238                pkg = new PackageParser.Package(packageName);
2239                pkg.applicationInfo.packageName = packageName;
2240                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2241                pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
2242                pkg.applicationInfo.sourceDir = ps.codePathString;
2243                pkg.applicationInfo.dataDir =
2244                        getDataPathForPackage(packageName, 0).getPath();
2245                pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
2246                pkg.applicationInfo.requiredCpuAbi = ps.requiredCpuAbiString;
2247            }
2248            return generatePackageInfo(pkg, flags, userId);
2249        }
2250        return null;
2251    }
2252
2253    @Override
2254    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2255        if (!sUserManager.exists(userId)) return null;
2256        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2257        // writer
2258        synchronized (mPackages) {
2259            PackageParser.Package p = mPackages.get(packageName);
2260            if (DEBUG_PACKAGE_INFO) Log.v(
2261                    TAG, "getApplicationInfo " + packageName
2262                    + ": " + p);
2263            if (p != null) {
2264                PackageSetting ps = mSettings.mPackages.get(packageName);
2265                if (ps == null) return null;
2266                // Note: isEnabledLP() does not apply here - always return info
2267                return PackageParser.generateApplicationInfo(
2268                        p, flags, ps.readUserState(userId), userId);
2269            }
2270            if ("android".equals(packageName)||"system".equals(packageName)) {
2271                return mAndroidApplication;
2272            }
2273            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2274                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2275            }
2276        }
2277        return null;
2278    }
2279
2280
2281    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2282        mContext.enforceCallingOrSelfPermission(
2283                android.Manifest.permission.CLEAR_APP_CACHE, null);
2284        // Queue up an async operation since clearing cache may take a little while.
2285        mHandler.post(new Runnable() {
2286            public void run() {
2287                mHandler.removeCallbacks(this);
2288                int retCode = -1;
2289                synchronized (mInstallLock) {
2290                    retCode = mInstaller.freeCache(freeStorageSize);
2291                    if (retCode < 0) {
2292                        Slog.w(TAG, "Couldn't clear application caches");
2293                    }
2294                }
2295                if (observer != null) {
2296                    try {
2297                        observer.onRemoveCompleted(null, (retCode >= 0));
2298                    } catch (RemoteException e) {
2299                        Slog.w(TAG, "RemoveException when invoking call back");
2300                    }
2301                }
2302            }
2303        });
2304    }
2305
2306    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2307        mContext.enforceCallingOrSelfPermission(
2308                android.Manifest.permission.CLEAR_APP_CACHE, null);
2309        // Queue up an async operation since clearing cache may take a little while.
2310        mHandler.post(new Runnable() {
2311            public void run() {
2312                mHandler.removeCallbacks(this);
2313                int retCode = -1;
2314                synchronized (mInstallLock) {
2315                    retCode = mInstaller.freeCache(freeStorageSize);
2316                    if (retCode < 0) {
2317                        Slog.w(TAG, "Couldn't clear application caches");
2318                    }
2319                }
2320                if(pi != null) {
2321                    try {
2322                        // Callback via pending intent
2323                        int code = (retCode >= 0) ? 1 : 0;
2324                        pi.sendIntent(null, code, null,
2325                                null, null);
2326                    } catch (SendIntentException e1) {
2327                        Slog.i(TAG, "Failed to send pending intent");
2328                    }
2329                }
2330            }
2331        });
2332    }
2333
2334    @Override
2335    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2336        if (!sUserManager.exists(userId)) return null;
2337        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2338        synchronized (mPackages) {
2339            PackageParser.Activity a = mActivities.mActivities.get(component);
2340
2341            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2342            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2343                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2344                if (ps == null) return null;
2345                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2346                        userId);
2347            }
2348            if (mResolveComponentName.equals(component)) {
2349                return mResolveActivity;
2350            }
2351        }
2352        return null;
2353    }
2354
2355    @Override
2356    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2357            String resolvedType) {
2358        synchronized (mPackages) {
2359            PackageParser.Activity a = mActivities.mActivities.get(component);
2360            if (a == null) {
2361                return false;
2362            }
2363            for (int i=0; i<a.intents.size(); i++) {
2364                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2365                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2366                    return true;
2367                }
2368            }
2369            return false;
2370        }
2371    }
2372
2373    @Override
2374    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2375        if (!sUserManager.exists(userId)) return null;
2376        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2377        synchronized (mPackages) {
2378            PackageParser.Activity a = mReceivers.mActivities.get(component);
2379            if (DEBUG_PACKAGE_INFO) Log.v(
2380                TAG, "getReceiverInfo " + component + ": " + a);
2381            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2382                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2383                if (ps == null) return null;
2384                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2385                        userId);
2386            }
2387        }
2388        return null;
2389    }
2390
2391    @Override
2392    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2393        if (!sUserManager.exists(userId)) return null;
2394        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2395        synchronized (mPackages) {
2396            PackageParser.Service s = mServices.mServices.get(component);
2397            if (DEBUG_PACKAGE_INFO) Log.v(
2398                TAG, "getServiceInfo " + component + ": " + s);
2399            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2400                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2401                if (ps == null) return null;
2402                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2403                        userId);
2404            }
2405        }
2406        return null;
2407    }
2408
2409    @Override
2410    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2411        if (!sUserManager.exists(userId)) return null;
2412        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2413        synchronized (mPackages) {
2414            PackageParser.Provider p = mProviders.mProviders.get(component);
2415            if (DEBUG_PACKAGE_INFO) Log.v(
2416                TAG, "getProviderInfo " + component + ": " + p);
2417            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2418                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2419                if (ps == null) return null;
2420                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2421                        userId);
2422            }
2423        }
2424        return null;
2425    }
2426
2427    public String[] getSystemSharedLibraryNames() {
2428        Set<String> libSet;
2429        synchronized (mPackages) {
2430            libSet = mSharedLibraries.keySet();
2431            int size = libSet.size();
2432            if (size > 0) {
2433                String[] libs = new String[size];
2434                libSet.toArray(libs);
2435                return libs;
2436            }
2437        }
2438        return null;
2439    }
2440
2441    public FeatureInfo[] getSystemAvailableFeatures() {
2442        Collection<FeatureInfo> featSet;
2443        synchronized (mPackages) {
2444            featSet = mAvailableFeatures.values();
2445            int size = featSet.size();
2446            if (size > 0) {
2447                FeatureInfo[] features = new FeatureInfo[size+1];
2448                featSet.toArray(features);
2449                FeatureInfo fi = new FeatureInfo();
2450                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2451                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2452                features[size] = fi;
2453                return features;
2454            }
2455        }
2456        return null;
2457    }
2458
2459    public boolean hasSystemFeature(String name) {
2460        synchronized (mPackages) {
2461            return mAvailableFeatures.containsKey(name);
2462        }
2463    }
2464
2465    private void checkValidCaller(int uid, int userId) {
2466        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2467            return;
2468
2469        throw new SecurityException("Caller uid=" + uid
2470                + " is not privileged to communicate with user=" + userId);
2471    }
2472
2473    public int checkPermission(String permName, String pkgName) {
2474        synchronized (mPackages) {
2475            PackageParser.Package p = mPackages.get(pkgName);
2476            if (p != null && p.mExtras != null) {
2477                PackageSetting ps = (PackageSetting)p.mExtras;
2478                if (ps.sharedUser != null) {
2479                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2480                        return PackageManager.PERMISSION_GRANTED;
2481                    }
2482                } else if (ps.grantedPermissions.contains(permName)) {
2483                    return PackageManager.PERMISSION_GRANTED;
2484                }
2485            }
2486        }
2487        return PackageManager.PERMISSION_DENIED;
2488    }
2489
2490    public int checkUidPermission(String permName, int uid) {
2491        synchronized (mPackages) {
2492            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2493            if (obj != null) {
2494                GrantedPermissions gp = (GrantedPermissions)obj;
2495                if (gp.grantedPermissions.contains(permName)) {
2496                    return PackageManager.PERMISSION_GRANTED;
2497                }
2498            } else {
2499                HashSet<String> perms = mSystemPermissions.get(uid);
2500                if (perms != null && perms.contains(permName)) {
2501                    return PackageManager.PERMISSION_GRANTED;
2502                }
2503            }
2504        }
2505        return PackageManager.PERMISSION_DENIED;
2506    }
2507
2508    /**
2509     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2510     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2511     * @param message the message to log on security exception
2512     * @return
2513     */
2514    private void enforceCrossUserPermission(int callingUid, int userId,
2515            boolean requireFullPermission, String message) {
2516        if (userId < 0) {
2517            throw new IllegalArgumentException("Invalid userId " + userId);
2518        }
2519        if (userId == UserHandle.getUserId(callingUid)) return;
2520        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2521            if (requireFullPermission) {
2522                mContext.enforceCallingOrSelfPermission(
2523                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2524            } else {
2525                try {
2526                    mContext.enforceCallingOrSelfPermission(
2527                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2528                } catch (SecurityException se) {
2529                    mContext.enforceCallingOrSelfPermission(
2530                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2531                }
2532            }
2533        }
2534    }
2535
2536    private BasePermission findPermissionTreeLP(String permName) {
2537        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2538            if (permName.startsWith(bp.name) &&
2539                    permName.length() > bp.name.length() &&
2540                    permName.charAt(bp.name.length()) == '.') {
2541                return bp;
2542            }
2543        }
2544        return null;
2545    }
2546
2547    private BasePermission checkPermissionTreeLP(String permName) {
2548        if (permName != null) {
2549            BasePermission bp = findPermissionTreeLP(permName);
2550            if (bp != null) {
2551                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2552                    return bp;
2553                }
2554                throw new SecurityException("Calling uid "
2555                        + Binder.getCallingUid()
2556                        + " is not allowed to add to permission tree "
2557                        + bp.name + " owned by uid " + bp.uid);
2558            }
2559        }
2560        throw new SecurityException("No permission tree found for " + permName);
2561    }
2562
2563    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2564        if (s1 == null) {
2565            return s2 == null;
2566        }
2567        if (s2 == null) {
2568            return false;
2569        }
2570        if (s1.getClass() != s2.getClass()) {
2571            return false;
2572        }
2573        return s1.equals(s2);
2574    }
2575
2576    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2577        if (pi1.icon != pi2.icon) return false;
2578        if (pi1.logo != pi2.logo) return false;
2579        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2580        if (!compareStrings(pi1.name, pi2.name)) return false;
2581        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2582        // We'll take care of setting this one.
2583        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2584        // These are not currently stored in settings.
2585        //if (!compareStrings(pi1.group, pi2.group)) return false;
2586        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2587        //if (pi1.labelRes != pi2.labelRes) return false;
2588        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2589        return true;
2590    }
2591
2592    int permissionInfoFootprint(PermissionInfo info) {
2593        int size = info.name.length();
2594        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2595        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2596        return size;
2597    }
2598
2599    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2600        int size = 0;
2601        for (BasePermission perm : mSettings.mPermissions.values()) {
2602            if (perm.uid == tree.uid) {
2603                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2604            }
2605        }
2606        return size;
2607    }
2608
2609    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2610        // We calculate the max size of permissions defined by this uid and throw
2611        // if that plus the size of 'info' would exceed our stated maximum.
2612        if (tree.uid != Process.SYSTEM_UID) {
2613            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2614            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2615                throw new SecurityException("Permission tree size cap exceeded");
2616            }
2617        }
2618    }
2619
2620    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2621        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2622            throw new SecurityException("Label must be specified in permission");
2623        }
2624        BasePermission tree = checkPermissionTreeLP(info.name);
2625        BasePermission bp = mSettings.mPermissions.get(info.name);
2626        boolean added = bp == null;
2627        boolean changed = true;
2628        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2629        if (added) {
2630            enforcePermissionCapLocked(info, tree);
2631            bp = new BasePermission(info.name, tree.sourcePackage,
2632                    BasePermission.TYPE_DYNAMIC);
2633        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2634            throw new SecurityException(
2635                    "Not allowed to modify non-dynamic permission "
2636                    + info.name);
2637        } else {
2638            if (bp.protectionLevel == fixedLevel
2639                    && bp.perm.owner.equals(tree.perm.owner)
2640                    && bp.uid == tree.uid
2641                    && comparePermissionInfos(bp.perm.info, info)) {
2642                changed = false;
2643            }
2644        }
2645        bp.protectionLevel = fixedLevel;
2646        info = new PermissionInfo(info);
2647        info.protectionLevel = fixedLevel;
2648        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2649        bp.perm.info.packageName = tree.perm.info.packageName;
2650        bp.uid = tree.uid;
2651        if (added) {
2652            mSettings.mPermissions.put(info.name, bp);
2653        }
2654        if (changed) {
2655            if (!async) {
2656                mSettings.writeLPr();
2657            } else {
2658                scheduleWriteSettingsLocked();
2659            }
2660        }
2661        return added;
2662    }
2663
2664    public boolean addPermission(PermissionInfo info) {
2665        synchronized (mPackages) {
2666            return addPermissionLocked(info, false);
2667        }
2668    }
2669
2670    public boolean addPermissionAsync(PermissionInfo info) {
2671        synchronized (mPackages) {
2672            return addPermissionLocked(info, true);
2673        }
2674    }
2675
2676    public void removePermission(String name) {
2677        synchronized (mPackages) {
2678            checkPermissionTreeLP(name);
2679            BasePermission bp = mSettings.mPermissions.get(name);
2680            if (bp != null) {
2681                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2682                    throw new SecurityException(
2683                            "Not allowed to modify non-dynamic permission "
2684                            + name);
2685                }
2686                mSettings.mPermissions.remove(name);
2687                mSettings.writeLPr();
2688            }
2689        }
2690    }
2691
2692    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2693        int index = pkg.requestedPermissions.indexOf(bp.name);
2694        if (index == -1) {
2695            throw new SecurityException("Package " + pkg.packageName
2696                    + " has not requested permission " + bp.name);
2697        }
2698        boolean isNormal =
2699                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2700                        == PermissionInfo.PROTECTION_NORMAL);
2701        boolean isDangerous =
2702                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2703                        == PermissionInfo.PROTECTION_DANGEROUS);
2704        boolean isDevelopment =
2705                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2706
2707        if (!isNormal && !isDangerous && !isDevelopment) {
2708            throw new SecurityException("Permission " + bp.name
2709                    + " is not a changeable permission type");
2710        }
2711
2712        if (isNormal || isDangerous) {
2713            if (pkg.requestedPermissionsRequired.get(index)) {
2714                throw new SecurityException("Can't change " + bp.name
2715                        + ". It is required by the application");
2716            }
2717        }
2718    }
2719
2720    public void grantPermission(String packageName, String permissionName) {
2721        mContext.enforceCallingOrSelfPermission(
2722                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2723        synchronized (mPackages) {
2724            final PackageParser.Package pkg = mPackages.get(packageName);
2725            if (pkg == null) {
2726                throw new IllegalArgumentException("Unknown package: " + packageName);
2727            }
2728            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2729            if (bp == null) {
2730                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2731            }
2732
2733            checkGrantRevokePermissions(pkg, bp);
2734
2735            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2736            if (ps == null) {
2737                return;
2738            }
2739            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2740            if (gp.grantedPermissions.add(permissionName)) {
2741                if (ps.haveGids) {
2742                    gp.gids = appendInts(gp.gids, bp.gids);
2743                }
2744                mSettings.writeLPr();
2745            }
2746        }
2747    }
2748
2749    public void revokePermission(String packageName, String permissionName) {
2750        int changedAppId = -1;
2751
2752        synchronized (mPackages) {
2753            final PackageParser.Package pkg = mPackages.get(packageName);
2754            if (pkg == null) {
2755                throw new IllegalArgumentException("Unknown package: " + packageName);
2756            }
2757            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2758                mContext.enforceCallingOrSelfPermission(
2759                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2760            }
2761            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2762            if (bp == null) {
2763                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2764            }
2765
2766            checkGrantRevokePermissions(pkg, bp);
2767
2768            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2769            if (ps == null) {
2770                return;
2771            }
2772            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2773            if (gp.grantedPermissions.remove(permissionName)) {
2774                gp.grantedPermissions.remove(permissionName);
2775                if (ps.haveGids) {
2776                    gp.gids = removeInts(gp.gids, bp.gids);
2777                }
2778                mSettings.writeLPr();
2779                changedAppId = ps.appId;
2780            }
2781        }
2782
2783        if (changedAppId >= 0) {
2784            // We changed the perm on someone, kill its processes.
2785            IActivityManager am = ActivityManagerNative.getDefault();
2786            if (am != null) {
2787                final int callingUserId = UserHandle.getCallingUserId();
2788                final long ident = Binder.clearCallingIdentity();
2789                try {
2790                    //XXX we should only revoke for the calling user's app permissions,
2791                    // but for now we impact all users.
2792                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2793                    //        "revoke " + permissionName);
2794                    int[] users = sUserManager.getUserIds();
2795                    for (int user : users) {
2796                        am.killUid(UserHandle.getUid(user, changedAppId),
2797                                "revoke " + permissionName);
2798                    }
2799                } catch (RemoteException e) {
2800                } finally {
2801                    Binder.restoreCallingIdentity(ident);
2802                }
2803            }
2804        }
2805    }
2806
2807    public boolean isProtectedBroadcast(String actionName) {
2808        synchronized (mPackages) {
2809            return mProtectedBroadcasts.contains(actionName);
2810        }
2811    }
2812
2813    public int checkSignatures(String pkg1, String pkg2) {
2814        synchronized (mPackages) {
2815            final PackageParser.Package p1 = mPackages.get(pkg1);
2816            final PackageParser.Package p2 = mPackages.get(pkg2);
2817            if (p1 == null || p1.mExtras == null
2818                    || p2 == null || p2.mExtras == null) {
2819                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2820            }
2821            return compareSignatures(p1.mSignatures, p2.mSignatures);
2822        }
2823    }
2824
2825    public int checkUidSignatures(int uid1, int uid2) {
2826        // Map to base uids.
2827        uid1 = UserHandle.getAppId(uid1);
2828        uid2 = UserHandle.getAppId(uid2);
2829        // reader
2830        synchronized (mPackages) {
2831            Signature[] s1;
2832            Signature[] s2;
2833            Object obj = mSettings.getUserIdLPr(uid1);
2834            if (obj != null) {
2835                if (obj instanceof SharedUserSetting) {
2836                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2837                } else if (obj instanceof PackageSetting) {
2838                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2839                } else {
2840                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2841                }
2842            } else {
2843                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2844            }
2845            obj = mSettings.getUserIdLPr(uid2);
2846            if (obj != null) {
2847                if (obj instanceof SharedUserSetting) {
2848                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2849                } else if (obj instanceof PackageSetting) {
2850                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2851                } else {
2852                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2853                }
2854            } else {
2855                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2856            }
2857            return compareSignatures(s1, s2);
2858        }
2859    }
2860
2861    /**
2862     * Compares two sets of signatures. Returns:
2863     * <br />
2864     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2865     * <br />
2866     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2867     * <br />
2868     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2869     * <br />
2870     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2871     * <br />
2872     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2873     */
2874    static int compareSignatures(Signature[] s1, Signature[] s2) {
2875        if (s1 == null) {
2876            return s2 == null
2877                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2878                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2879        }
2880
2881        if (s2 == null) {
2882            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2883        }
2884
2885        if (s1.length != s2.length) {
2886            return PackageManager.SIGNATURE_NO_MATCH;
2887        }
2888
2889        // Since both signature sets are of size 1, we can compare without HashSets.
2890        if (s1.length == 1) {
2891            return s1[0].equals(s2[0]) ?
2892                    PackageManager.SIGNATURE_MATCH :
2893                    PackageManager.SIGNATURE_NO_MATCH;
2894        }
2895
2896        HashSet<Signature> set1 = new HashSet<Signature>();
2897        for (Signature sig : s1) {
2898            set1.add(sig);
2899        }
2900        HashSet<Signature> set2 = new HashSet<Signature>();
2901        for (Signature sig : s2) {
2902            set2.add(sig);
2903        }
2904        // Make sure s2 contains all signatures in s1.
2905        if (set1.equals(set2)) {
2906            return PackageManager.SIGNATURE_MATCH;
2907        }
2908        return PackageManager.SIGNATURE_NO_MATCH;
2909    }
2910
2911    /**
2912     * If the database version for this type of package (internal storage or
2913     * external storage) is less than the version where package signatures
2914     * were updated, return true.
2915     */
2916    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2917        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2918                DatabaseVersion.SIGNATURE_END_ENTITY))
2919                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2920                        DatabaseVersion.SIGNATURE_END_ENTITY));
2921    }
2922
2923    /**
2924     * Used for backward compatibility to make sure any packages with
2925     * certificate chains get upgraded to the new style. {@code existingSigs}
2926     * will be in the old format (since they were stored on disk from before the
2927     * system upgrade) and {@code scannedSigs} will be in the newer format.
2928     */
2929    private int compareSignaturesCompat(PackageSignatures existingSigs,
2930            PackageParser.Package scannedPkg) {
2931        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2932            return PackageManager.SIGNATURE_NO_MATCH;
2933        }
2934
2935        HashSet<Signature> existingSet = new HashSet<Signature>();
2936        for (Signature sig : existingSigs.mSignatures) {
2937            existingSet.add(sig);
2938        }
2939        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2940        for (Signature sig : scannedPkg.mSignatures) {
2941            try {
2942                Signature[] chainSignatures = sig.getChainSignatures();
2943                for (Signature chainSig : chainSignatures) {
2944                    scannedCompatSet.add(chainSig);
2945                }
2946            } catch (CertificateEncodingException e) {
2947                scannedCompatSet.add(sig);
2948            }
2949        }
2950        /*
2951         * Make sure the expanded scanned set contains all signatures in the
2952         * existing one.
2953         */
2954        if (scannedCompatSet.equals(existingSet)) {
2955            // Migrate the old signatures to the new scheme.
2956            existingSigs.assignSignatures(scannedPkg.mSignatures);
2957            // The new KeySets will be re-added later in the scanning process.
2958            mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName);
2959            return PackageManager.SIGNATURE_MATCH;
2960        }
2961        return PackageManager.SIGNATURE_NO_MATCH;
2962    }
2963
2964    public String[] getPackagesForUid(int uid) {
2965        uid = UserHandle.getAppId(uid);
2966        // reader
2967        synchronized (mPackages) {
2968            Object obj = mSettings.getUserIdLPr(uid);
2969            if (obj instanceof SharedUserSetting) {
2970                final SharedUserSetting sus = (SharedUserSetting) obj;
2971                final int N = sus.packages.size();
2972                final String[] res = new String[N];
2973                final Iterator<PackageSetting> it = sus.packages.iterator();
2974                int i = 0;
2975                while (it.hasNext()) {
2976                    res[i++] = it.next().name;
2977                }
2978                return res;
2979            } else if (obj instanceof PackageSetting) {
2980                final PackageSetting ps = (PackageSetting) obj;
2981                return new String[] { ps.name };
2982            }
2983        }
2984        return null;
2985    }
2986
2987    public String getNameForUid(int uid) {
2988        // reader
2989        synchronized (mPackages) {
2990            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2991            if (obj instanceof SharedUserSetting) {
2992                final SharedUserSetting sus = (SharedUserSetting) obj;
2993                return sus.name + ":" + sus.userId;
2994            } else if (obj instanceof PackageSetting) {
2995                final PackageSetting ps = (PackageSetting) obj;
2996                return ps.name;
2997            }
2998        }
2999        return null;
3000    }
3001
3002    public int getUidForSharedUser(String sharedUserName) {
3003        if(sharedUserName == null) {
3004            return -1;
3005        }
3006        // reader
3007        synchronized (mPackages) {
3008            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
3009            if (suid == null) {
3010                return -1;
3011            }
3012            return suid.userId;
3013        }
3014    }
3015
3016    public int getFlagsForUid(int uid) {
3017        synchronized (mPackages) {
3018            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3019            if (obj instanceof SharedUserSetting) {
3020                final SharedUserSetting sus = (SharedUserSetting) obj;
3021                return sus.pkgFlags;
3022            } else if (obj instanceof PackageSetting) {
3023                final PackageSetting ps = (PackageSetting) obj;
3024                return ps.pkgFlags;
3025            }
3026        }
3027        return 0;
3028    }
3029
3030    @Override
3031    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3032            int flags, int userId) {
3033        if (!sUserManager.exists(userId)) return null;
3034        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
3035        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3036        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3037    }
3038
3039    @Override
3040    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3041            IntentFilter filter, int match, ComponentName activity) {
3042        final int userId = UserHandle.getCallingUserId();
3043        if (DEBUG_PREFERRED) {
3044            Log.v(TAG, "setLastChosenActivity intent=" + intent
3045                + " resolvedType=" + resolvedType
3046                + " flags=" + flags
3047                + " filter=" + filter
3048                + " match=" + match
3049                + " activity=" + activity);
3050            filter.dump(new PrintStreamPrinter(System.out), "    ");
3051        }
3052        intent.setComponent(null);
3053        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3054        // Find any earlier preferred or last chosen entries and nuke them
3055        findPreferredActivity(intent, resolvedType,
3056                flags, query, 0, false, true, false, userId);
3057        // Add the new activity as the last chosen for this filter
3058        addPreferredActivityInternal(filter, match, null, activity, false, userId);
3059    }
3060
3061    @Override
3062    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3063        final int userId = UserHandle.getCallingUserId();
3064        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3065        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3066        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3067                false, false, false, userId);
3068    }
3069
3070    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3071            int flags, List<ResolveInfo> query, int userId) {
3072        if (query != null) {
3073            final int N = query.size();
3074            if (N == 1) {
3075                return query.get(0);
3076            } else if (N > 1) {
3077                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3078                // If there is more than one activity with the same priority,
3079                // then let the user decide between them.
3080                ResolveInfo r0 = query.get(0);
3081                ResolveInfo r1 = query.get(1);
3082                if (DEBUG_INTENT_MATCHING || debug) {
3083                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3084                            + r1.activityInfo.name + "=" + r1.priority);
3085                }
3086                // If the first activity has a higher priority, or a different
3087                // default, then it is always desireable to pick it.
3088                if (r0.priority != r1.priority
3089                        || r0.preferredOrder != r1.preferredOrder
3090                        || r0.isDefault != r1.isDefault) {
3091                    return query.get(0);
3092                }
3093                // If we have saved a preference for a preferred activity for
3094                // this Intent, use that.
3095                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3096                        flags, query, r0.priority, true, false, debug, userId);
3097                if (ri != null) {
3098                    return ri;
3099                }
3100                if (userId != 0) {
3101                    ri = new ResolveInfo(mResolveInfo);
3102                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3103                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3104                            ri.activityInfo.applicationInfo);
3105                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3106                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3107                    return ri;
3108                }
3109                return mResolveInfo;
3110            }
3111        }
3112        return null;
3113    }
3114
3115    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3116            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3117        final int N = query.size();
3118        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3119                .get(userId);
3120        // Get the list of persistent preferred activities that handle the intent
3121        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3122        List<PersistentPreferredActivity> pprefs = ppir != null
3123                ? ppir.queryIntent(intent, resolvedType,
3124                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3125                : null;
3126        if (pprefs != null && pprefs.size() > 0) {
3127            final int M = pprefs.size();
3128            for (int i=0; i<M; i++) {
3129                final PersistentPreferredActivity ppa = pprefs.get(i);
3130                if (DEBUG_PREFERRED || debug) {
3131                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3132                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3133                            + "\n  component=" + ppa.mComponent);
3134                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3135                }
3136                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3137                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3138                if (DEBUG_PREFERRED || debug) {
3139                    Slog.v(TAG, "Found persistent preferred activity:");
3140                    if (ai != null) {
3141                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3142                    } else {
3143                        Slog.v(TAG, "  null");
3144                    }
3145                }
3146                if (ai == null) {
3147                    // This previously registered persistent preferred activity
3148                    // component is no longer known. Ignore it and do NOT remove it.
3149                    continue;
3150                }
3151                for (int j=0; j<N; j++) {
3152                    final ResolveInfo ri = query.get(j);
3153                    if (!ri.activityInfo.applicationInfo.packageName
3154                            .equals(ai.applicationInfo.packageName)) {
3155                        continue;
3156                    }
3157                    if (!ri.activityInfo.name.equals(ai.name)) {
3158                        continue;
3159                    }
3160                    //  Found a persistent preference that can handle the intent.
3161                    if (DEBUG_PREFERRED || debug) {
3162                        Slog.v(TAG, "Returning persistent preferred activity: " +
3163                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3164                    }
3165                    return ri;
3166                }
3167            }
3168        }
3169        return null;
3170    }
3171
3172    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3173            List<ResolveInfo> query, int priority, boolean always,
3174            boolean removeMatches, boolean debug, int userId) {
3175        if (!sUserManager.exists(userId)) return null;
3176        // writer
3177        synchronized (mPackages) {
3178            if (intent.getSelector() != null) {
3179                intent = intent.getSelector();
3180            }
3181            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3182
3183            // Try to find a matching persistent preferred activity.
3184            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3185                    debug, userId);
3186
3187            // If a persistent preferred activity matched, use it.
3188            if (pri != null) {
3189                return pri;
3190            }
3191
3192            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3193            // Get the list of preferred activities that handle the intent
3194            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3195            List<PreferredActivity> prefs = pir != null
3196                    ? pir.queryIntent(intent, resolvedType,
3197                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3198                    : null;
3199            if (prefs != null && prefs.size() > 0) {
3200                // First figure out how good the original match set is.
3201                // We will only allow preferred activities that came
3202                // from the same match quality.
3203                int match = 0;
3204
3205                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3206
3207                final int N = query.size();
3208                for (int j=0; j<N; j++) {
3209                    final ResolveInfo ri = query.get(j);
3210                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3211                            + ": 0x" + Integer.toHexString(match));
3212                    if (ri.match > match) {
3213                        match = ri.match;
3214                    }
3215                }
3216
3217                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3218                        + Integer.toHexString(match));
3219
3220                match &= IntentFilter.MATCH_CATEGORY_MASK;
3221                final int M = prefs.size();
3222                for (int i=0; i<M; i++) {
3223                    final PreferredActivity pa = prefs.get(i);
3224                    if (DEBUG_PREFERRED || debug) {
3225                        Slog.v(TAG, "Checking PreferredActivity ds="
3226                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3227                                + "\n  component=" + pa.mPref.mComponent);
3228                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3229                    }
3230                    if (pa.mPref.mMatch != match) {
3231                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3232                                + Integer.toHexString(pa.mPref.mMatch));
3233                        continue;
3234                    }
3235                    // If it's not an "always" type preferred activity and that's what we're
3236                    // looking for, skip it.
3237                    if (always && !pa.mPref.mAlways) {
3238                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3239                        continue;
3240                    }
3241                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3242                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3243                    if (DEBUG_PREFERRED || debug) {
3244                        Slog.v(TAG, "Found preferred activity:");
3245                        if (ai != null) {
3246                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3247                        } else {
3248                            Slog.v(TAG, "  null");
3249                        }
3250                    }
3251                    if (ai == null) {
3252                        // This previously registered preferred activity
3253                        // component is no longer known.  Most likely an update
3254                        // to the app was installed and in the new version this
3255                        // component no longer exists.  Clean it up by removing
3256                        // it from the preferred activities list, and skip it.
3257                        Slog.w(TAG, "Removing dangling preferred activity: "
3258                                + pa.mPref.mComponent);
3259                        pir.removeFilter(pa);
3260                        continue;
3261                    }
3262                    for (int j=0; j<N; j++) {
3263                        final ResolveInfo ri = query.get(j);
3264                        if (!ri.activityInfo.applicationInfo.packageName
3265                                .equals(ai.applicationInfo.packageName)) {
3266                            continue;
3267                        }
3268                        if (!ri.activityInfo.name.equals(ai.name)) {
3269                            continue;
3270                        }
3271
3272                        if (removeMatches) {
3273                            pir.removeFilter(pa);
3274                            if (DEBUG_PREFERRED) {
3275                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3276                            }
3277                            break;
3278                        }
3279
3280                        // Okay we found a previously set preferred or last chosen app.
3281                        // If the result set is different from when this
3282                        // was created, we need to clear it and re-ask the
3283                        // user their preference, if we're looking for an "always" type entry.
3284                        if (always && !pa.mPref.sameSet(query, priority)) {
3285                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3286                                    + intent + " type " + resolvedType);
3287                            if (DEBUG_PREFERRED) {
3288                                Slog.v(TAG, "Removing preferred activity since set changed "
3289                                        + pa.mPref.mComponent);
3290                            }
3291                            pir.removeFilter(pa);
3292                            // Re-add the filter as a "last chosen" entry (!always)
3293                            PreferredActivity lastChosen = new PreferredActivity(
3294                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3295                            pir.addFilter(lastChosen);
3296                            mSettings.writePackageRestrictionsLPr(userId);
3297                            return null;
3298                        }
3299
3300                        // Yay! Either the set matched or we're looking for the last chosen
3301                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3302                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3303                        mSettings.writePackageRestrictionsLPr(userId);
3304                        return ri;
3305                    }
3306                }
3307            }
3308            mSettings.writePackageRestrictionsLPr(userId);
3309        }
3310        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3311        return null;
3312    }
3313
3314    /*
3315     * Returns if intent can be forwarded from the userId from to dest
3316     */
3317    @Override
3318    public boolean canForwardTo(Intent intent, String resolvedType, int userIdFrom, int userIdDest) {
3319        mContext.enforceCallingOrSelfPermission(
3320                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3321        List<ForwardingIntentFilter> matches =
3322                getMatchingForwardingIntentFilters(intent, resolvedType, userIdFrom);
3323        if (matches != null) {
3324            int size = matches.size();
3325            for (int i = 0; i < size; i++) {
3326                if (matches.get(i).getUserIdDest() == userIdDest) return true;
3327            }
3328        }
3329        return false;
3330    }
3331
3332    private List<ForwardingIntentFilter> getMatchingForwardingIntentFilters(Intent intent,
3333            String resolvedType, int userId) {
3334        ForwardingIntentResolver fir = mSettings.mForwardingIntentResolvers.get(userId);
3335        if (fir != null) {
3336            return fir.queryIntent(intent, resolvedType, false, userId);
3337        }
3338        return null;
3339    }
3340
3341    @Override
3342    public List<ResolveInfo> queryIntentActivities(Intent intent,
3343            String resolvedType, int flags, int userId) {
3344        if (!sUserManager.exists(userId)) return Collections.emptyList();
3345        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3346        ComponentName comp = intent.getComponent();
3347        if (comp == null) {
3348            if (intent.getSelector() != null) {
3349                intent = intent.getSelector();
3350                comp = intent.getComponent();
3351            }
3352        }
3353
3354        if (comp != null) {
3355            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3356            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3357            if (ai != null) {
3358                final ResolveInfo ri = new ResolveInfo();
3359                ri.activityInfo = ai;
3360                list.add(ri);
3361            }
3362            return list;
3363        }
3364
3365        // reader
3366        synchronized (mPackages) {
3367            final String pkgName = intent.getPackage();
3368            if (pkgName == null) {
3369                List<ResolveInfo> result =
3370                        mActivities.queryIntent(intent, resolvedType, flags, userId);
3371                // Checking if we can forward the intent to another user
3372                List<ForwardingIntentFilter> fifs =
3373                        getMatchingForwardingIntentFilters(intent, resolvedType, userId);
3374                if (fifs != null) {
3375                    ForwardingIntentFilter forwardingIntentFilterWithResult = null;
3376                    HashSet<Integer> alreadyTriedUserIds = new HashSet<Integer>();
3377                    for (ForwardingIntentFilter fif : fifs) {
3378                        int userIdDest = fif.getUserIdDest();
3379                        // Two {@link ForwardingIntentFilter}s can have the same userIdDest and
3380                        // match the same an intent. For performance reasons, it is better not to
3381                        // run queryIntent twice for the same userId
3382                        if (!alreadyTriedUserIds.contains(userIdDest)) {
3383                            List<ResolveInfo> resultUser = mActivities.queryIntent(intent,
3384                                    resolvedType, flags, userIdDest);
3385                            if (resultUser != null) {
3386                                forwardingIntentFilterWithResult = fif;
3387                                // As soon as there is a match in another user, we add the
3388                                // intentForwarderActivity to the list of ResolveInfo.
3389                                break;
3390                            }
3391                            alreadyTriedUserIds.add(userIdDest);
3392                        }
3393                    }
3394                    if (forwardingIntentFilterWithResult != null) {
3395                        ResolveInfo forwardingResolveInfo = createForwardingResolveInfo(
3396                                forwardingIntentFilterWithResult, userId);
3397                        result.add(forwardingResolveInfo);
3398                    }
3399                }
3400                return result;
3401            }
3402            final PackageParser.Package pkg = mPackages.get(pkgName);
3403            if (pkg != null) {
3404                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3405                        pkg.activities, userId);
3406            }
3407            return new ArrayList<ResolveInfo>();
3408        }
3409    }
3410
3411    private ResolveInfo createForwardingResolveInfo(ForwardingIntentFilter fif, int userIdFrom) {
3412        String className;
3413        int userIdDest = fif.getUserIdDest();
3414        if (userIdDest == UserHandle.USER_OWNER) {
3415            className = FORWARD_INTENT_TO_USER_OWNER;
3416        } else {
3417            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3418        }
3419        ComponentName forwardingActivityComponentName = new ComponentName(
3420                mAndroidApplication.packageName, className);
3421        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3422                userIdFrom);
3423        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3424        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3425        forwardingResolveInfo.priority = 0;
3426        forwardingResolveInfo.preferredOrder = 0;
3427        forwardingResolveInfo.match = 0;
3428        forwardingResolveInfo.isDefault = true;
3429        forwardingResolveInfo.filter = fif;
3430        return forwardingResolveInfo;
3431    }
3432
3433    @Override
3434    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3435            Intent[] specifics, String[] specificTypes, Intent intent,
3436            String resolvedType, int flags, int userId) {
3437        if (!sUserManager.exists(userId)) return Collections.emptyList();
3438        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3439                "query intent activity options");
3440        final String resultsAction = intent.getAction();
3441
3442        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3443                | PackageManager.GET_RESOLVED_FILTER, userId);
3444
3445        if (DEBUG_INTENT_MATCHING) {
3446            Log.v(TAG, "Query " + intent + ": " + results);
3447        }
3448
3449        int specificsPos = 0;
3450        int N;
3451
3452        // todo: note that the algorithm used here is O(N^2).  This
3453        // isn't a problem in our current environment, but if we start running
3454        // into situations where we have more than 5 or 10 matches then this
3455        // should probably be changed to something smarter...
3456
3457        // First we go through and resolve each of the specific items
3458        // that were supplied, taking care of removing any corresponding
3459        // duplicate items in the generic resolve list.
3460        if (specifics != null) {
3461            for (int i=0; i<specifics.length; i++) {
3462                final Intent sintent = specifics[i];
3463                if (sintent == null) {
3464                    continue;
3465                }
3466
3467                if (DEBUG_INTENT_MATCHING) {
3468                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3469                }
3470
3471                String action = sintent.getAction();
3472                if (resultsAction != null && resultsAction.equals(action)) {
3473                    // If this action was explicitly requested, then don't
3474                    // remove things that have it.
3475                    action = null;
3476                }
3477
3478                ResolveInfo ri = null;
3479                ActivityInfo ai = null;
3480
3481                ComponentName comp = sintent.getComponent();
3482                if (comp == null) {
3483                    ri = resolveIntent(
3484                        sintent,
3485                        specificTypes != null ? specificTypes[i] : null,
3486                            flags, userId);
3487                    if (ri == null) {
3488                        continue;
3489                    }
3490                    if (ri == mResolveInfo) {
3491                        // ACK!  Must do something better with this.
3492                    }
3493                    ai = ri.activityInfo;
3494                    comp = new ComponentName(ai.applicationInfo.packageName,
3495                            ai.name);
3496                } else {
3497                    ai = getActivityInfo(comp, flags, userId);
3498                    if (ai == null) {
3499                        continue;
3500                    }
3501                }
3502
3503                // Look for any generic query activities that are duplicates
3504                // of this specific one, and remove them from the results.
3505                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3506                N = results.size();
3507                int j;
3508                for (j=specificsPos; j<N; j++) {
3509                    ResolveInfo sri = results.get(j);
3510                    if ((sri.activityInfo.name.equals(comp.getClassName())
3511                            && sri.activityInfo.applicationInfo.packageName.equals(
3512                                    comp.getPackageName()))
3513                        || (action != null && sri.filter.matchAction(action))) {
3514                        results.remove(j);
3515                        if (DEBUG_INTENT_MATCHING) Log.v(
3516                            TAG, "Removing duplicate item from " + j
3517                            + " due to specific " + specificsPos);
3518                        if (ri == null) {
3519                            ri = sri;
3520                        }
3521                        j--;
3522                        N--;
3523                    }
3524                }
3525
3526                // Add this specific item to its proper place.
3527                if (ri == null) {
3528                    ri = new ResolveInfo();
3529                    ri.activityInfo = ai;
3530                }
3531                results.add(specificsPos, ri);
3532                ri.specificIndex = i;
3533                specificsPos++;
3534            }
3535        }
3536
3537        // Now we go through the remaining generic results and remove any
3538        // duplicate actions that are found here.
3539        N = results.size();
3540        for (int i=specificsPos; i<N-1; i++) {
3541            final ResolveInfo rii = results.get(i);
3542            if (rii.filter == null) {
3543                continue;
3544            }
3545
3546            // Iterate over all of the actions of this result's intent
3547            // filter...  typically this should be just one.
3548            final Iterator<String> it = rii.filter.actionsIterator();
3549            if (it == null) {
3550                continue;
3551            }
3552            while (it.hasNext()) {
3553                final String action = it.next();
3554                if (resultsAction != null && resultsAction.equals(action)) {
3555                    // If this action was explicitly requested, then don't
3556                    // remove things that have it.
3557                    continue;
3558                }
3559                for (int j=i+1; j<N; j++) {
3560                    final ResolveInfo rij = results.get(j);
3561                    if (rij.filter != null && rij.filter.hasAction(action)) {
3562                        results.remove(j);
3563                        if (DEBUG_INTENT_MATCHING) Log.v(
3564                            TAG, "Removing duplicate item from " + j
3565                            + " due to action " + action + " at " + i);
3566                        j--;
3567                        N--;
3568                    }
3569                }
3570            }
3571
3572            // If the caller didn't request filter information, drop it now
3573            // so we don't have to marshall/unmarshall it.
3574            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3575                rii.filter = null;
3576            }
3577        }
3578
3579        // Filter out the caller activity if so requested.
3580        if (caller != null) {
3581            N = results.size();
3582            for (int i=0; i<N; i++) {
3583                ActivityInfo ainfo = results.get(i).activityInfo;
3584                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3585                        && caller.getClassName().equals(ainfo.name)) {
3586                    results.remove(i);
3587                    break;
3588                }
3589            }
3590        }
3591
3592        // If the caller didn't request filter information,
3593        // drop them now so we don't have to
3594        // marshall/unmarshall it.
3595        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3596            N = results.size();
3597            for (int i=0; i<N; i++) {
3598                results.get(i).filter = null;
3599            }
3600        }
3601
3602        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3603        return results;
3604    }
3605
3606    @Override
3607    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3608            int userId) {
3609        if (!sUserManager.exists(userId)) return Collections.emptyList();
3610        ComponentName comp = intent.getComponent();
3611        if (comp == null) {
3612            if (intent.getSelector() != null) {
3613                intent = intent.getSelector();
3614                comp = intent.getComponent();
3615            }
3616        }
3617        if (comp != null) {
3618            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3619            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3620            if (ai != null) {
3621                ResolveInfo ri = new ResolveInfo();
3622                ri.activityInfo = ai;
3623                list.add(ri);
3624            }
3625            return list;
3626        }
3627
3628        // reader
3629        synchronized (mPackages) {
3630            String pkgName = intent.getPackage();
3631            if (pkgName == null) {
3632                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3633            }
3634            final PackageParser.Package pkg = mPackages.get(pkgName);
3635            if (pkg != null) {
3636                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3637                        userId);
3638            }
3639            return null;
3640        }
3641    }
3642
3643    @Override
3644    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3645        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3646        if (!sUserManager.exists(userId)) return null;
3647        if (query != null) {
3648            if (query.size() >= 1) {
3649                // If there is more than one service with the same priority,
3650                // just arbitrarily pick the first one.
3651                return query.get(0);
3652            }
3653        }
3654        return null;
3655    }
3656
3657    @Override
3658    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3659            int userId) {
3660        if (!sUserManager.exists(userId)) return Collections.emptyList();
3661        ComponentName comp = intent.getComponent();
3662        if (comp == null) {
3663            if (intent.getSelector() != null) {
3664                intent = intent.getSelector();
3665                comp = intent.getComponent();
3666            }
3667        }
3668        if (comp != null) {
3669            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3670            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3671            if (si != null) {
3672                final ResolveInfo ri = new ResolveInfo();
3673                ri.serviceInfo = si;
3674                list.add(ri);
3675            }
3676            return list;
3677        }
3678
3679        // reader
3680        synchronized (mPackages) {
3681            String pkgName = intent.getPackage();
3682            if (pkgName == null) {
3683                return mServices.queryIntent(intent, resolvedType, flags, userId);
3684            }
3685            final PackageParser.Package pkg = mPackages.get(pkgName);
3686            if (pkg != null) {
3687                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3688                        userId);
3689            }
3690            return null;
3691        }
3692    }
3693
3694    @Override
3695    public List<ResolveInfo> queryIntentContentProviders(
3696            Intent intent, String resolvedType, int flags, int userId) {
3697        if (!sUserManager.exists(userId)) return Collections.emptyList();
3698        ComponentName comp = intent.getComponent();
3699        if (comp == null) {
3700            if (intent.getSelector() != null) {
3701                intent = intent.getSelector();
3702                comp = intent.getComponent();
3703            }
3704        }
3705        if (comp != null) {
3706            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3707            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3708            if (pi != null) {
3709                final ResolveInfo ri = new ResolveInfo();
3710                ri.providerInfo = pi;
3711                list.add(ri);
3712            }
3713            return list;
3714        }
3715
3716        // reader
3717        synchronized (mPackages) {
3718            String pkgName = intent.getPackage();
3719            if (pkgName == null) {
3720                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3721            }
3722            final PackageParser.Package pkg = mPackages.get(pkgName);
3723            if (pkg != null) {
3724                return mProviders.queryIntentForPackage(
3725                        intent, resolvedType, flags, pkg.providers, userId);
3726            }
3727            return null;
3728        }
3729    }
3730
3731    @Override
3732    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3733        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3734
3735        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3736
3737        // writer
3738        synchronized (mPackages) {
3739            ArrayList<PackageInfo> list;
3740            if (listUninstalled) {
3741                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3742                for (PackageSetting ps : mSettings.mPackages.values()) {
3743                    PackageInfo pi;
3744                    if (ps.pkg != null) {
3745                        pi = generatePackageInfo(ps.pkg, flags, userId);
3746                    } else {
3747                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3748                    }
3749                    if (pi != null) {
3750                        list.add(pi);
3751                    }
3752                }
3753            } else {
3754                list = new ArrayList<PackageInfo>(mPackages.size());
3755                for (PackageParser.Package p : mPackages.values()) {
3756                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3757                    if (pi != null) {
3758                        list.add(pi);
3759                    }
3760                }
3761            }
3762
3763            return new ParceledListSlice<PackageInfo>(list);
3764        }
3765    }
3766
3767    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3768            String[] permissions, boolean[] tmp, int flags, int userId) {
3769        int numMatch = 0;
3770        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3771        for (int i=0; i<permissions.length; i++) {
3772            if (gp.grantedPermissions.contains(permissions[i])) {
3773                tmp[i] = true;
3774                numMatch++;
3775            } else {
3776                tmp[i] = false;
3777            }
3778        }
3779        if (numMatch == 0) {
3780            return;
3781        }
3782        PackageInfo pi;
3783        if (ps.pkg != null) {
3784            pi = generatePackageInfo(ps.pkg, flags, userId);
3785        } else {
3786            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3787        }
3788        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3789            if (numMatch == permissions.length) {
3790                pi.requestedPermissions = permissions;
3791            } else {
3792                pi.requestedPermissions = new String[numMatch];
3793                numMatch = 0;
3794                for (int i=0; i<permissions.length; i++) {
3795                    if (tmp[i]) {
3796                        pi.requestedPermissions[numMatch] = permissions[i];
3797                        numMatch++;
3798                    }
3799                }
3800            }
3801        }
3802        list.add(pi);
3803    }
3804
3805    @Override
3806    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3807            String[] permissions, int flags, int userId) {
3808        if (!sUserManager.exists(userId)) return null;
3809        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3810
3811        // writer
3812        synchronized (mPackages) {
3813            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3814            boolean[] tmpBools = new boolean[permissions.length];
3815            if (listUninstalled) {
3816                for (PackageSetting ps : mSettings.mPackages.values()) {
3817                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3818                }
3819            } else {
3820                for (PackageParser.Package pkg : mPackages.values()) {
3821                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3822                    if (ps != null) {
3823                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3824                                userId);
3825                    }
3826                }
3827            }
3828
3829            return new ParceledListSlice<PackageInfo>(list);
3830        }
3831    }
3832
3833    @Override
3834    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3835        if (!sUserManager.exists(userId)) return null;
3836        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3837
3838        // writer
3839        synchronized (mPackages) {
3840            ArrayList<ApplicationInfo> list;
3841            if (listUninstalled) {
3842                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3843                for (PackageSetting ps : mSettings.mPackages.values()) {
3844                    ApplicationInfo ai;
3845                    if (ps.pkg != null) {
3846                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3847                                ps.readUserState(userId), userId);
3848                    } else {
3849                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3850                    }
3851                    if (ai != null) {
3852                        list.add(ai);
3853                    }
3854                }
3855            } else {
3856                list = new ArrayList<ApplicationInfo>(mPackages.size());
3857                for (PackageParser.Package p : mPackages.values()) {
3858                    if (p.mExtras != null) {
3859                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3860                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3861                        if (ai != null) {
3862                            list.add(ai);
3863                        }
3864                    }
3865                }
3866            }
3867
3868            return new ParceledListSlice<ApplicationInfo>(list);
3869        }
3870    }
3871
3872    public List<ApplicationInfo> getPersistentApplications(int flags) {
3873        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3874
3875        // reader
3876        synchronized (mPackages) {
3877            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3878            final int userId = UserHandle.getCallingUserId();
3879            while (i.hasNext()) {
3880                final PackageParser.Package p = i.next();
3881                if (p.applicationInfo != null
3882                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3883                        && (!mSafeMode || isSystemApp(p))) {
3884                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3885                    if (ps != null) {
3886                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3887                                ps.readUserState(userId), userId);
3888                        if (ai != null) {
3889                            finalList.add(ai);
3890                        }
3891                    }
3892                }
3893            }
3894        }
3895
3896        return finalList;
3897    }
3898
3899    @Override
3900    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3901        if (!sUserManager.exists(userId)) return null;
3902        // reader
3903        synchronized (mPackages) {
3904            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3905            PackageSetting ps = provider != null
3906                    ? mSettings.mPackages.get(provider.owner.packageName)
3907                    : null;
3908            return ps != null
3909                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3910                    && (!mSafeMode || (provider.info.applicationInfo.flags
3911                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3912                    ? PackageParser.generateProviderInfo(provider, flags,
3913                            ps.readUserState(userId), userId)
3914                    : null;
3915        }
3916    }
3917
3918    /**
3919     * @deprecated
3920     */
3921    @Deprecated
3922    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3923        // reader
3924        synchronized (mPackages) {
3925            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3926                    .entrySet().iterator();
3927            final int userId = UserHandle.getCallingUserId();
3928            while (i.hasNext()) {
3929                Map.Entry<String, PackageParser.Provider> entry = i.next();
3930                PackageParser.Provider p = entry.getValue();
3931                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3932
3933                if (ps != null && p.syncable
3934                        && (!mSafeMode || (p.info.applicationInfo.flags
3935                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3936                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3937                            ps.readUserState(userId), userId);
3938                    if (info != null) {
3939                        outNames.add(entry.getKey());
3940                        outInfo.add(info);
3941                    }
3942                }
3943            }
3944        }
3945    }
3946
3947    public List<ProviderInfo> queryContentProviders(String processName,
3948            int uid, int flags) {
3949        ArrayList<ProviderInfo> finalList = null;
3950        // reader
3951        synchronized (mPackages) {
3952            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3953            final int userId = processName != null ?
3954                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3955            while (i.hasNext()) {
3956                final PackageParser.Provider p = i.next();
3957                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3958                if (ps != null && p.info.authority != null
3959                        && (processName == null
3960                                || (p.info.processName.equals(processName)
3961                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3962                        && mSettings.isEnabledLPr(p.info, flags, userId)
3963                        && (!mSafeMode
3964                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3965                    if (finalList == null) {
3966                        finalList = new ArrayList<ProviderInfo>(3);
3967                    }
3968                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3969                            ps.readUserState(userId), userId);
3970                    if (info != null) {
3971                        finalList.add(info);
3972                    }
3973                }
3974            }
3975        }
3976
3977        if (finalList != null) {
3978            Collections.sort(finalList, mProviderInitOrderSorter);
3979        }
3980
3981        return finalList;
3982    }
3983
3984    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3985            int flags) {
3986        // reader
3987        synchronized (mPackages) {
3988            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3989            return PackageParser.generateInstrumentationInfo(i, flags);
3990        }
3991    }
3992
3993    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3994            int flags) {
3995        ArrayList<InstrumentationInfo> finalList =
3996            new ArrayList<InstrumentationInfo>();
3997
3998        // reader
3999        synchronized (mPackages) {
4000            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4001            while (i.hasNext()) {
4002                final PackageParser.Instrumentation p = i.next();
4003                if (targetPackage == null
4004                        || targetPackage.equals(p.info.targetPackage)) {
4005                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4006                            flags);
4007                    if (ii != null) {
4008                        finalList.add(ii);
4009                    }
4010                }
4011            }
4012        }
4013
4014        return finalList;
4015    }
4016
4017    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4018        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4019        if (overlays == null) {
4020            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4021            return;
4022        }
4023        for (PackageParser.Package opkg : overlays.values()) {
4024            // Not much to do if idmap fails: we already logged the error
4025            // and we certainly don't want to abort installation of pkg simply
4026            // because an overlay didn't fit properly. For these reasons,
4027            // ignore the return value of createIdmapForPackagePairLI.
4028            createIdmapForPackagePairLI(pkg, opkg);
4029        }
4030    }
4031
4032    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4033            PackageParser.Package opkg) {
4034        if (!opkg.mTrustedOverlay) {
4035            Slog.w(TAG, "Skipping target and overlay pair " + pkg.mScanPath + " and " +
4036                    opkg.mScanPath + ": overlay not trusted");
4037            return false;
4038        }
4039        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4040        if (overlaySet == null) {
4041            Slog.e(TAG, "was about to create idmap for " + pkg.mScanPath + " and " +
4042                    opkg.mScanPath + " but target package has no known overlays");
4043            return false;
4044        }
4045        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4046        if (mInstaller.idmap(pkg.mScanPath, opkg.mScanPath, sharedGid) != 0) {
4047            Slog.e(TAG, "Failed to generate idmap for " + pkg.mScanPath + " and " + opkg.mScanPath);
4048            return false;
4049        }
4050        PackageParser.Package[] overlayArray =
4051            overlaySet.values().toArray(new PackageParser.Package[0]);
4052        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4053            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4054                return p1.mOverlayPriority - p2.mOverlayPriority;
4055            }
4056        };
4057        Arrays.sort(overlayArray, cmp);
4058
4059        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4060        int i = 0;
4061        for (PackageParser.Package p : overlayArray) {
4062            pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir;
4063        }
4064        return true;
4065    }
4066
4067    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4068        String[] files = dir.list();
4069        if (files == null) {
4070            Log.d(TAG, "No files in app dir " + dir);
4071            return;
4072        }
4073
4074        if (DEBUG_PACKAGE_SCANNING) {
4075            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4076                    + " flags=0x" + Integer.toHexString(flags));
4077        }
4078
4079        int i;
4080        for (i=0; i<files.length; i++) {
4081            File file = new File(dir, files[i]);
4082            if (!isPackageFilename(files[i])) {
4083                // Ignore entries which are not apk's
4084                continue;
4085            }
4086            PackageParser.Package pkg = scanPackageLI(file,
4087                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null);
4088            // Don't mess around with apps in system partition.
4089            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4090                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
4091                // Delete the apk
4092                Slog.w(TAG, "Cleaning up failed install of " + file);
4093                file.delete();
4094            }
4095        }
4096    }
4097
4098    private static File getSettingsProblemFile() {
4099        File dataDir = Environment.getDataDirectory();
4100        File systemDir = new File(dataDir, "system");
4101        File fname = new File(systemDir, "uiderrors.txt");
4102        return fname;
4103    }
4104
4105    static void reportSettingsProblem(int priority, String msg) {
4106        try {
4107            File fname = getSettingsProblemFile();
4108            FileOutputStream out = new FileOutputStream(fname, true);
4109            PrintWriter pw = new FastPrintWriter(out);
4110            SimpleDateFormat formatter = new SimpleDateFormat();
4111            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4112            pw.println(dateString + ": " + msg);
4113            pw.close();
4114            FileUtils.setPermissions(
4115                    fname.toString(),
4116                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4117                    -1, -1);
4118        } catch (java.io.IOException e) {
4119        }
4120        Slog.println(priority, TAG, msg);
4121    }
4122
4123    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
4124            PackageParser.Package pkg, File srcFile, int parseFlags) {
4125        if (ps != null
4126                && ps.codePath.equals(srcFile)
4127                && ps.timeStamp == srcFile.lastModified()
4128                && !isCompatSignatureUpdateNeeded(pkg)) {
4129            if (ps.signatures.mSignatures != null
4130                    && ps.signatures.mSignatures.length != 0) {
4131                // Optimization: reuse the existing cached certificates
4132                // if the package appears to be unchanged.
4133                pkg.mSignatures = ps.signatures.mSignatures;
4134                return true;
4135            }
4136
4137            Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
4138        } else {
4139            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4140        }
4141
4142        if (!pp.collectCertificates(pkg, parseFlags)) {
4143            mLastScanError = pp.getParseError();
4144            return false;
4145        }
4146        return true;
4147    }
4148
4149    /*
4150     *  Scan a package and return the newly parsed package.
4151     *  Returns null in case of errors and the error code is stored in mLastScanError
4152     */
4153    private PackageParser.Package scanPackageLI(File scanFile,
4154            int parseFlags, int scanMode, long currentTime, UserHandle user) {
4155        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4156        String scanPath = scanFile.getPath();
4157        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
4158        parseFlags |= mDefParseFlags;
4159        PackageParser pp = new PackageParser(scanPath);
4160        pp.setSeparateProcesses(mSeparateProcesses);
4161        pp.setOnlyCoreApps(mOnlyCore);
4162        final PackageParser.Package pkg = pp.parsePackage(scanFile,
4163                scanPath, mMetrics, parseFlags, (scanMode & SCAN_TRUSTED_OVERLAY) != 0);
4164
4165        if (pkg == null) {
4166            mLastScanError = pp.getParseError();
4167            return null;
4168        }
4169
4170        PackageSetting ps = null;
4171        PackageSetting updatedPkg;
4172        // reader
4173        synchronized (mPackages) {
4174            // Look to see if we already know about this package.
4175            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4176            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4177                // This package has been renamed to its original name.  Let's
4178                // use that.
4179                ps = mSettings.peekPackageLPr(oldName);
4180            }
4181            // If there was no original package, see one for the real package name.
4182            if (ps == null) {
4183                ps = mSettings.peekPackageLPr(pkg.packageName);
4184            }
4185            // Check to see if this package could be hiding/updating a system
4186            // package.  Must look for it either under the original or real
4187            // package name depending on our state.
4188            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4189            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4190        }
4191        boolean updatedPkgBetter = false;
4192        // First check if this is a system package that may involve an update
4193        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4194            if (ps != null && !ps.codePath.equals(scanFile)) {
4195                // The path has changed from what was last scanned...  check the
4196                // version of the new path against what we have stored to determine
4197                // what to do.
4198                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4199                if (pkg.mVersionCode < ps.versionCode) {
4200                    // The system package has been updated and the code path does not match
4201                    // Ignore entry. Skip it.
4202                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4203                            + " ignored: updated version " + ps.versionCode
4204                            + " better than this " + pkg.mVersionCode);
4205                    if (!updatedPkg.codePath.equals(scanFile)) {
4206                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4207                                + ps.name + " changing from " + updatedPkg.codePathString
4208                                + " to " + scanFile);
4209                        updatedPkg.codePath = scanFile;
4210                        updatedPkg.codePathString = scanFile.toString();
4211                        // This is the point at which we know that the system-disk APK
4212                        // for this package has moved during a reboot (e.g. due to an OTA),
4213                        // so we need to reevaluate it for privilege policy.
4214                        if (locationIsPrivileged(scanFile)) {
4215                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4216                        }
4217                    }
4218                    updatedPkg.pkg = pkg;
4219                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4220                    return null;
4221                } else {
4222                    // The current app on the system partion is better than
4223                    // what we have updated to on the data partition; switch
4224                    // back to the system partition version.
4225                    // At this point, its safely assumed that package installation for
4226                    // apps in system partition will go through. If not there won't be a working
4227                    // version of the app
4228                    // writer
4229                    synchronized (mPackages) {
4230                        // Just remove the loaded entries from package lists.
4231                        mPackages.remove(ps.name);
4232                    }
4233                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4234                            + "reverting from " + ps.codePathString
4235                            + ": new version " + pkg.mVersionCode
4236                            + " better than installed " + ps.versionCode);
4237
4238                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4239                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4240                            getAppInstructionSetFromSettings(ps));
4241                    synchronized (mInstallLock) {
4242                        args.cleanUpResourcesLI();
4243                    }
4244                    synchronized (mPackages) {
4245                        mSettings.enableSystemPackageLPw(ps.name);
4246                    }
4247                    updatedPkgBetter = true;
4248                }
4249            }
4250        }
4251
4252        if (updatedPkg != null) {
4253            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4254            // initially
4255            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4256
4257            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4258            // flag set initially
4259            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4260                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4261            }
4262        }
4263        // Verify certificates against what was last scanned
4264        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
4265            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
4266            return null;
4267        }
4268
4269        /*
4270         * A new system app appeared, but we already had a non-system one of the
4271         * same name installed earlier.
4272         */
4273        boolean shouldHideSystemApp = false;
4274        if (updatedPkg == null && ps != null
4275                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4276            /*
4277             * Check to make sure the signatures match first. If they don't,
4278             * wipe the installed application and its data.
4279             */
4280            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4281                    != PackageManager.SIGNATURE_MATCH) {
4282                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4283                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4284                ps = null;
4285            } else {
4286                /*
4287                 * If the newly-added system app is an older version than the
4288                 * already installed version, hide it. It will be scanned later
4289                 * and re-added like an update.
4290                 */
4291                if (pkg.mVersionCode < ps.versionCode) {
4292                    shouldHideSystemApp = true;
4293                } else {
4294                    /*
4295                     * The newly found system app is a newer version that the
4296                     * one previously installed. Simply remove the
4297                     * already-installed application and replace it with our own
4298                     * while keeping the application data.
4299                     */
4300                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4301                            + ps.codePathString + ": new version " + pkg.mVersionCode
4302                            + " better than installed " + ps.versionCode);
4303                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4304                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4305                            getAppInstructionSetFromSettings(ps));
4306                    synchronized (mInstallLock) {
4307                        args.cleanUpResourcesLI();
4308                    }
4309                }
4310            }
4311        }
4312
4313        // The apk is forward locked (not public) if its code and resources
4314        // are kept in different files. (except for app in either system or
4315        // vendor path).
4316        // TODO grab this value from PackageSettings
4317        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4318            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4319                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4320            }
4321        }
4322
4323        String codePath = null;
4324        String resPath = null;
4325        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4326            if (ps != null && ps.resourcePathString != null) {
4327                resPath = ps.resourcePathString;
4328            } else {
4329                // Should not happen at all. Just log an error.
4330                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4331            }
4332        } else {
4333            resPath = pkg.mScanPath;
4334        }
4335
4336        codePath = pkg.mScanPath;
4337        // Set application objects path explicitly.
4338        setApplicationInfoPaths(pkg, codePath, resPath);
4339        // Note that we invoke the following method only if we are about to unpack an application
4340        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4341                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4342
4343        /*
4344         * If the system app should be overridden by a previously installed
4345         * data, hide the system app now and let the /data/app scan pick it up
4346         * again.
4347         */
4348        if (shouldHideSystemApp) {
4349            synchronized (mPackages) {
4350                /*
4351                 * We have to grant systems permissions before we hide, because
4352                 * grantPermissions will assume the package update is trying to
4353                 * expand its permissions.
4354                 */
4355                grantPermissionsLPw(pkg, true);
4356                mSettings.disableSystemPackageLPw(pkg.packageName);
4357            }
4358        }
4359
4360        return scannedPkg;
4361    }
4362
4363    private static void setApplicationInfoPaths(PackageParser.Package pkg, String destCodePath,
4364            String destResPath) {
4365        pkg.mPath = pkg.mScanPath = destCodePath;
4366        pkg.applicationInfo.sourceDir = destCodePath;
4367        pkg.applicationInfo.publicSourceDir = destResPath;
4368    }
4369
4370    private static String fixProcessName(String defProcessName,
4371            String processName, int uid) {
4372        if (processName == null) {
4373            return defProcessName;
4374        }
4375        return processName;
4376    }
4377
4378    private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) {
4379        if (pkgSetting.signatures.mSignatures != null) {
4380            // Already existing package. Make sure signatures match
4381            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4382                    == PackageManager.SIGNATURE_MATCH;
4383            if (!match) {
4384                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4385                        == PackageManager.SIGNATURE_MATCH;
4386            }
4387            if (!match) {
4388                Slog.e(TAG, "Package " + pkg.packageName
4389                        + " signatures do not match the previously installed version; ignoring!");
4390                mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4391                return false;
4392            }
4393        }
4394        // Check for shared user signatures
4395        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4396            // Already existing package. Make sure signatures match
4397            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4398                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4399            if (!match) {
4400                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4401                        == PackageManager.SIGNATURE_MATCH;
4402            }
4403            if (!match) {
4404                Slog.e(TAG, "Package " + pkg.packageName
4405                        + " has no signatures that match those in shared user "
4406                        + pkgSetting.sharedUser.name + "; ignoring!");
4407                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4408                return false;
4409            }
4410        }
4411        return true;
4412    }
4413
4414    /**
4415     * Enforces that only the system UID or root's UID can call a method exposed
4416     * via Binder.
4417     *
4418     * @param message used as message if SecurityException is thrown
4419     * @throws SecurityException if the caller is not system or root
4420     */
4421    private static final void enforceSystemOrRoot(String message) {
4422        final int uid = Binder.getCallingUid();
4423        if (uid != Process.SYSTEM_UID && uid != 0) {
4424            throw new SecurityException(message);
4425        }
4426    }
4427
4428    @Override
4429    public void performBootDexOpt() {
4430        enforceSystemOrRoot("Only the system can request dexopt be performed");
4431
4432        final HashSet<PackageParser.Package> pkgs;
4433        synchronized (mPackages) {
4434            pkgs = mDeferredDexOpt;
4435            mDeferredDexOpt = null;
4436        }
4437
4438        if (pkgs != null) {
4439            // Filter out packages that aren't recently used.
4440            //
4441            // The exception is first boot of a non-eng device, which
4442            // should do a full dexopt.
4443            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4444            if (eng || !isFirstBoot()) {
4445                // TODO: add a property to control this?
4446                long dexOptLRUThresholdInMinutes;
4447                if (eng) {
4448                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4449                } else {
4450                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4451                }
4452                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4453
4454                int total = pkgs.size();
4455                int skipped = 0;
4456                long now = System.currentTimeMillis();
4457                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4458                    PackageParser.Package pkg = i.next();
4459                    long then = pkg.mLastPackageUsageTimeInMills;
4460                    if (then + dexOptLRUThresholdInMills < now) {
4461                        if (DEBUG_DEXOPT) {
4462                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4463                                  ((then == 0) ? "never" : new Date(then)));
4464                        }
4465                        i.remove();
4466                        skipped++;
4467                    }
4468                }
4469                if (DEBUG_DEXOPT) {
4470                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4471                }
4472            }
4473
4474            int i = 0;
4475            for (PackageParser.Package pkg : pkgs) {
4476                i++;
4477                if (DEBUG_DEXOPT) {
4478                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4479                          + ": " + pkg.packageName);
4480                }
4481                if (!isFirstBoot()) {
4482                    try {
4483                        ActivityManagerNative.getDefault().showBootMessage(
4484                                mContext.getResources().getString(
4485                                        R.string.android_upgrading_apk,
4486                                        i, pkgs.size()), true);
4487                    } catch (RemoteException e) {
4488                    }
4489                }
4490                PackageParser.Package p = pkg;
4491                synchronized (mInstallLock) {
4492                    if (p.mDexOptNeeded) {
4493                        performDexOptLI(p, false /* force dex */, false /* defer */,
4494                                true /* include dependencies */);
4495                    }
4496                }
4497            }
4498        }
4499    }
4500
4501    @Override
4502    public boolean performDexOpt(String packageName) {
4503        enforceSystemOrRoot("Only the system can request dexopt be performed");
4504
4505        PackageParser.Package p;
4506        synchronized (mPackages) {
4507            p = mPackages.get(packageName);
4508            if (p == null) {
4509                return false;
4510            }
4511            p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4512            mPackageUsage.write();
4513            if (!p.mDexOptNeeded) {
4514                return false;
4515            }
4516        }
4517
4518        synchronized (mInstallLock) {
4519            return performDexOptLI(p, false /* force dex */, false /* defer */,
4520                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4521        }
4522    }
4523
4524    public void shutdown() {
4525        mPackageUsage.write(true);
4526    }
4527
4528    private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet,
4529             boolean forceDex, boolean defer, HashSet<String> done) {
4530        for (int i=0; i<libs.size(); i++) {
4531            PackageParser.Package libPkg;
4532            String libName;
4533            synchronized (mPackages) {
4534                libName = libs.get(i);
4535                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4536                if (lib != null && lib.apk != null) {
4537                    libPkg = mPackages.get(lib.apk);
4538                } else {
4539                    libPkg = null;
4540                }
4541            }
4542            if (libPkg != null && !done.contains(libName)) {
4543                performDexOptLI(libPkg, instructionSet, forceDex, defer, done);
4544            }
4545        }
4546    }
4547
4548    static final int DEX_OPT_SKIPPED = 0;
4549    static final int DEX_OPT_PERFORMED = 1;
4550    static final int DEX_OPT_DEFERRED = 2;
4551    static final int DEX_OPT_FAILED = -1;
4552
4553    private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride,
4554            boolean forceDex, boolean defer, HashSet<String> done) {
4555        final String instructionSet = instructionSetOverride != null ?
4556                instructionSetOverride : getAppInstructionSet(pkg.applicationInfo);
4557
4558        if (done != null) {
4559            done.add(pkg.packageName);
4560            if (pkg.usesLibraries != null) {
4561                performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done);
4562            }
4563            if (pkg.usesOptionalLibraries != null) {
4564                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done);
4565            }
4566        }
4567
4568        boolean performed = false;
4569        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
4570            String path = pkg.mScanPath;
4571            try {
4572                boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path,
4573                                                                                pkg.packageName,
4574                                                                                instructionSet,
4575                                                                                defer);
4576                // There are three basic cases here:
4577                // 1.) we need to dexopt, either because we are forced or it is needed
4578                // 2.) we are defering a needed dexopt
4579                // 3.) we are skipping an unneeded dexopt
4580                if (forceDex || (!defer && isDexOptNeededInternal)) {
4581                    Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
4582                    final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4583                    int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4584                                                pkg.packageName, instructionSet);
4585                    // Note that we ran dexopt, since rerunning will
4586                    // probably just result in an error again.
4587                    pkg.mDexOptNeeded = false;
4588                    if (ret < 0) {
4589                        return DEX_OPT_FAILED;
4590                    }
4591                    return DEX_OPT_PERFORMED;
4592                }
4593                if (defer && isDexOptNeededInternal) {
4594                    if (mDeferredDexOpt == null) {
4595                        mDeferredDexOpt = new HashSet<PackageParser.Package>();
4596                    }
4597                    mDeferredDexOpt.add(pkg);
4598                    return DEX_OPT_DEFERRED;
4599                }
4600                pkg.mDexOptNeeded = false;
4601                return DEX_OPT_SKIPPED;
4602            } catch (FileNotFoundException e) {
4603                Slog.w(TAG, "Apk not found for dexopt: " + path);
4604                return DEX_OPT_FAILED;
4605            } catch (IOException e) {
4606                Slog.w(TAG, "IOException reading apk: " + path, e);
4607                return DEX_OPT_FAILED;
4608            } catch (StaleDexCacheError e) {
4609                Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4610                return DEX_OPT_FAILED;
4611            } catch (Exception e) {
4612                Slog.w(TAG, "Exception when doing dexopt : ", e);
4613                return DEX_OPT_FAILED;
4614            }
4615        }
4616        return DEX_OPT_SKIPPED;
4617    }
4618
4619    private String getAppInstructionSet(ApplicationInfo info) {
4620        String instructionSet = getPreferredInstructionSet();
4621
4622        if (info.requiredCpuAbi != null) {
4623            instructionSet = VMRuntime.getInstructionSet(info.requiredCpuAbi);
4624        }
4625
4626        return instructionSet;
4627    }
4628
4629    private String getAppInstructionSetFromSettings(PackageSetting ps) {
4630        String instructionSet = getPreferredInstructionSet();
4631
4632        if (ps.requiredCpuAbiString != null) {
4633            instructionSet = VMRuntime.getInstructionSet(ps.requiredCpuAbiString);
4634        }
4635
4636        return instructionSet;
4637    }
4638
4639    private static String getPreferredInstructionSet() {
4640        if (sPreferredInstructionSet == null) {
4641            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4642        }
4643
4644        return sPreferredInstructionSet;
4645    }
4646
4647    private static List<String> getAllInstructionSets() {
4648        final String[] allAbis = Build.SUPPORTED_ABIS;
4649        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4650
4651        for (String abi : allAbis) {
4652            final String instructionSet = VMRuntime.getInstructionSet(abi);
4653            if (!allInstructionSets.contains(instructionSet)) {
4654                allInstructionSets.add(instructionSet);
4655            }
4656        }
4657
4658        return allInstructionSets;
4659    }
4660
4661    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4662            boolean inclDependencies) {
4663        HashSet<String> done;
4664        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4665            done = new HashSet<String>();
4666            done.add(pkg.packageName);
4667        } else {
4668            done = null;
4669        }
4670        return performDexOptLI(pkg, null /* instruction set override */,  forceDex, defer, done);
4671    }
4672
4673    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4674        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4675            Slog.w(TAG, "Unable to update from " + oldPkg.name
4676                    + " to " + newPkg.packageName
4677                    + ": old package not in system partition");
4678            return false;
4679        } else if (mPackages.get(oldPkg.name) != null) {
4680            Slog.w(TAG, "Unable to update from " + oldPkg.name
4681                    + " to " + newPkg.packageName
4682                    + ": old package still exists");
4683            return false;
4684        }
4685        return true;
4686    }
4687
4688    File getDataPathForUser(int userId) {
4689        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4690    }
4691
4692    private File getDataPathForPackage(String packageName, int userId) {
4693        /*
4694         * Until we fully support multiple users, return the directory we
4695         * previously would have. The PackageManagerTests will need to be
4696         * revised when this is changed back..
4697         */
4698        if (userId == 0) {
4699            return new File(mAppDataDir, packageName);
4700        } else {
4701            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4702                + File.separator + packageName);
4703        }
4704    }
4705
4706    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4707        int[] users = sUserManager.getUserIds();
4708        int res = mInstaller.install(packageName, uid, uid, seinfo);
4709        if (res < 0) {
4710            return res;
4711        }
4712        for (int user : users) {
4713            if (user != 0) {
4714                res = mInstaller.createUserData(packageName,
4715                        UserHandle.getUid(user, uid), user, seinfo);
4716                if (res < 0) {
4717                    return res;
4718                }
4719            }
4720        }
4721        return res;
4722    }
4723
4724    private int removeDataDirsLI(String packageName) {
4725        int[] users = sUserManager.getUserIds();
4726        int res = 0;
4727        for (int user : users) {
4728            int resInner = mInstaller.remove(packageName, user);
4729            if (resInner < 0) {
4730                res = resInner;
4731            }
4732        }
4733
4734        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4735        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4736        if (!nativeLibraryFile.delete()) {
4737            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4738        }
4739
4740        return res;
4741    }
4742
4743    private int addSharedLibraryLPw(final SharedLibraryEntry file, int num,
4744            PackageParser.Package changingLib) {
4745        if (file.path != null) {
4746            mTmpSharedLibraries[num] = file.path;
4747            return num+1;
4748        }
4749        PackageParser.Package p = mPackages.get(file.apk);
4750        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4751            // If we are doing this while in the middle of updating a library apk,
4752            // then we need to make sure to use that new apk for determining the
4753            // dependencies here.  (We haven't yet finished committing the new apk
4754            // to the package manager state.)
4755            if (p == null || p.packageName.equals(changingLib.packageName)) {
4756                p = changingLib;
4757            }
4758        }
4759        if (p != null) {
4760            String path = p.mPath;
4761            for (int i=0; i<num; i++) {
4762                if (mTmpSharedLibraries[i].equals(path)) {
4763                    return num;
4764                }
4765            }
4766            mTmpSharedLibraries[num] = p.mPath;
4767            return num+1;
4768        }
4769        return num;
4770    }
4771
4772    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4773            PackageParser.Package changingLib) {
4774        // We might be upgrading from a version of the platform that did not
4775        // provide per-package native library directories for system apps.
4776        // Fix that up here.
4777        if (isSystemApp(pkg)) {
4778            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4779            setInternalAppNativeLibraryPath(pkg, ps);
4780        }
4781
4782        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4783            if (mTmpSharedLibraries == null ||
4784                    mTmpSharedLibraries.length < mSharedLibraries.size()) {
4785                mTmpSharedLibraries = new String[mSharedLibraries.size()];
4786            }
4787            int num = 0;
4788            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4789            for (int i=0; i<N; i++) {
4790                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4791                if (file == null) {
4792                    Slog.e(TAG, "Package " + pkg.packageName
4793                            + " requires unavailable shared library "
4794                            + pkg.usesLibraries.get(i) + "; failing!");
4795                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4796                    return false;
4797                }
4798                num = addSharedLibraryLPw(file, num, changingLib);
4799            }
4800            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4801            for (int i=0; i<N; i++) {
4802                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4803                if (file == null) {
4804                    Slog.w(TAG, "Package " + pkg.packageName
4805                            + " desires unavailable shared library "
4806                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4807                } else {
4808                    num = addSharedLibraryLPw(file, num, changingLib);
4809                }
4810            }
4811            if (num > 0) {
4812                pkg.usesLibraryFiles = new String[num];
4813                System.arraycopy(mTmpSharedLibraries, 0,
4814                        pkg.usesLibraryFiles, 0, num);
4815            } else {
4816                pkg.usesLibraryFiles = null;
4817            }
4818        }
4819        return true;
4820    }
4821
4822    private static boolean hasString(List<String> list, List<String> which) {
4823        if (list == null) {
4824            return false;
4825        }
4826        for (int i=list.size()-1; i>=0; i--) {
4827            for (int j=which.size()-1; j>=0; j--) {
4828                if (which.get(j).equals(list.get(i))) {
4829                    return true;
4830                }
4831            }
4832        }
4833        return false;
4834    }
4835
4836    private void updateAllSharedLibrariesLPw() {
4837        for (PackageParser.Package pkg : mPackages.values()) {
4838            updateSharedLibrariesLPw(pkg, null);
4839        }
4840    }
4841
4842    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4843            PackageParser.Package changingPkg) {
4844        ArrayList<PackageParser.Package> res = null;
4845        for (PackageParser.Package pkg : mPackages.values()) {
4846            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4847                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4848                if (res == null) {
4849                    res = new ArrayList<PackageParser.Package>();
4850                }
4851                res.add(pkg);
4852                updateSharedLibrariesLPw(pkg, changingPkg);
4853            }
4854        }
4855        return res;
4856    }
4857
4858    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4859            int parseFlags, int scanMode, long currentTime, UserHandle user) {
4860        File scanFile = new File(pkg.mScanPath);
4861        if (scanFile == null || pkg.applicationInfo.sourceDir == null ||
4862                pkg.applicationInfo.publicSourceDir == null) {
4863            // Bail out. The resource and code paths haven't been set.
4864            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4865            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4866            return null;
4867        }
4868
4869        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4870            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4871        }
4872
4873        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4874            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4875        }
4876
4877        if (mCustomResolverComponentName != null &&
4878                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4879            setUpCustomResolverActivity(pkg);
4880        }
4881
4882        if (pkg.packageName.equals("android")) {
4883            synchronized (mPackages) {
4884                if (mAndroidApplication != null) {
4885                    Slog.w(TAG, "*************************************************");
4886                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4887                    Slog.w(TAG, " file=" + scanFile);
4888                    Slog.w(TAG, "*************************************************");
4889                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4890                    return null;
4891                }
4892
4893                // Set up information for our fall-back user intent resolution activity.
4894                mPlatformPackage = pkg;
4895                pkg.mVersionCode = mSdkVersion;
4896                mAndroidApplication = pkg.applicationInfo;
4897
4898                if (!mResolverReplaced) {
4899                    mResolveActivity.applicationInfo = mAndroidApplication;
4900                    mResolveActivity.name = ResolverActivity.class.getName();
4901                    mResolveActivity.packageName = mAndroidApplication.packageName;
4902                    mResolveActivity.processName = "system:ui";
4903                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4904                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4905                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
4906                    mResolveActivity.exported = true;
4907                    mResolveActivity.enabled = true;
4908                    mResolveInfo.activityInfo = mResolveActivity;
4909                    mResolveInfo.priority = 0;
4910                    mResolveInfo.preferredOrder = 0;
4911                    mResolveInfo.match = 0;
4912                    mResolveComponentName = new ComponentName(
4913                            mAndroidApplication.packageName, mResolveActivity.name);
4914                }
4915            }
4916        }
4917
4918        if (DEBUG_PACKAGE_SCANNING) {
4919            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4920                Log.d(TAG, "Scanning package " + pkg.packageName);
4921        }
4922
4923        if (mPackages.containsKey(pkg.packageName)
4924                || mSharedLibraries.containsKey(pkg.packageName)) {
4925            Slog.w(TAG, "Application package " + pkg.packageName
4926                    + " already installed.  Skipping duplicate.");
4927            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4928            return null;
4929        }
4930
4931        // Initialize package source and resource directories
4932        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
4933        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
4934
4935        SharedUserSetting suid = null;
4936        PackageSetting pkgSetting = null;
4937
4938        if (!isSystemApp(pkg)) {
4939            // Only system apps can use these features.
4940            pkg.mOriginalPackages = null;
4941            pkg.mRealPackage = null;
4942            pkg.mAdoptPermissions = null;
4943        }
4944
4945        // writer
4946        synchronized (mPackages) {
4947            if (pkg.mSharedUserId != null) {
4948                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
4949                if (suid == null) {
4950                    Slog.w(TAG, "Creating application package " + pkg.packageName
4951                            + " for shared user failed");
4952                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4953                    return null;
4954                }
4955                if (DEBUG_PACKAGE_SCANNING) {
4956                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4957                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
4958                                + "): packages=" + suid.packages);
4959                }
4960            }
4961
4962            // Check if we are renaming from an original package name.
4963            PackageSetting origPackage = null;
4964            String realName = null;
4965            if (pkg.mOriginalPackages != null) {
4966                // This package may need to be renamed to a previously
4967                // installed name.  Let's check on that...
4968                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
4969                if (pkg.mOriginalPackages.contains(renamed)) {
4970                    // This package had originally been installed as the
4971                    // original name, and we have already taken care of
4972                    // transitioning to the new one.  Just update the new
4973                    // one to continue using the old name.
4974                    realName = pkg.mRealPackage;
4975                    if (!pkg.packageName.equals(renamed)) {
4976                        // Callers into this function may have already taken
4977                        // care of renaming the package; only do it here if
4978                        // it is not already done.
4979                        pkg.setPackageName(renamed);
4980                    }
4981
4982                } else {
4983                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
4984                        if ((origPackage = mSettings.peekPackageLPr(
4985                                pkg.mOriginalPackages.get(i))) != null) {
4986                            // We do have the package already installed under its
4987                            // original name...  should we use it?
4988                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
4989                                // New package is not compatible with original.
4990                                origPackage = null;
4991                                continue;
4992                            } else if (origPackage.sharedUser != null) {
4993                                // Make sure uid is compatible between packages.
4994                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
4995                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
4996                                            + " to " + pkg.packageName + ": old uid "
4997                                            + origPackage.sharedUser.name
4998                                            + " differs from " + pkg.mSharedUserId);
4999                                    origPackage = null;
5000                                    continue;
5001                                }
5002                            } else {
5003                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5004                                        + pkg.packageName + " to old name " + origPackage.name);
5005                            }
5006                            break;
5007                        }
5008                    }
5009                }
5010            }
5011
5012            if (mTransferedPackages.contains(pkg.packageName)) {
5013                Slog.w(TAG, "Package " + pkg.packageName
5014                        + " was transferred to another, but its .apk remains");
5015            }
5016
5017            // Just create the setting, don't add it yet. For already existing packages
5018            // the PkgSetting exists already and doesn't have to be created.
5019            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5020                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
5021                    pkg.applicationInfo.requiredCpuAbi,
5022                    pkg.applicationInfo.flags, user, false);
5023            if (pkgSetting == null) {
5024                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
5025                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5026                return null;
5027            }
5028
5029            if (pkgSetting.origPackage != null) {
5030                // If we are first transitioning from an original package,
5031                // fix up the new package's name now.  We need to do this after
5032                // looking up the package under its new name, so getPackageLP
5033                // can take care of fiddling things correctly.
5034                pkg.setPackageName(origPackage.name);
5035
5036                // File a report about this.
5037                String msg = "New package " + pkgSetting.realName
5038                        + " renamed to replace old package " + pkgSetting.name;
5039                reportSettingsProblem(Log.WARN, msg);
5040
5041                // Make a note of it.
5042                mTransferedPackages.add(origPackage.name);
5043
5044                // No longer need to retain this.
5045                pkgSetting.origPackage = null;
5046            }
5047
5048            if (realName != null) {
5049                // Make a note of it.
5050                mTransferedPackages.add(pkg.packageName);
5051            }
5052
5053            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5054                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5055            }
5056
5057            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5058                // Check all shared libraries and map to their actual file path.
5059                // We only do this here for apps not on a system dir, because those
5060                // are the only ones that can fail an install due to this.  We
5061                // will take care of the system apps by updating all of their
5062                // library paths after the scan is done.
5063                if (!updateSharedLibrariesLPw(pkg, null)) {
5064                    return null;
5065                }
5066            }
5067
5068            if (mFoundPolicyFile) {
5069                SELinuxMMAC.assignSeinfoValue(pkg);
5070            }
5071
5072            pkg.applicationInfo.uid = pkgSetting.appId;
5073            pkg.mExtras = pkgSetting;
5074
5075            if (!verifySignaturesLP(pkgSetting, pkg)) {
5076                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5077                    return null;
5078                }
5079                // The signature has changed, but this package is in the system
5080                // image...  let's recover!
5081                pkgSetting.signatures.mSignatures = pkg.mSignatures;
5082                // However...  if this package is part of a shared user, but it
5083                // doesn't match the signature of the shared user, let's fail.
5084                // What this means is that you can't change the signatures
5085                // associated with an overall shared user, which doesn't seem all
5086                // that unreasonable.
5087                if (pkgSetting.sharedUser != null) {
5088                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5089                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5090                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
5091                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5092                        return null;
5093                    }
5094                }
5095                // File a report about this.
5096                String msg = "System package " + pkg.packageName
5097                        + " signature changed; retaining data.";
5098                reportSettingsProblem(Log.WARN, msg);
5099            }
5100
5101            // Verify that this new package doesn't have any content providers
5102            // that conflict with existing packages.  Only do this if the
5103            // package isn't already installed, since we don't want to break
5104            // things that are installed.
5105            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5106                final int N = pkg.providers.size();
5107                int i;
5108                for (i=0; i<N; i++) {
5109                    PackageParser.Provider p = pkg.providers.get(i);
5110                    if (p.info.authority != null) {
5111                        String names[] = p.info.authority.split(";");
5112                        for (int j = 0; j < names.length; j++) {
5113                            if (mProvidersByAuthority.containsKey(names[j])) {
5114                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5115                                Slog.w(TAG, "Can't install because provider name " + names[j] +
5116                                        " (in package " + pkg.applicationInfo.packageName +
5117                                        ") is already used by "
5118                                        + ((other != null && other.getComponentName() != null)
5119                                                ? other.getComponentName().getPackageName() : "?"));
5120                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
5121                                return null;
5122                            }
5123                        }
5124                    }
5125                }
5126            }
5127
5128            if (pkg.mAdoptPermissions != null) {
5129                // This package wants to adopt ownership of permissions from
5130                // another package.
5131                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5132                    final String origName = pkg.mAdoptPermissions.get(i);
5133                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5134                    if (orig != null) {
5135                        if (verifyPackageUpdateLPr(orig, pkg)) {
5136                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5137                                    + pkg.packageName);
5138                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5139                        }
5140                    }
5141                }
5142            }
5143        }
5144
5145        final String pkgName = pkg.packageName;
5146
5147        final long scanFileTime = scanFile.lastModified();
5148        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5149        pkg.applicationInfo.processName = fixProcessName(
5150                pkg.applicationInfo.packageName,
5151                pkg.applicationInfo.processName,
5152                pkg.applicationInfo.uid);
5153
5154        File dataPath;
5155        if (mPlatformPackage == pkg) {
5156            // The system package is special.
5157            dataPath = new File (Environment.getDataDirectory(), "system");
5158            pkg.applicationInfo.dataDir = dataPath.getPath();
5159        } else {
5160            // This is a normal package, need to make its data directory.
5161            dataPath = getDataPathForPackage(pkg.packageName, 0);
5162
5163            boolean uidError = false;
5164
5165            if (dataPath.exists()) {
5166                int currentUid = 0;
5167                try {
5168                    StructStat stat = Os.stat(dataPath.getPath());
5169                    currentUid = stat.st_uid;
5170                } catch (ErrnoException e) {
5171                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5172                }
5173
5174                // If we have mismatched owners for the data path, we have a problem.
5175                if (currentUid != pkg.applicationInfo.uid) {
5176                    boolean recovered = false;
5177                    if (currentUid == 0) {
5178                        // The directory somehow became owned by root.  Wow.
5179                        // This is probably because the system was stopped while
5180                        // installd was in the middle of messing with its libs
5181                        // directory.  Ask installd to fix that.
5182                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5183                                pkg.applicationInfo.uid);
5184                        if (ret >= 0) {
5185                            recovered = true;
5186                            String msg = "Package " + pkg.packageName
5187                                    + " unexpectedly changed to uid 0; recovered to " +
5188                                    + pkg.applicationInfo.uid;
5189                            reportSettingsProblem(Log.WARN, msg);
5190                        }
5191                    }
5192                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5193                            || (scanMode&SCAN_BOOTING) != 0)) {
5194                        // If this is a system app, we can at least delete its
5195                        // current data so the application will still work.
5196                        int ret = removeDataDirsLI(pkgName);
5197                        if (ret >= 0) {
5198                            // TODO: Kill the processes first
5199                            // Old data gone!
5200                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5201                                    ? "System package " : "Third party package ";
5202                            String msg = prefix + pkg.packageName
5203                                    + " has changed from uid: "
5204                                    + currentUid + " to "
5205                                    + pkg.applicationInfo.uid + "; old data erased";
5206                            reportSettingsProblem(Log.WARN, msg);
5207                            recovered = true;
5208
5209                            // And now re-install the app.
5210                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5211                                                   pkg.applicationInfo.seinfo);
5212                            if (ret == -1) {
5213                                // Ack should not happen!
5214                                msg = prefix + pkg.packageName
5215                                        + " could not have data directory re-created after delete.";
5216                                reportSettingsProblem(Log.WARN, msg);
5217                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5218                                return null;
5219                            }
5220                        }
5221                        if (!recovered) {
5222                            mHasSystemUidErrors = true;
5223                        }
5224                    } else if (!recovered) {
5225                        // If we allow this install to proceed, we will be broken.
5226                        // Abort, abort!
5227                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
5228                        return null;
5229                    }
5230                    if (!recovered) {
5231                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5232                            + pkg.applicationInfo.uid + "/fs_"
5233                            + currentUid;
5234                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5235                        String msg = "Package " + pkg.packageName
5236                                + " has mismatched uid: "
5237                                + currentUid + " on disk, "
5238                                + pkg.applicationInfo.uid + " in settings";
5239                        // writer
5240                        synchronized (mPackages) {
5241                            mSettings.mReadMessages.append(msg);
5242                            mSettings.mReadMessages.append('\n');
5243                            uidError = true;
5244                            if (!pkgSetting.uidError) {
5245                                reportSettingsProblem(Log.ERROR, msg);
5246                            }
5247                        }
5248                    }
5249                }
5250                pkg.applicationInfo.dataDir = dataPath.getPath();
5251                if (mShouldRestoreconData) {
5252                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5253                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5254                                pkg.applicationInfo.uid);
5255                }
5256            } else {
5257                if (DEBUG_PACKAGE_SCANNING) {
5258                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5259                        Log.v(TAG, "Want this data dir: " + dataPath);
5260                }
5261                //invoke installer to do the actual installation
5262                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5263                                           pkg.applicationInfo.seinfo);
5264                if (ret < 0) {
5265                    // Error from installer
5266                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5267                    return null;
5268                }
5269
5270                if (dataPath.exists()) {
5271                    pkg.applicationInfo.dataDir = dataPath.getPath();
5272                } else {
5273                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5274                    pkg.applicationInfo.dataDir = null;
5275                }
5276            }
5277
5278            /*
5279             * Set the data dir to the default "/data/data/<package name>/lib"
5280             * if we got here without anyone telling us different (e.g., apps
5281             * stored on SD card have their native libraries stored in the ASEC
5282             * container with the APK).
5283             *
5284             * This happens during an upgrade from a package settings file that
5285             * doesn't have a native library path attribute at all.
5286             */
5287            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
5288                if (pkgSetting.nativeLibraryPathString == null) {
5289                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
5290                } else {
5291                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
5292                }
5293            }
5294            pkgSetting.uidError = uidError;
5295        }
5296
5297        String path = scanFile.getPath();
5298        /* Note: We don't want to unpack the native binaries for
5299         *        system applications, unless they have been updated
5300         *        (the binaries are already under /system/lib).
5301         *        Also, don't unpack libs for apps on the external card
5302         *        since they should have their libraries in the ASEC
5303         *        container already.
5304         *
5305         *        In other words, we're going to unpack the binaries
5306         *        only for non-system apps and system app upgrades.
5307         */
5308        if (pkg.applicationInfo.nativeLibraryDir != null) {
5309            try {
5310                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5311                final String dataPathString = dataPath.getCanonicalPath();
5312
5313                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5314                    /*
5315                     * Upgrading from a previous version of the OS sometimes
5316                     * leaves native libraries in the /data/data/<app>/lib
5317                     * directory for system apps even when they shouldn't be.
5318                     * Recent changes in the JNI library search path
5319                     * necessitates we remove those to match previous behavior.
5320                     */
5321                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
5322                        Log.i(TAG, "removed obsolete native libraries for system package "
5323                                + path);
5324                    }
5325
5326                    setInternalAppAbi(pkg, pkgSetting);
5327                } else {
5328                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
5329                        /*
5330                         * Update native library dir if it starts with
5331                         * /data/data
5332                         */
5333                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
5334                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
5335                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5336                        }
5337
5338                        try {
5339                            int copyRet = copyNativeLibrariesForInternalApp(scanFile, nativeLibraryDir);
5340                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5341                                Slog.e(TAG, "Unable to copy native libraries");
5342                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5343                                return null;
5344                            }
5345
5346                            // We've successfully copied native libraries across, so we make a
5347                            // note of what ABI we're using
5348                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5349                                pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[copyRet];
5350                            } else {
5351                                pkg.applicationInfo.requiredCpuAbi = null;
5352                            }
5353                        } catch (IOException e) {
5354                            Slog.e(TAG, "Unable to copy native libraries", e);
5355                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5356                            return null;
5357                        }
5358                    } else {
5359                        // We don't have to copy the shared libraries if we're in the ASEC container
5360                        // but we still need to scan the file to figure out what ABI the app needs.
5361                        //
5362                        // TODO: This duplicates work done in the default container service. It's possible
5363                        // to clean this up but we'll need to change the interface between this service
5364                        // and IMediaContainerService (but doing so will spread this logic out, rather
5365                        // than centralizing it).
5366                        final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5367                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS);
5368                        if (abi >= 0) {
5369                            pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_ABIS[abi];
5370                        } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) {
5371                            // Note that (non upgraded) system apps will not have any native
5372                            // libraries bundled in their APK, but we're guaranteed not to be
5373                            // such an app at this point.
5374                            pkg.applicationInfo.requiredCpuAbi = null;
5375                        } else {
5376                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5377                            return null;
5378                        }
5379                        handle.close();
5380                    }
5381
5382                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5383                    final int[] userIds = sUserManager.getUserIds();
5384                    synchronized (mInstallLock) {
5385                        for (int userId : userIds) {
5386                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
5387                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
5388                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
5389                                        + ")");
5390                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5391                                return null;
5392                            }
5393                        }
5394                    }
5395                }
5396            } catch (IOException ioe) {
5397                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5398            }
5399        }
5400        pkg.mScanPath = path;
5401
5402        if ((scanMode&SCAN_NO_DEX) == 0) {
5403            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5404                    == DEX_OPT_FAILED) {
5405                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5406                    removeDataDirsLI(pkg.packageName);
5407                }
5408
5409                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5410                return null;
5411            }
5412        }
5413
5414        if (mFactoryTest && pkg.requestedPermissions.contains(
5415                android.Manifest.permission.FACTORY_TEST)) {
5416            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5417        }
5418
5419        ArrayList<PackageParser.Package> clientLibPkgs = null;
5420
5421        // writer
5422        synchronized (mPackages) {
5423            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5424                // Only system apps can add new shared libraries.
5425                if (pkg.libraryNames != null) {
5426                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5427                        String name = pkg.libraryNames.get(i);
5428                        boolean allowed = false;
5429                        if (isUpdatedSystemApp(pkg)) {
5430                            // New library entries can only be added through the
5431                            // system image.  This is important to get rid of a lot
5432                            // of nasty edge cases: for example if we allowed a non-
5433                            // system update of the app to add a library, then uninstalling
5434                            // the update would make the library go away, and assumptions
5435                            // we made such as through app install filtering would now
5436                            // have allowed apps on the device which aren't compatible
5437                            // with it.  Better to just have the restriction here, be
5438                            // conservative, and create many fewer cases that can negatively
5439                            // impact the user experience.
5440                            final PackageSetting sysPs = mSettings
5441                                    .getDisabledSystemPkgLPr(pkg.packageName);
5442                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5443                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5444                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5445                                        allowed = true;
5446                                        allowed = true;
5447                                        break;
5448                                    }
5449                                }
5450                            }
5451                        } else {
5452                            allowed = true;
5453                        }
5454                        if (allowed) {
5455                            if (!mSharedLibraries.containsKey(name)) {
5456                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5457                            } else if (!name.equals(pkg.packageName)) {
5458                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5459                                        + name + " already exists; skipping");
5460                            }
5461                        } else {
5462                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5463                                    + name + " that is not declared on system image; skipping");
5464                        }
5465                    }
5466                    if ((scanMode&SCAN_BOOTING) == 0) {
5467                        // If we are not booting, we need to update any applications
5468                        // that are clients of our shared library.  If we are booting,
5469                        // this will all be done once the scan is complete.
5470                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5471                    }
5472                }
5473            }
5474        }
5475
5476        // We also need to dexopt any apps that are dependent on this library.  Note that
5477        // if these fail, we should abort the install since installing the library will
5478        // result in some apps being broken.
5479        if (clientLibPkgs != null) {
5480            if ((scanMode&SCAN_NO_DEX) == 0) {
5481                for (int i=0; i<clientLibPkgs.size(); i++) {
5482                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5483                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5484                            == DEX_OPT_FAILED) {
5485                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5486                            removeDataDirsLI(pkg.packageName);
5487                        }
5488
5489                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5490                        return null;
5491                    }
5492                }
5493            }
5494        }
5495
5496        // Request the ActivityManager to kill the process(only for existing packages)
5497        // so that we do not end up in a confused state while the user is still using the older
5498        // version of the application while the new one gets installed.
5499        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5500            // If the package lives in an asec, tell everyone that the container is going
5501            // away so they can clean up any references to its resources (which would prevent
5502            // vold from being able to unmount the asec)
5503            if (isForwardLocked(pkg) || isExternal(pkg)) {
5504                if (DEBUG_INSTALL) {
5505                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5506                }
5507                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5508                final ArrayList<String> pkgList = new ArrayList<String>(1);
5509                pkgList.add(pkg.applicationInfo.packageName);
5510                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5511            }
5512
5513            // Post the request that it be killed now that the going-away broadcast is en route
5514            killApplication(pkg.applicationInfo.packageName,
5515                        pkg.applicationInfo.uid, "update pkg");
5516        }
5517
5518        // Also need to kill any apps that are dependent on the library.
5519        if (clientLibPkgs != null) {
5520            for (int i=0; i<clientLibPkgs.size(); i++) {
5521                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5522                killApplication(clientPkg.applicationInfo.packageName,
5523                        clientPkg.applicationInfo.uid, "update lib");
5524            }
5525        }
5526
5527        // writer
5528        synchronized (mPackages) {
5529            if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5530                // We don't do this here during boot because we can do it all
5531                // at once after scanning all existing packages.
5532                adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5533                        true, forceDex, (scanMode & SCAN_DEFER_DEX) != 0);
5534            }
5535            // We don't expect installation to fail beyond this point,
5536            if ((scanMode&SCAN_MONITOR) != 0) {
5537                mAppDirs.put(pkg.mPath, pkg);
5538            }
5539            // Add the new setting to mSettings
5540            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5541            // Add the new setting to mPackages
5542            mPackages.put(pkg.applicationInfo.packageName, pkg);
5543            // Make sure we don't accidentally delete its data.
5544            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5545            while (iter.hasNext()) {
5546                PackageCleanItem item = iter.next();
5547                if (pkgName.equals(item.packageName)) {
5548                    iter.remove();
5549                }
5550            }
5551
5552            // Take care of first install / last update times.
5553            if (currentTime != 0) {
5554                if (pkgSetting.firstInstallTime == 0) {
5555                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5556                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5557                    pkgSetting.lastUpdateTime = currentTime;
5558                }
5559            } else if (pkgSetting.firstInstallTime == 0) {
5560                // We need *something*.  Take time time stamp of the file.
5561                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5562            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5563                if (scanFileTime != pkgSetting.timeStamp) {
5564                    // A package on the system image has changed; consider this
5565                    // to be an update.
5566                    pkgSetting.lastUpdateTime = scanFileTime;
5567                }
5568            }
5569
5570            // Add the package's KeySets to the global KeySetManager
5571            KeySetManager ksm = mSettings.mKeySetManager;
5572            try {
5573                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5574                if (pkg.mKeySetMapping != null) {
5575                    for (Map.Entry<String, Set<PublicKey>> entry : pkg.mKeySetMapping.entrySet()) {
5576                        if (entry.getValue() != null) {
5577                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5578                                entry.getValue(), entry.getKey());
5579                        }
5580                    }
5581                }
5582            } catch (NullPointerException e) {
5583                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5584            } catch (IllegalArgumentException e) {
5585                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5586            }
5587
5588            int N = pkg.providers.size();
5589            StringBuilder r = null;
5590            int i;
5591            for (i=0; i<N; i++) {
5592                PackageParser.Provider p = pkg.providers.get(i);
5593                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5594                        p.info.processName, pkg.applicationInfo.uid);
5595                mProviders.addProvider(p);
5596                p.syncable = p.info.isSyncable;
5597                if (p.info.authority != null) {
5598                    String names[] = p.info.authority.split(";");
5599                    p.info.authority = null;
5600                    for (int j = 0; j < names.length; j++) {
5601                        if (j == 1 && p.syncable) {
5602                            // We only want the first authority for a provider to possibly be
5603                            // syncable, so if we already added this provider using a different
5604                            // authority clear the syncable flag. We copy the provider before
5605                            // changing it because the mProviders object contains a reference
5606                            // to a provider that we don't want to change.
5607                            // Only do this for the second authority since the resulting provider
5608                            // object can be the same for all future authorities for this provider.
5609                            p = new PackageParser.Provider(p);
5610                            p.syncable = false;
5611                        }
5612                        if (!mProvidersByAuthority.containsKey(names[j])) {
5613                            mProvidersByAuthority.put(names[j], p);
5614                            if (p.info.authority == null) {
5615                                p.info.authority = names[j];
5616                            } else {
5617                                p.info.authority = p.info.authority + ";" + names[j];
5618                            }
5619                            if (DEBUG_PACKAGE_SCANNING) {
5620                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5621                                    Log.d(TAG, "Registered content provider: " + names[j]
5622                                            + ", className = " + p.info.name + ", isSyncable = "
5623                                            + p.info.isSyncable);
5624                            }
5625                        } else {
5626                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5627                            Slog.w(TAG, "Skipping provider name " + names[j] +
5628                                    " (in package " + pkg.applicationInfo.packageName +
5629                                    "): name already used by "
5630                                    + ((other != null && other.getComponentName() != null)
5631                                            ? other.getComponentName().getPackageName() : "?"));
5632                        }
5633                    }
5634                }
5635                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5636                    if (r == null) {
5637                        r = new StringBuilder(256);
5638                    } else {
5639                        r.append(' ');
5640                    }
5641                    r.append(p.info.name);
5642                }
5643            }
5644            if (r != null) {
5645                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5646            }
5647
5648            N = pkg.services.size();
5649            r = null;
5650            for (i=0; i<N; i++) {
5651                PackageParser.Service s = pkg.services.get(i);
5652                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5653                        s.info.processName, pkg.applicationInfo.uid);
5654                mServices.addService(s);
5655                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5656                    if (r == null) {
5657                        r = new StringBuilder(256);
5658                    } else {
5659                        r.append(' ');
5660                    }
5661                    r.append(s.info.name);
5662                }
5663            }
5664            if (r != null) {
5665                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5666            }
5667
5668            N = pkg.receivers.size();
5669            r = null;
5670            for (i=0; i<N; i++) {
5671                PackageParser.Activity a = pkg.receivers.get(i);
5672                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5673                        a.info.processName, pkg.applicationInfo.uid);
5674                mReceivers.addActivity(a, "receiver");
5675                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5676                    if (r == null) {
5677                        r = new StringBuilder(256);
5678                    } else {
5679                        r.append(' ');
5680                    }
5681                    r.append(a.info.name);
5682                }
5683            }
5684            if (r != null) {
5685                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5686            }
5687
5688            N = pkg.activities.size();
5689            r = null;
5690            for (i=0; i<N; i++) {
5691                PackageParser.Activity a = pkg.activities.get(i);
5692                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5693                        a.info.processName, pkg.applicationInfo.uid);
5694                mActivities.addActivity(a, "activity");
5695                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5696                    if (r == null) {
5697                        r = new StringBuilder(256);
5698                    } else {
5699                        r.append(' ');
5700                    }
5701                    r.append(a.info.name);
5702                }
5703            }
5704            if (r != null) {
5705                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5706            }
5707
5708            N = pkg.permissionGroups.size();
5709            r = null;
5710            for (i=0; i<N; i++) {
5711                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5712                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5713                if (cur == null) {
5714                    mPermissionGroups.put(pg.info.name, pg);
5715                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5716                        if (r == null) {
5717                            r = new StringBuilder(256);
5718                        } else {
5719                            r.append(' ');
5720                        }
5721                        r.append(pg.info.name);
5722                    }
5723                } else {
5724                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5725                            + pg.info.packageName + " ignored: original from "
5726                            + cur.info.packageName);
5727                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5728                        if (r == null) {
5729                            r = new StringBuilder(256);
5730                        } else {
5731                            r.append(' ');
5732                        }
5733                        r.append("DUP:");
5734                        r.append(pg.info.name);
5735                    }
5736                }
5737            }
5738            if (r != null) {
5739                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5740            }
5741
5742            N = pkg.permissions.size();
5743            r = null;
5744            for (i=0; i<N; i++) {
5745                PackageParser.Permission p = pkg.permissions.get(i);
5746                HashMap<String, BasePermission> permissionMap =
5747                        p.tree ? mSettings.mPermissionTrees
5748                        : mSettings.mPermissions;
5749                p.group = mPermissionGroups.get(p.info.group);
5750                if (p.info.group == null || p.group != null) {
5751                    BasePermission bp = permissionMap.get(p.info.name);
5752                    if (bp == null) {
5753                        bp = new BasePermission(p.info.name, p.info.packageName,
5754                                BasePermission.TYPE_NORMAL);
5755                        permissionMap.put(p.info.name, bp);
5756                    }
5757                    if (bp.perm == null) {
5758                        if (bp.sourcePackage != null
5759                                && !bp.sourcePackage.equals(p.info.packageName)) {
5760                            // If this is a permission that was formerly defined by a non-system
5761                            // app, but is now defined by a system app (following an upgrade),
5762                            // discard the previous declaration and consider the system's to be
5763                            // canonical.
5764                            if (isSystemApp(p.owner)) {
5765                                String msg = "New decl " + p.owner + " of permission  "
5766                                        + p.info.name + " is system";
5767                                reportSettingsProblem(Log.WARN, msg);
5768                                bp.sourcePackage = null;
5769                            }
5770                        }
5771                        if (bp.sourcePackage == null
5772                                || bp.sourcePackage.equals(p.info.packageName)) {
5773                            BasePermission tree = findPermissionTreeLP(p.info.name);
5774                            if (tree == null
5775                                    || tree.sourcePackage.equals(p.info.packageName)) {
5776                                bp.packageSetting = pkgSetting;
5777                                bp.perm = p;
5778                                bp.uid = pkg.applicationInfo.uid;
5779                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5780                                    if (r == null) {
5781                                        r = new StringBuilder(256);
5782                                    } else {
5783                                        r.append(' ');
5784                                    }
5785                                    r.append(p.info.name);
5786                                }
5787                            } else {
5788                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5789                                        + p.info.packageName + " ignored: base tree "
5790                                        + tree.name + " is from package "
5791                                        + tree.sourcePackage);
5792                            }
5793                        } else {
5794                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5795                                    + p.info.packageName + " ignored: original from "
5796                                    + bp.sourcePackage);
5797                        }
5798                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5799                        if (r == null) {
5800                            r = new StringBuilder(256);
5801                        } else {
5802                            r.append(' ');
5803                        }
5804                        r.append("DUP:");
5805                        r.append(p.info.name);
5806                    }
5807                    if (bp.perm == p) {
5808                        bp.protectionLevel = p.info.protectionLevel;
5809                    }
5810                } else {
5811                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5812                            + p.info.packageName + " ignored: no group "
5813                            + p.group);
5814                }
5815            }
5816            if (r != null) {
5817                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5818            }
5819
5820            N = pkg.instrumentation.size();
5821            r = null;
5822            for (i=0; i<N; i++) {
5823                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5824                a.info.packageName = pkg.applicationInfo.packageName;
5825                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5826                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5827                a.info.dataDir = pkg.applicationInfo.dataDir;
5828                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5829                mInstrumentation.put(a.getComponentName(), a);
5830                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5831                    if (r == null) {
5832                        r = new StringBuilder(256);
5833                    } else {
5834                        r.append(' ');
5835                    }
5836                    r.append(a.info.name);
5837                }
5838            }
5839            if (r != null) {
5840                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5841            }
5842
5843            if (pkg.protectedBroadcasts != null) {
5844                N = pkg.protectedBroadcasts.size();
5845                for (i=0; i<N; i++) {
5846                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5847                }
5848            }
5849
5850            pkgSetting.setTimeStamp(scanFileTime);
5851
5852            // Create idmap files for pairs of (packages, overlay packages).
5853            // Note: "android", ie framework-res.apk, is handled by native layers.
5854            if (pkg.mOverlayTarget != null) {
5855                // This is an overlay package.
5856                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5857                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5858                        mOverlays.put(pkg.mOverlayTarget,
5859                                new HashMap<String, PackageParser.Package>());
5860                    }
5861                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5862                    map.put(pkg.packageName, pkg);
5863                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5864                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5865                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5866                        return null;
5867                    }
5868                }
5869            } else if (mOverlays.containsKey(pkg.packageName) &&
5870                    !pkg.packageName.equals("android")) {
5871                // This is a regular package, with one or more known overlay packages.
5872                createIdmapsForPackageLI(pkg);
5873            }
5874        }
5875
5876        return pkg;
5877    }
5878
5879    public void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
5880            boolean doDexOpt, boolean forceDexOpt, boolean deferDexOpt) {
5881        String requiredInstructionSet = null;
5882        PackageSetting requirer = null;
5883        for (PackageSetting ps : packagesForUser) {
5884            if (ps.requiredCpuAbiString != null) {
5885                final String instructionSet = VMRuntime.getInstructionSet(ps.requiredCpuAbiString);
5886                if (requiredInstructionSet != null) {
5887                    if (!instructionSet.equals(requiredInstructionSet)) {
5888                        // We have a mismatch between instruction sets (say arm vs arm64).
5889                        //
5890                        // TODO: We should rescan all the packages in a shared UID to check if
5891                        // they do contain shared libs for other ABIs in addition to the ones we've
5892                        // already extracted. For example, the package might contain both arm64-v8a
5893                        // and armeabi-v7a shared libs, and we'd have chosen arm64-v8a on 64 bit
5894                        // devices.
5895                        String errorMessage = "Instruction set mismatch, " + requirer.pkg.packageName
5896                                + " requires " + requiredInstructionSet + " whereas " + ps.pkg.packageName
5897                                + " requires " + instructionSet;
5898                        Slog.e(TAG, errorMessage);
5899
5900                        reportSettingsProblem(Log.WARN, errorMessage);
5901                        // Give up, don't bother making any other changes to the package settings.
5902                        return;
5903                    }
5904                } else {
5905                    requiredInstructionSet = instructionSet;
5906                    requirer = ps;
5907                }
5908            }
5909        }
5910
5911        if (requiredInstructionSet != null) {
5912            for (PackageSetting ps : packagesForUser) {
5913                if (ps.requiredCpuAbiString == null) {
5914                    ps.requiredCpuAbiString = requirer.requiredCpuAbiString;
5915                    if (ps.pkg != null) {
5916                        ps.pkg.applicationInfo.requiredCpuAbi = requirer.requiredCpuAbiString;
5917                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + ps.requiredCpuAbiString);
5918                        if (doDexOpt) {
5919                            performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true);
5920                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
5921                        }
5922                    }
5923                }
5924            }
5925        }
5926    }
5927
5928    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
5929        synchronized (mPackages) {
5930            mResolverReplaced = true;
5931            // Set up information for custom user intent resolution activity.
5932            mResolveActivity.applicationInfo = pkg.applicationInfo;
5933            mResolveActivity.name = mCustomResolverComponentName.getClassName();
5934            mResolveActivity.packageName = pkg.applicationInfo.packageName;
5935            mResolveActivity.processName = null;
5936            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5937            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
5938                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
5939            mResolveActivity.theme = 0;
5940            mResolveActivity.exported = true;
5941            mResolveActivity.enabled = true;
5942            mResolveInfo.activityInfo = mResolveActivity;
5943            mResolveInfo.priority = 0;
5944            mResolveInfo.preferredOrder = 0;
5945            mResolveInfo.match = 0;
5946            mResolveComponentName = mCustomResolverComponentName;
5947            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
5948                    mResolveComponentName);
5949        }
5950    }
5951
5952    private String calculateApkRoot(final String codePathString) {
5953        final File codePath = new File(codePathString);
5954        final File codeRoot;
5955        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
5956            codeRoot = Environment.getRootDirectory();
5957        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
5958            codeRoot = Environment.getOemDirectory();
5959        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
5960            codeRoot = Environment.getVendorDirectory();
5961        } else {
5962            // Unrecognized code path; take its top real segment as the apk root:
5963            // e.g. /something/app/blah.apk => /something
5964            try {
5965                File f = codePath.getCanonicalFile();
5966                File parent = f.getParentFile();    // non-null because codePath is a file
5967                File tmp;
5968                while ((tmp = parent.getParentFile()) != null) {
5969                    f = parent;
5970                    parent = tmp;
5971                }
5972                codeRoot = f;
5973                Slog.w(TAG, "Unrecognized code path "
5974                        + codePath + " - using " + codeRoot);
5975            } catch (IOException e) {
5976                // Can't canonicalize the lib path -- shenanigans?
5977                Slog.w(TAG, "Can't canonicalize code path " + codePath);
5978                return Environment.getRootDirectory().getPath();
5979            }
5980        }
5981        return codeRoot.getPath();
5982    }
5983
5984    // This is the initial scan-time determination of how to handle a given
5985    // package for purposes of native library location.
5986    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
5987            PackageSetting pkgSetting) {
5988        // "bundled" here means system-installed with no overriding update
5989        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
5990        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
5991        final File libDir;
5992        if (bundledApk) {
5993            // If "/system/lib64/apkname" exists, assume that is the per-package
5994            // native library directory to use; otherwise use "/system/lib/apkname".
5995            String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
5996            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
5997            File packLib64 = new File(lib64, apkName);
5998            libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
5999        } else {
6000            libDir = mAppLibInstallDir;
6001        }
6002        final String nativeLibraryPath = (new File(libDir, apkName)).getPath();
6003        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
6004        pkgSetting.nativeLibraryPathString = nativeLibraryPath;
6005    }
6006
6007    // Deduces the required ABI of an upgraded system app.
6008    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
6009        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6010        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6011
6012        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
6013        // or similar.
6014        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
6015        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
6016
6017        // Assume that the bundled native libraries always correspond to the
6018        // most preferred 32 or 64 bit ABI.
6019        if (lib64.exists()) {
6020            pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6021            pkgSetting.requiredCpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
6022        } else if (lib.exists()) {
6023            pkg.applicationInfo.requiredCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6024            pkgSetting.requiredCpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
6025        } else {
6026            // This is the case where the app has no native code.
6027            pkg.applicationInfo.requiredCpuAbi = null;
6028            pkgSetting.requiredCpuAbiString = null;
6029        }
6030    }
6031
6032    private static int copyNativeLibrariesForInternalApp(File scanFile, final File nativeLibraryDir)
6033            throws IOException {
6034        if (!nativeLibraryDir.isDirectory()) {
6035            nativeLibraryDir.delete();
6036
6037            if (!nativeLibraryDir.mkdir()) {
6038                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
6039            }
6040
6041            try {
6042                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6043            } catch (ErrnoException e) {
6044                throw new IOException("Cannot chmod native library directory "
6045                        + nativeLibraryDir.getPath(), e);
6046            }
6047        } else if (!SELinux.restorecon(nativeLibraryDir)) {
6048            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
6049        }
6050
6051        /*
6052         * If this is an internal application or our nativeLibraryPath points to
6053         * the app-lib directory, unpack the libraries if necessary.
6054         */
6055        final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
6056        try {
6057            int abi = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_ABIS);
6058            if (abi >= 0) {
6059                int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
6060                        nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
6061                if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6062                    return copyRet;
6063                }
6064            }
6065
6066            return abi;
6067        } finally {
6068            handle.close();
6069        }
6070    }
6071
6072    private void killApplication(String pkgName, int appId, String reason) {
6073        // Request the ActivityManager to kill the process(only for existing packages)
6074        // so that we do not end up in a confused state while the user is still using the older
6075        // version of the application while the new one gets installed.
6076        IActivityManager am = ActivityManagerNative.getDefault();
6077        if (am != null) {
6078            try {
6079                am.killApplicationWithAppId(pkgName, appId, reason);
6080            } catch (RemoteException e) {
6081            }
6082        }
6083    }
6084
6085    void removePackageLI(PackageSetting ps, boolean chatty) {
6086        if (DEBUG_INSTALL) {
6087            if (chatty)
6088                Log.d(TAG, "Removing package " + ps.name);
6089        }
6090
6091        // writer
6092        synchronized (mPackages) {
6093            mPackages.remove(ps.name);
6094            if (ps.codePathString != null) {
6095                mAppDirs.remove(ps.codePathString);
6096            }
6097
6098            final PackageParser.Package pkg = ps.pkg;
6099            if (pkg != null) {
6100                cleanPackageDataStructuresLILPw(pkg, chatty);
6101            }
6102        }
6103    }
6104
6105    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6106        if (DEBUG_INSTALL) {
6107            if (chatty)
6108                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6109        }
6110
6111        // writer
6112        synchronized (mPackages) {
6113            mPackages.remove(pkg.applicationInfo.packageName);
6114            if (pkg.mPath != null) {
6115                mAppDirs.remove(pkg.mPath);
6116            }
6117            cleanPackageDataStructuresLILPw(pkg, chatty);
6118        }
6119    }
6120
6121    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6122        int N = pkg.providers.size();
6123        StringBuilder r = null;
6124        int i;
6125        for (i=0; i<N; i++) {
6126            PackageParser.Provider p = pkg.providers.get(i);
6127            mProviders.removeProvider(p);
6128            if (p.info.authority == null) {
6129
6130                /* There was another ContentProvider with this authority when
6131                 * this app was installed so this authority is null,
6132                 * Ignore it as we don't have to unregister the provider.
6133                 */
6134                continue;
6135            }
6136            String names[] = p.info.authority.split(";");
6137            for (int j = 0; j < names.length; j++) {
6138                if (mProvidersByAuthority.get(names[j]) == p) {
6139                    mProvidersByAuthority.remove(names[j]);
6140                    if (DEBUG_REMOVE) {
6141                        if (chatty)
6142                            Log.d(TAG, "Unregistered content provider: " + names[j]
6143                                    + ", className = " + p.info.name + ", isSyncable = "
6144                                    + p.info.isSyncable);
6145                    }
6146                }
6147            }
6148            if (DEBUG_REMOVE && chatty) {
6149                if (r == null) {
6150                    r = new StringBuilder(256);
6151                } else {
6152                    r.append(' ');
6153                }
6154                r.append(p.info.name);
6155            }
6156        }
6157        if (r != null) {
6158            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6159        }
6160
6161        N = pkg.services.size();
6162        r = null;
6163        for (i=0; i<N; i++) {
6164            PackageParser.Service s = pkg.services.get(i);
6165            mServices.removeService(s);
6166            if (chatty) {
6167                if (r == null) {
6168                    r = new StringBuilder(256);
6169                } else {
6170                    r.append(' ');
6171                }
6172                r.append(s.info.name);
6173            }
6174        }
6175        if (r != null) {
6176            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6177        }
6178
6179        N = pkg.receivers.size();
6180        r = null;
6181        for (i=0; i<N; i++) {
6182            PackageParser.Activity a = pkg.receivers.get(i);
6183            mReceivers.removeActivity(a, "receiver");
6184            if (DEBUG_REMOVE && chatty) {
6185                if (r == null) {
6186                    r = new StringBuilder(256);
6187                } else {
6188                    r.append(' ');
6189                }
6190                r.append(a.info.name);
6191            }
6192        }
6193        if (r != null) {
6194            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6195        }
6196
6197        N = pkg.activities.size();
6198        r = null;
6199        for (i=0; i<N; i++) {
6200            PackageParser.Activity a = pkg.activities.get(i);
6201            mActivities.removeActivity(a, "activity");
6202            if (DEBUG_REMOVE && chatty) {
6203                if (r == null) {
6204                    r = new StringBuilder(256);
6205                } else {
6206                    r.append(' ');
6207                }
6208                r.append(a.info.name);
6209            }
6210        }
6211        if (r != null) {
6212            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6213        }
6214
6215        N = pkg.permissions.size();
6216        r = null;
6217        for (i=0; i<N; i++) {
6218            PackageParser.Permission p = pkg.permissions.get(i);
6219            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6220            if (bp == null) {
6221                bp = mSettings.mPermissionTrees.get(p.info.name);
6222            }
6223            if (bp != null && bp.perm == p) {
6224                bp.perm = null;
6225                if (DEBUG_REMOVE && chatty) {
6226                    if (r == null) {
6227                        r = new StringBuilder(256);
6228                    } else {
6229                        r.append(' ');
6230                    }
6231                    r.append(p.info.name);
6232                }
6233            }
6234        }
6235        if (r != null) {
6236            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6237        }
6238
6239        N = pkg.instrumentation.size();
6240        r = null;
6241        for (i=0; i<N; i++) {
6242            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6243            mInstrumentation.remove(a.getComponentName());
6244            if (DEBUG_REMOVE && chatty) {
6245                if (r == null) {
6246                    r = new StringBuilder(256);
6247                } else {
6248                    r.append(' ');
6249                }
6250                r.append(a.info.name);
6251            }
6252        }
6253        if (r != null) {
6254            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6255        }
6256
6257        r = null;
6258        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6259            // Only system apps can hold shared libraries.
6260            if (pkg.libraryNames != null) {
6261                for (i=0; i<pkg.libraryNames.size(); i++) {
6262                    String name = pkg.libraryNames.get(i);
6263                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6264                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6265                        mSharedLibraries.remove(name);
6266                        if (DEBUG_REMOVE && chatty) {
6267                            if (r == null) {
6268                                r = new StringBuilder(256);
6269                            } else {
6270                                r.append(' ');
6271                            }
6272                            r.append(name);
6273                        }
6274                    }
6275                }
6276            }
6277        }
6278        if (r != null) {
6279            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6280        }
6281    }
6282
6283    private static final boolean isPackageFilename(String name) {
6284        return name != null && name.endsWith(".apk");
6285    }
6286
6287    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6288        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6289            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6290                return true;
6291            }
6292        }
6293        return false;
6294    }
6295
6296    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6297    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6298    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6299
6300    private void updatePermissionsLPw(String changingPkg,
6301            PackageParser.Package pkgInfo, int flags) {
6302        // Make sure there are no dangling permission trees.
6303        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6304        while (it.hasNext()) {
6305            final BasePermission bp = it.next();
6306            if (bp.packageSetting == null) {
6307                // We may not yet have parsed the package, so just see if
6308                // we still know about its settings.
6309                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6310            }
6311            if (bp.packageSetting == null) {
6312                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6313                        + " from package " + bp.sourcePackage);
6314                it.remove();
6315            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6316                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6317                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6318                            + " from package " + bp.sourcePackage);
6319                    flags |= UPDATE_PERMISSIONS_ALL;
6320                    it.remove();
6321                }
6322            }
6323        }
6324
6325        // Make sure all dynamic permissions have been assigned to a package,
6326        // and make sure there are no dangling permissions.
6327        it = mSettings.mPermissions.values().iterator();
6328        while (it.hasNext()) {
6329            final BasePermission bp = it.next();
6330            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6331                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6332                        + bp.name + " pkg=" + bp.sourcePackage
6333                        + " info=" + bp.pendingInfo);
6334                if (bp.packageSetting == null && bp.pendingInfo != null) {
6335                    final BasePermission tree = findPermissionTreeLP(bp.name);
6336                    if (tree != null && tree.perm != null) {
6337                        bp.packageSetting = tree.packageSetting;
6338                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6339                                new PermissionInfo(bp.pendingInfo));
6340                        bp.perm.info.packageName = tree.perm.info.packageName;
6341                        bp.perm.info.name = bp.name;
6342                        bp.uid = tree.uid;
6343                    }
6344                }
6345            }
6346            if (bp.packageSetting == null) {
6347                // We may not yet have parsed the package, so just see if
6348                // we still know about its settings.
6349                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6350            }
6351            if (bp.packageSetting == null) {
6352                Slog.w(TAG, "Removing dangling permission: " + bp.name
6353                        + " from package " + bp.sourcePackage);
6354                it.remove();
6355            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6356                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6357                    Slog.i(TAG, "Removing old permission: " + bp.name
6358                            + " from package " + bp.sourcePackage);
6359                    flags |= UPDATE_PERMISSIONS_ALL;
6360                    it.remove();
6361                }
6362            }
6363        }
6364
6365        // Now update the permissions for all packages, in particular
6366        // replace the granted permissions of the system packages.
6367        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6368            for (PackageParser.Package pkg : mPackages.values()) {
6369                if (pkg != pkgInfo) {
6370                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6371                }
6372            }
6373        }
6374
6375        if (pkgInfo != null) {
6376            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6377        }
6378    }
6379
6380    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6381        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6382        if (ps == null) {
6383            return;
6384        }
6385        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6386        HashSet<String> origPermissions = gp.grantedPermissions;
6387        boolean changedPermission = false;
6388
6389        if (replace) {
6390            ps.permissionsFixed = false;
6391            if (gp == ps) {
6392                origPermissions = new HashSet<String>(gp.grantedPermissions);
6393                gp.grantedPermissions.clear();
6394                gp.gids = mGlobalGids;
6395            }
6396        }
6397
6398        if (gp.gids == null) {
6399            gp.gids = mGlobalGids;
6400        }
6401
6402        final int N = pkg.requestedPermissions.size();
6403        for (int i=0; i<N; i++) {
6404            final String name = pkg.requestedPermissions.get(i);
6405            final boolean required = pkg.requestedPermissionsRequired.get(i);
6406            final BasePermission bp = mSettings.mPermissions.get(name);
6407            if (DEBUG_INSTALL) {
6408                if (gp != ps) {
6409                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6410                }
6411            }
6412
6413            if (bp == null || bp.packageSetting == null) {
6414                Slog.w(TAG, "Unknown permission " + name
6415                        + " in package " + pkg.packageName);
6416                continue;
6417            }
6418
6419            final String perm = bp.name;
6420            boolean allowed;
6421            boolean allowedSig = false;
6422            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6423            if (level == PermissionInfo.PROTECTION_NORMAL
6424                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6425                // We grant a normal or dangerous permission if any of the following
6426                // are true:
6427                // 1) The permission is required
6428                // 2) The permission is optional, but was granted in the past
6429                // 3) The permission is optional, but was requested by an
6430                //    app in /system (not /data)
6431                //
6432                // Otherwise, reject the permission.
6433                allowed = (required || origPermissions.contains(perm)
6434                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6435            } else if (bp.packageSetting == null) {
6436                // This permission is invalid; skip it.
6437                allowed = false;
6438            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6439                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6440                if (allowed) {
6441                    allowedSig = true;
6442                }
6443            } else {
6444                allowed = false;
6445            }
6446            if (DEBUG_INSTALL) {
6447                if (gp != ps) {
6448                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6449                }
6450            }
6451            if (allowed) {
6452                if (!isSystemApp(ps) && ps.permissionsFixed) {
6453                    // If this is an existing, non-system package, then
6454                    // we can't add any new permissions to it.
6455                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6456                        // Except...  if this is a permission that was added
6457                        // to the platform (note: need to only do this when
6458                        // updating the platform).
6459                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6460                    }
6461                }
6462                if (allowed) {
6463                    if (!gp.grantedPermissions.contains(perm)) {
6464                        changedPermission = true;
6465                        gp.grantedPermissions.add(perm);
6466                        gp.gids = appendInts(gp.gids, bp.gids);
6467                    } else if (!ps.haveGids) {
6468                        gp.gids = appendInts(gp.gids, bp.gids);
6469                    }
6470                } else {
6471                    Slog.w(TAG, "Not granting permission " + perm
6472                            + " to package " + pkg.packageName
6473                            + " because it was previously installed without");
6474                }
6475            } else {
6476                if (gp.grantedPermissions.remove(perm)) {
6477                    changedPermission = true;
6478                    gp.gids = removeInts(gp.gids, bp.gids);
6479                    Slog.i(TAG, "Un-granting permission " + perm
6480                            + " from package " + pkg.packageName
6481                            + " (protectionLevel=" + bp.protectionLevel
6482                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6483                            + ")");
6484                } else {
6485                    Slog.w(TAG, "Not granting permission " + perm
6486                            + " to package " + pkg.packageName
6487                            + " (protectionLevel=" + bp.protectionLevel
6488                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6489                            + ")");
6490                }
6491            }
6492        }
6493
6494        if ((changedPermission || replace) && !ps.permissionsFixed &&
6495                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6496            // This is the first that we have heard about this package, so the
6497            // permissions we have now selected are fixed until explicitly
6498            // changed.
6499            ps.permissionsFixed = true;
6500        }
6501        ps.haveGids = true;
6502    }
6503
6504    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6505        boolean allowed = false;
6506        final int NP = PackageParser.NEW_PERMISSIONS.length;
6507        for (int ip=0; ip<NP; ip++) {
6508            final PackageParser.NewPermissionInfo npi
6509                    = PackageParser.NEW_PERMISSIONS[ip];
6510            if (npi.name.equals(perm)
6511                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6512                allowed = true;
6513                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6514                        + pkg.packageName);
6515                break;
6516            }
6517        }
6518        return allowed;
6519    }
6520
6521    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6522                                          BasePermission bp, HashSet<String> origPermissions) {
6523        boolean allowed;
6524        allowed = (compareSignatures(
6525                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6526                        == PackageManager.SIGNATURE_MATCH)
6527                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6528                        == PackageManager.SIGNATURE_MATCH);
6529        if (!allowed && (bp.protectionLevel
6530                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6531            if (isSystemApp(pkg)) {
6532                // For updated system applications, a system permission
6533                // is granted only if it had been defined by the original application.
6534                if (isUpdatedSystemApp(pkg)) {
6535                    final PackageSetting sysPs = mSettings
6536                            .getDisabledSystemPkgLPr(pkg.packageName);
6537                    final GrantedPermissions origGp = sysPs.sharedUser != null
6538                            ? sysPs.sharedUser : sysPs;
6539
6540                    if (origGp.grantedPermissions.contains(perm)) {
6541                        // If the original was granted this permission, we take
6542                        // that grant decision as read and propagate it to the
6543                        // update.
6544                        allowed = true;
6545                    } else {
6546                        // The system apk may have been updated with an older
6547                        // version of the one on the data partition, but which
6548                        // granted a new system permission that it didn't have
6549                        // before.  In this case we do want to allow the app to
6550                        // now get the new permission if the ancestral apk is
6551                        // privileged to get it.
6552                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6553                            for (int j=0;
6554                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6555                                if (perm.equals(
6556                                        sysPs.pkg.requestedPermissions.get(j))) {
6557                                    allowed = true;
6558                                    break;
6559                                }
6560                            }
6561                        }
6562                    }
6563                } else {
6564                    allowed = isPrivilegedApp(pkg);
6565                }
6566            }
6567        }
6568        if (!allowed && (bp.protectionLevel
6569                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6570            // For development permissions, a development permission
6571            // is granted only if it was already granted.
6572            allowed = origPermissions.contains(perm);
6573        }
6574        return allowed;
6575    }
6576
6577    final class ActivityIntentResolver
6578            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6579        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6580                boolean defaultOnly, int userId) {
6581            if (!sUserManager.exists(userId)) return null;
6582            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6583            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6584        }
6585
6586        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6587                int userId) {
6588            if (!sUserManager.exists(userId)) return null;
6589            mFlags = flags;
6590            return super.queryIntent(intent, resolvedType,
6591                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6592        }
6593
6594        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6595                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6596            if (!sUserManager.exists(userId)) return null;
6597            if (packageActivities == null) {
6598                return null;
6599            }
6600            mFlags = flags;
6601            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6602            final int N = packageActivities.size();
6603            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6604                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6605
6606            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6607            for (int i = 0; i < N; ++i) {
6608                intentFilters = packageActivities.get(i).intents;
6609                if (intentFilters != null && intentFilters.size() > 0) {
6610                    PackageParser.ActivityIntentInfo[] array =
6611                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6612                    intentFilters.toArray(array);
6613                    listCut.add(array);
6614                }
6615            }
6616            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6617        }
6618
6619        public final void addActivity(PackageParser.Activity a, String type) {
6620            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6621            mActivities.put(a.getComponentName(), a);
6622            if (DEBUG_SHOW_INFO)
6623                Log.v(
6624                TAG, "  " + type + " " +
6625                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6626            if (DEBUG_SHOW_INFO)
6627                Log.v(TAG, "    Class=" + a.info.name);
6628            final int NI = a.intents.size();
6629            for (int j=0; j<NI; j++) {
6630                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6631                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6632                    intent.setPriority(0);
6633                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6634                            + a.className + " with priority > 0, forcing to 0");
6635                }
6636                if (DEBUG_SHOW_INFO) {
6637                    Log.v(TAG, "    IntentFilter:");
6638                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6639                }
6640                if (!intent.debugCheck()) {
6641                    Log.w(TAG, "==> For Activity " + a.info.name);
6642                }
6643                addFilter(intent);
6644            }
6645        }
6646
6647        public final void removeActivity(PackageParser.Activity a, String type) {
6648            mActivities.remove(a.getComponentName());
6649            if (DEBUG_SHOW_INFO) {
6650                Log.v(TAG, "  " + type + " "
6651                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6652                                : a.info.name) + ":");
6653                Log.v(TAG, "    Class=" + a.info.name);
6654            }
6655            final int NI = a.intents.size();
6656            for (int j=0; j<NI; j++) {
6657                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6658                if (DEBUG_SHOW_INFO) {
6659                    Log.v(TAG, "    IntentFilter:");
6660                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6661                }
6662                removeFilter(intent);
6663            }
6664        }
6665
6666        @Override
6667        protected boolean allowFilterResult(
6668                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6669            ActivityInfo filterAi = filter.activity.info;
6670            for (int i=dest.size()-1; i>=0; i--) {
6671                ActivityInfo destAi = dest.get(i).activityInfo;
6672                if (destAi.name == filterAi.name
6673                        && destAi.packageName == filterAi.packageName) {
6674                    return false;
6675                }
6676            }
6677            return true;
6678        }
6679
6680        @Override
6681        protected ActivityIntentInfo[] newArray(int size) {
6682            return new ActivityIntentInfo[size];
6683        }
6684
6685        @Override
6686        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6687            if (!sUserManager.exists(userId)) return true;
6688            PackageParser.Package p = filter.activity.owner;
6689            if (p != null) {
6690                PackageSetting ps = (PackageSetting)p.mExtras;
6691                if (ps != null) {
6692                    // System apps are never considered stopped for purposes of
6693                    // filtering, because there may be no way for the user to
6694                    // actually re-launch them.
6695                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6696                            && ps.getStopped(userId);
6697                }
6698            }
6699            return false;
6700        }
6701
6702        @Override
6703        protected boolean isPackageForFilter(String packageName,
6704                PackageParser.ActivityIntentInfo info) {
6705            return packageName.equals(info.activity.owner.packageName);
6706        }
6707
6708        @Override
6709        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6710                int match, int userId) {
6711            if (!sUserManager.exists(userId)) return null;
6712            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6713                return null;
6714            }
6715            final PackageParser.Activity activity = info.activity;
6716            if (mSafeMode && (activity.info.applicationInfo.flags
6717                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6718                return null;
6719            }
6720            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6721            if (ps == null) {
6722                return null;
6723            }
6724            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6725                    ps.readUserState(userId), userId);
6726            if (ai == null) {
6727                return null;
6728            }
6729            final ResolveInfo res = new ResolveInfo();
6730            res.activityInfo = ai;
6731            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6732                res.filter = info;
6733            }
6734            res.priority = info.getPriority();
6735            res.preferredOrder = activity.owner.mPreferredOrder;
6736            //System.out.println("Result: " + res.activityInfo.className +
6737            //                   " = " + res.priority);
6738            res.match = match;
6739            res.isDefault = info.hasDefault;
6740            res.labelRes = info.labelRes;
6741            res.nonLocalizedLabel = info.nonLocalizedLabel;
6742            res.icon = info.icon;
6743            res.system = isSystemApp(res.activityInfo.applicationInfo);
6744            return res;
6745        }
6746
6747        @Override
6748        protected void sortResults(List<ResolveInfo> results) {
6749            Collections.sort(results, mResolvePrioritySorter);
6750        }
6751
6752        @Override
6753        protected void dumpFilter(PrintWriter out, String prefix,
6754                PackageParser.ActivityIntentInfo filter) {
6755            out.print(prefix); out.print(
6756                    Integer.toHexString(System.identityHashCode(filter.activity)));
6757                    out.print(' ');
6758                    filter.activity.printComponentShortName(out);
6759                    out.print(" filter ");
6760                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6761        }
6762
6763//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6764//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6765//            final List<ResolveInfo> retList = Lists.newArrayList();
6766//            while (i.hasNext()) {
6767//                final ResolveInfo resolveInfo = i.next();
6768//                if (isEnabledLP(resolveInfo.activityInfo)) {
6769//                    retList.add(resolveInfo);
6770//                }
6771//            }
6772//            return retList;
6773//        }
6774
6775        // Keys are String (activity class name), values are Activity.
6776        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6777                = new HashMap<ComponentName, PackageParser.Activity>();
6778        private int mFlags;
6779    }
6780
6781    private final class ServiceIntentResolver
6782            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6783        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6784                boolean defaultOnly, int userId) {
6785            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6786            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6787        }
6788
6789        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6790                int userId) {
6791            if (!sUserManager.exists(userId)) return null;
6792            mFlags = flags;
6793            return super.queryIntent(intent, resolvedType,
6794                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6795        }
6796
6797        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6798                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6799            if (!sUserManager.exists(userId)) return null;
6800            if (packageServices == null) {
6801                return null;
6802            }
6803            mFlags = flags;
6804            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6805            final int N = packageServices.size();
6806            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6807                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6808
6809            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6810            for (int i = 0; i < N; ++i) {
6811                intentFilters = packageServices.get(i).intents;
6812                if (intentFilters != null && intentFilters.size() > 0) {
6813                    PackageParser.ServiceIntentInfo[] array =
6814                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6815                    intentFilters.toArray(array);
6816                    listCut.add(array);
6817                }
6818            }
6819            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6820        }
6821
6822        public final void addService(PackageParser.Service s) {
6823            mServices.put(s.getComponentName(), s);
6824            if (DEBUG_SHOW_INFO) {
6825                Log.v(TAG, "  "
6826                        + (s.info.nonLocalizedLabel != null
6827                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6828                Log.v(TAG, "    Class=" + s.info.name);
6829            }
6830            final int NI = s.intents.size();
6831            int j;
6832            for (j=0; j<NI; j++) {
6833                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6834                if (DEBUG_SHOW_INFO) {
6835                    Log.v(TAG, "    IntentFilter:");
6836                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6837                }
6838                if (!intent.debugCheck()) {
6839                    Log.w(TAG, "==> For Service " + s.info.name);
6840                }
6841                addFilter(intent);
6842            }
6843        }
6844
6845        public final void removeService(PackageParser.Service s) {
6846            mServices.remove(s.getComponentName());
6847            if (DEBUG_SHOW_INFO) {
6848                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
6849                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6850                Log.v(TAG, "    Class=" + s.info.name);
6851            }
6852            final int NI = s.intents.size();
6853            int j;
6854            for (j=0; j<NI; j++) {
6855                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6856                if (DEBUG_SHOW_INFO) {
6857                    Log.v(TAG, "    IntentFilter:");
6858                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6859                }
6860                removeFilter(intent);
6861            }
6862        }
6863
6864        @Override
6865        protected boolean allowFilterResult(
6866                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
6867            ServiceInfo filterSi = filter.service.info;
6868            for (int i=dest.size()-1; i>=0; i--) {
6869                ServiceInfo destAi = dest.get(i).serviceInfo;
6870                if (destAi.name == filterSi.name
6871                        && destAi.packageName == filterSi.packageName) {
6872                    return false;
6873                }
6874            }
6875            return true;
6876        }
6877
6878        @Override
6879        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
6880            return new PackageParser.ServiceIntentInfo[size];
6881        }
6882
6883        @Override
6884        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
6885            if (!sUserManager.exists(userId)) return true;
6886            PackageParser.Package p = filter.service.owner;
6887            if (p != null) {
6888                PackageSetting ps = (PackageSetting)p.mExtras;
6889                if (ps != null) {
6890                    // System apps are never considered stopped for purposes of
6891                    // filtering, because there may be no way for the user to
6892                    // actually re-launch them.
6893                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
6894                            && ps.getStopped(userId);
6895                }
6896            }
6897            return false;
6898        }
6899
6900        @Override
6901        protected boolean isPackageForFilter(String packageName,
6902                PackageParser.ServiceIntentInfo info) {
6903            return packageName.equals(info.service.owner.packageName);
6904        }
6905
6906        @Override
6907        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
6908                int match, int userId) {
6909            if (!sUserManager.exists(userId)) return null;
6910            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
6911            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
6912                return null;
6913            }
6914            final PackageParser.Service service = info.service;
6915            if (mSafeMode && (service.info.applicationInfo.flags
6916                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6917                return null;
6918            }
6919            PackageSetting ps = (PackageSetting) service.owner.mExtras;
6920            if (ps == null) {
6921                return null;
6922            }
6923            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
6924                    ps.readUserState(userId), userId);
6925            if (si == null) {
6926                return null;
6927            }
6928            final ResolveInfo res = new ResolveInfo();
6929            res.serviceInfo = si;
6930            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6931                res.filter = filter;
6932            }
6933            res.priority = info.getPriority();
6934            res.preferredOrder = service.owner.mPreferredOrder;
6935            //System.out.println("Result: " + res.activityInfo.className +
6936            //                   " = " + res.priority);
6937            res.match = match;
6938            res.isDefault = info.hasDefault;
6939            res.labelRes = info.labelRes;
6940            res.nonLocalizedLabel = info.nonLocalizedLabel;
6941            res.icon = info.icon;
6942            res.system = isSystemApp(res.serviceInfo.applicationInfo);
6943            return res;
6944        }
6945
6946        @Override
6947        protected void sortResults(List<ResolveInfo> results) {
6948            Collections.sort(results, mResolvePrioritySorter);
6949        }
6950
6951        @Override
6952        protected void dumpFilter(PrintWriter out, String prefix,
6953                PackageParser.ServiceIntentInfo filter) {
6954            out.print(prefix); out.print(
6955                    Integer.toHexString(System.identityHashCode(filter.service)));
6956                    out.print(' ');
6957                    filter.service.printComponentShortName(out);
6958                    out.print(" filter ");
6959                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6960        }
6961
6962//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6963//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6964//            final List<ResolveInfo> retList = Lists.newArrayList();
6965//            while (i.hasNext()) {
6966//                final ResolveInfo resolveInfo = (ResolveInfo) i;
6967//                if (isEnabledLP(resolveInfo.serviceInfo)) {
6968//                    retList.add(resolveInfo);
6969//                }
6970//            }
6971//            return retList;
6972//        }
6973
6974        // Keys are String (activity class name), values are Activity.
6975        private final HashMap<ComponentName, PackageParser.Service> mServices
6976                = new HashMap<ComponentName, PackageParser.Service>();
6977        private int mFlags;
6978    };
6979
6980    private final class ProviderIntentResolver
6981            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
6982        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6983                boolean defaultOnly, int userId) {
6984            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6985            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6986        }
6987
6988        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6989                int userId) {
6990            if (!sUserManager.exists(userId))
6991                return null;
6992            mFlags = flags;
6993            return super.queryIntent(intent, resolvedType,
6994                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6995        }
6996
6997        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6998                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
6999            if (!sUserManager.exists(userId))
7000                return null;
7001            if (packageProviders == null) {
7002                return null;
7003            }
7004            mFlags = flags;
7005            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7006            final int N = packageProviders.size();
7007            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7008                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7009
7010            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7011            for (int i = 0; i < N; ++i) {
7012                intentFilters = packageProviders.get(i).intents;
7013                if (intentFilters != null && intentFilters.size() > 0) {
7014                    PackageParser.ProviderIntentInfo[] array =
7015                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7016                    intentFilters.toArray(array);
7017                    listCut.add(array);
7018                }
7019            }
7020            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7021        }
7022
7023        public final void addProvider(PackageParser.Provider p) {
7024            if (mProviders.containsKey(p.getComponentName())) {
7025                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7026                return;
7027            }
7028
7029            mProviders.put(p.getComponentName(), p);
7030            if (DEBUG_SHOW_INFO) {
7031                Log.v(TAG, "  "
7032                        + (p.info.nonLocalizedLabel != null
7033                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7034                Log.v(TAG, "    Class=" + p.info.name);
7035            }
7036            final int NI = p.intents.size();
7037            int j;
7038            for (j = 0; j < NI; j++) {
7039                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7040                if (DEBUG_SHOW_INFO) {
7041                    Log.v(TAG, "    IntentFilter:");
7042                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7043                }
7044                if (!intent.debugCheck()) {
7045                    Log.w(TAG, "==> For Provider " + p.info.name);
7046                }
7047                addFilter(intent);
7048            }
7049        }
7050
7051        public final void removeProvider(PackageParser.Provider p) {
7052            mProviders.remove(p.getComponentName());
7053            if (DEBUG_SHOW_INFO) {
7054                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7055                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7056                Log.v(TAG, "    Class=" + p.info.name);
7057            }
7058            final int NI = p.intents.size();
7059            int j;
7060            for (j = 0; j < NI; j++) {
7061                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7062                if (DEBUG_SHOW_INFO) {
7063                    Log.v(TAG, "    IntentFilter:");
7064                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7065                }
7066                removeFilter(intent);
7067            }
7068        }
7069
7070        @Override
7071        protected boolean allowFilterResult(
7072                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7073            ProviderInfo filterPi = filter.provider.info;
7074            for (int i = dest.size() - 1; i >= 0; i--) {
7075                ProviderInfo destPi = dest.get(i).providerInfo;
7076                if (destPi.name == filterPi.name
7077                        && destPi.packageName == filterPi.packageName) {
7078                    return false;
7079                }
7080            }
7081            return true;
7082        }
7083
7084        @Override
7085        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7086            return new PackageParser.ProviderIntentInfo[size];
7087        }
7088
7089        @Override
7090        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7091            if (!sUserManager.exists(userId))
7092                return true;
7093            PackageParser.Package p = filter.provider.owner;
7094            if (p != null) {
7095                PackageSetting ps = (PackageSetting) p.mExtras;
7096                if (ps != null) {
7097                    // System apps are never considered stopped for purposes of
7098                    // filtering, because there may be no way for the user to
7099                    // actually re-launch them.
7100                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7101                            && ps.getStopped(userId);
7102                }
7103            }
7104            return false;
7105        }
7106
7107        @Override
7108        protected boolean isPackageForFilter(String packageName,
7109                PackageParser.ProviderIntentInfo info) {
7110            return packageName.equals(info.provider.owner.packageName);
7111        }
7112
7113        @Override
7114        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7115                int match, int userId) {
7116            if (!sUserManager.exists(userId))
7117                return null;
7118            final PackageParser.ProviderIntentInfo info = filter;
7119            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7120                return null;
7121            }
7122            final PackageParser.Provider provider = info.provider;
7123            if (mSafeMode && (provider.info.applicationInfo.flags
7124                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7125                return null;
7126            }
7127            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7128            if (ps == null) {
7129                return null;
7130            }
7131            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7132                    ps.readUserState(userId), userId);
7133            if (pi == null) {
7134                return null;
7135            }
7136            final ResolveInfo res = new ResolveInfo();
7137            res.providerInfo = pi;
7138            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7139                res.filter = filter;
7140            }
7141            res.priority = info.getPriority();
7142            res.preferredOrder = provider.owner.mPreferredOrder;
7143            res.match = match;
7144            res.isDefault = info.hasDefault;
7145            res.labelRes = info.labelRes;
7146            res.nonLocalizedLabel = info.nonLocalizedLabel;
7147            res.icon = info.icon;
7148            res.system = isSystemApp(res.providerInfo.applicationInfo);
7149            return res;
7150        }
7151
7152        @Override
7153        protected void sortResults(List<ResolveInfo> results) {
7154            Collections.sort(results, mResolvePrioritySorter);
7155        }
7156
7157        @Override
7158        protected void dumpFilter(PrintWriter out, String prefix,
7159                PackageParser.ProviderIntentInfo filter) {
7160            out.print(prefix);
7161            out.print(
7162                    Integer.toHexString(System.identityHashCode(filter.provider)));
7163            out.print(' ');
7164            filter.provider.printComponentShortName(out);
7165            out.print(" filter ");
7166            out.println(Integer.toHexString(System.identityHashCode(filter)));
7167        }
7168
7169        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7170                = new HashMap<ComponentName, PackageParser.Provider>();
7171        private int mFlags;
7172    };
7173
7174    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7175            new Comparator<ResolveInfo>() {
7176        public int compare(ResolveInfo r1, ResolveInfo r2) {
7177            int v1 = r1.priority;
7178            int v2 = r2.priority;
7179            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7180            if (v1 != v2) {
7181                return (v1 > v2) ? -1 : 1;
7182            }
7183            v1 = r1.preferredOrder;
7184            v2 = r2.preferredOrder;
7185            if (v1 != v2) {
7186                return (v1 > v2) ? -1 : 1;
7187            }
7188            if (r1.isDefault != r2.isDefault) {
7189                return r1.isDefault ? -1 : 1;
7190            }
7191            v1 = r1.match;
7192            v2 = r2.match;
7193            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7194            if (v1 != v2) {
7195                return (v1 > v2) ? -1 : 1;
7196            }
7197            if (r1.system != r2.system) {
7198                return r1.system ? -1 : 1;
7199            }
7200            return 0;
7201        }
7202    };
7203
7204    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7205            new Comparator<ProviderInfo>() {
7206        public int compare(ProviderInfo p1, ProviderInfo p2) {
7207            final int v1 = p1.initOrder;
7208            final int v2 = p2.initOrder;
7209            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7210        }
7211    };
7212
7213    static final void sendPackageBroadcast(String action, String pkg,
7214            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7215            int[] userIds) {
7216        IActivityManager am = ActivityManagerNative.getDefault();
7217        if (am != null) {
7218            try {
7219                if (userIds == null) {
7220                    userIds = am.getRunningUserIds();
7221                }
7222                for (int id : userIds) {
7223                    final Intent intent = new Intent(action,
7224                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7225                    if (extras != null) {
7226                        intent.putExtras(extras);
7227                    }
7228                    if (targetPkg != null) {
7229                        intent.setPackage(targetPkg);
7230                    }
7231                    // Modify the UID when posting to other users
7232                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7233                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7234                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7235                        intent.putExtra(Intent.EXTRA_UID, uid);
7236                    }
7237                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7238                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7239                    if (DEBUG_BROADCASTS) {
7240                        RuntimeException here = new RuntimeException("here");
7241                        here.fillInStackTrace();
7242                        Slog.d(TAG, "Sending to user " + id + ": "
7243                                + intent.toShortString(false, true, false, false)
7244                                + " " + intent.getExtras(), here);
7245                    }
7246                    am.broadcastIntent(null, intent, null, finishedReceiver,
7247                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7248                            finishedReceiver != null, false, id);
7249                }
7250            } catch (RemoteException ex) {
7251            }
7252        }
7253    }
7254
7255    /**
7256     * Check if the external storage media is available. This is true if there
7257     * is a mounted external storage medium or if the external storage is
7258     * emulated.
7259     */
7260    private boolean isExternalMediaAvailable() {
7261        return mMediaMounted || Environment.isExternalStorageEmulated();
7262    }
7263
7264    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7265        // writer
7266        synchronized (mPackages) {
7267            if (!isExternalMediaAvailable()) {
7268                // If the external storage is no longer mounted at this point,
7269                // the caller may not have been able to delete all of this
7270                // packages files and can not delete any more.  Bail.
7271                return null;
7272            }
7273            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7274            if (lastPackage != null) {
7275                pkgs.remove(lastPackage);
7276            }
7277            if (pkgs.size() > 0) {
7278                return pkgs.get(0);
7279            }
7280        }
7281        return null;
7282    }
7283
7284    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7285        if (false) {
7286            RuntimeException here = new RuntimeException("here");
7287            here.fillInStackTrace();
7288            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7289                    + " andCode=" + andCode, here);
7290        }
7291        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7292                userId, andCode ? 1 : 0, packageName));
7293    }
7294
7295    void startCleaningPackages() {
7296        // reader
7297        synchronized (mPackages) {
7298            if (!isExternalMediaAvailable()) {
7299                return;
7300            }
7301            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7302                return;
7303            }
7304        }
7305        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7306        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7307        IActivityManager am = ActivityManagerNative.getDefault();
7308        if (am != null) {
7309            try {
7310                am.startService(null, intent, null, UserHandle.USER_OWNER);
7311            } catch (RemoteException e) {
7312            }
7313        }
7314    }
7315
7316    private final class AppDirObserver extends FileObserver {
7317        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7318            super(path, mask);
7319            mRootDir = path;
7320            mIsRom = isrom;
7321            mIsPrivileged = isPrivileged;
7322        }
7323
7324        public void onEvent(int event, String path) {
7325            String removedPackage = null;
7326            int removedAppId = -1;
7327            int[] removedUsers = null;
7328            String addedPackage = null;
7329            int addedAppId = -1;
7330            int[] addedUsers = null;
7331
7332            // TODO post a message to the handler to obtain serial ordering
7333            synchronized (mInstallLock) {
7334                String fullPathStr = null;
7335                File fullPath = null;
7336                if (path != null) {
7337                    fullPath = new File(mRootDir, path);
7338                    fullPathStr = fullPath.getPath();
7339                }
7340
7341                if (DEBUG_APP_DIR_OBSERVER)
7342                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7343
7344                if (!isPackageFilename(path)) {
7345                    if (DEBUG_APP_DIR_OBSERVER)
7346                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7347                    return;
7348                }
7349
7350                // Ignore packages that are being installed or
7351                // have just been installed.
7352                if (ignoreCodePath(fullPathStr)) {
7353                    return;
7354                }
7355                PackageParser.Package p = null;
7356                PackageSetting ps = null;
7357                // reader
7358                synchronized (mPackages) {
7359                    p = mAppDirs.get(fullPathStr);
7360                    if (p != null) {
7361                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7362                        if (ps != null) {
7363                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7364                        } else {
7365                            removedUsers = sUserManager.getUserIds();
7366                        }
7367                    }
7368                    addedUsers = sUserManager.getUserIds();
7369                }
7370                if ((event&REMOVE_EVENTS) != 0) {
7371                    if (ps != null) {
7372                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7373                        removePackageLI(ps, true);
7374                        removedPackage = ps.name;
7375                        removedAppId = ps.appId;
7376                    }
7377                }
7378
7379                if ((event&ADD_EVENTS) != 0) {
7380                    if (p == null) {
7381                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7382                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7383                        if (mIsRom) {
7384                            flags |= PackageParser.PARSE_IS_SYSTEM
7385                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7386                            if (mIsPrivileged) {
7387                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7388                            }
7389                        }
7390                        p = scanPackageLI(fullPath, flags,
7391                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7392                                System.currentTimeMillis(), UserHandle.ALL);
7393                        if (p != null) {
7394                            /*
7395                             * TODO this seems dangerous as the package may have
7396                             * changed since we last acquired the mPackages
7397                             * lock.
7398                             */
7399                            // writer
7400                            synchronized (mPackages) {
7401                                updatePermissionsLPw(p.packageName, p,
7402                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7403                            }
7404                            addedPackage = p.applicationInfo.packageName;
7405                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7406                        }
7407                    }
7408                }
7409
7410                // reader
7411                synchronized (mPackages) {
7412                    mSettings.writeLPr();
7413                }
7414            }
7415
7416            if (removedPackage != null) {
7417                Bundle extras = new Bundle(1);
7418                extras.putInt(Intent.EXTRA_UID, removedAppId);
7419                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7420                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7421                        extras, null, null, removedUsers);
7422            }
7423            if (addedPackage != null) {
7424                Bundle extras = new Bundle(1);
7425                extras.putInt(Intent.EXTRA_UID, addedAppId);
7426                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7427                        extras, null, null, addedUsers);
7428            }
7429        }
7430
7431        private final String mRootDir;
7432        private final boolean mIsRom;
7433        private final boolean mIsPrivileged;
7434    }
7435
7436    /*
7437     * The old-style observer methods all just trampoline to the newer signature with
7438     * expanded install observer API.  The older API continues to work but does not
7439     * supply the additional details of the Observer2 API.
7440     */
7441
7442    /* Called when a downloaded package installation has been confirmed by the user */
7443    public void installPackage(
7444            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
7445        installPackageEtc(packageURI, observer, null, flags, null);
7446    }
7447
7448    /* Called when a downloaded package installation has been confirmed by the user */
7449    public void installPackage(
7450            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
7451            final String installerPackageName) {
7452        installPackageWithVerificationEtc(packageURI, observer, null, flags,
7453                installerPackageName, null, null, null);
7454    }
7455
7456    @Override
7457    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
7458            int flags, String installerPackageName, Uri verificationURI,
7459            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7460        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7461                VerificationParams.NO_UID, manifestDigest);
7462        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7463                installerPackageName, verificationParams, encryptionParams);
7464    }
7465
7466    public void installPackageWithVerificationAndEncryption(Uri packageURI,
7467            IPackageInstallObserver observer, int flags, String installerPackageName,
7468            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7469        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7470                installerPackageName, verificationParams, encryptionParams);
7471    }
7472
7473    /*
7474     * And here are the "live" versions that take both observer arguments
7475     */
7476    public void installPackageEtc(
7477            final Uri packageURI, final IPackageInstallObserver observer,
7478            IPackageInstallObserver2 observer2, final int flags) {
7479        installPackageEtc(packageURI, observer, observer2, flags, null);
7480    }
7481
7482    public void installPackageEtc(
7483            final Uri packageURI, final IPackageInstallObserver observer,
7484            final IPackageInstallObserver2 observer2, final int flags,
7485            final String installerPackageName) {
7486        installPackageWithVerificationEtc(packageURI, observer, observer2, flags,
7487                installerPackageName, null, null, null);
7488    }
7489
7490    @Override
7491    public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer,
7492            IPackageInstallObserver2 observer2,
7493            int flags, String installerPackageName, Uri verificationURI,
7494            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7495        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7496                VerificationParams.NO_UID, manifestDigest);
7497        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags,
7498                installerPackageName, verificationParams, encryptionParams);
7499    }
7500
7501    /*
7502     * All of the installPackage...*() methods redirect to this one for the master implementation
7503     */
7504    public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI,
7505            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7506            int flags, String installerPackageName,
7507            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7508        if (observer == null && observer2 == null) {
7509            throw new IllegalArgumentException("No install observer supplied");
7510        }
7511        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7512                null);
7513
7514        final int uid = Binder.getCallingUid();
7515        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7516            try {
7517                if (observer != null) {
7518                    observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7519                }
7520                if (observer2 != null) {
7521                    observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7522                }
7523            } catch (RemoteException re) {
7524            }
7525            return;
7526        }
7527
7528        UserHandle user;
7529        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7530            user = UserHandle.ALL;
7531        } else {
7532            user = new UserHandle(UserHandle.getUserId(uid));
7533        }
7534
7535        final int filteredFlags;
7536
7537        if (uid == Process.SHELL_UID || uid == 0) {
7538            if (DEBUG_INSTALL) {
7539                Slog.v(TAG, "Install from ADB");
7540            }
7541            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7542        } else {
7543            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7544        }
7545
7546        verificationParams.setInstallerUid(uid);
7547
7548        final Message msg = mHandler.obtainMessage(INIT_COPY);
7549        msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags,
7550                installerPackageName, verificationParams, encryptionParams, user);
7551        mHandler.sendMessage(msg);
7552    }
7553
7554    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7555        Bundle extras = new Bundle(1);
7556        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7557
7558        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7559                packageName, extras, null, null, new int[] {userId});
7560        try {
7561            IActivityManager am = ActivityManagerNative.getDefault();
7562            final boolean isSystem =
7563                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7564            if (isSystem && am.isUserRunning(userId, false)) {
7565                // The just-installed/enabled app is bundled on the system, so presumed
7566                // to be able to run automatically without needing an explicit launch.
7567                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7568                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7569                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7570                        .setPackage(packageName);
7571                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7572                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7573            }
7574        } catch (RemoteException e) {
7575            // shouldn't happen
7576            Slog.w(TAG, "Unable to bootstrap installed package", e);
7577        }
7578    }
7579
7580    @Override
7581    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7582            int userId) {
7583        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7584        PackageSetting pkgSetting;
7585        final int uid = Binder.getCallingUid();
7586        if (UserHandle.getUserId(uid) != userId) {
7587            mContext.enforceCallingOrSelfPermission(
7588                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7589                    "setApplicationBlockedSetting for user " + userId);
7590        }
7591
7592        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7593            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7594            return false;
7595        }
7596
7597        long callingId = Binder.clearCallingIdentity();
7598        try {
7599            boolean sendAdded = false;
7600            boolean sendRemoved = false;
7601            // writer
7602            synchronized (mPackages) {
7603                pkgSetting = mSettings.mPackages.get(packageName);
7604                if (pkgSetting == null) {
7605                    return false;
7606                }
7607                if (pkgSetting.getBlocked(userId) != blocked) {
7608                    pkgSetting.setBlocked(blocked, userId);
7609                    mSettings.writePackageRestrictionsLPr(userId);
7610                    if (blocked) {
7611                        sendRemoved = true;
7612                    } else {
7613                        sendAdded = true;
7614                    }
7615                }
7616            }
7617            if (sendAdded) {
7618                sendPackageAddedForUser(packageName, pkgSetting, userId);
7619                return true;
7620            }
7621            if (sendRemoved) {
7622                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7623                        "blocking pkg");
7624                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7625            }
7626        } finally {
7627            Binder.restoreCallingIdentity(callingId);
7628        }
7629        return false;
7630    }
7631
7632    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7633            int userId) {
7634        final PackageRemovedInfo info = new PackageRemovedInfo();
7635        info.removedPackage = packageName;
7636        info.removedUsers = new int[] {userId};
7637        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7638        info.sendBroadcast(false, false, false);
7639    }
7640
7641    /**
7642     * Returns true if application is not found or there was an error. Otherwise it returns
7643     * the blocked state of the package for the given user.
7644     */
7645    @Override
7646    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7647        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7648        PackageSetting pkgSetting;
7649        final int uid = Binder.getCallingUid();
7650        if (UserHandle.getUserId(uid) != userId) {
7651            mContext.enforceCallingPermission(
7652                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7653                    "getApplicationBlocked for user " + userId);
7654        }
7655        long callingId = Binder.clearCallingIdentity();
7656        try {
7657            // writer
7658            synchronized (mPackages) {
7659                pkgSetting = mSettings.mPackages.get(packageName);
7660                if (pkgSetting == null) {
7661                    return true;
7662                }
7663                return pkgSetting.getBlocked(userId);
7664            }
7665        } finally {
7666            Binder.restoreCallingIdentity(callingId);
7667        }
7668    }
7669
7670    /**
7671     * @hide
7672     */
7673    @Override
7674    public int installExistingPackageAsUser(String packageName, int userId) {
7675        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7676                null);
7677        PackageSetting pkgSetting;
7678        final int uid = Binder.getCallingUid();
7679        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7680        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7681            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7682        }
7683
7684        long callingId = Binder.clearCallingIdentity();
7685        try {
7686            boolean sendAdded = false;
7687            Bundle extras = new Bundle(1);
7688
7689            // writer
7690            synchronized (mPackages) {
7691                pkgSetting = mSettings.mPackages.get(packageName);
7692                if (pkgSetting == null) {
7693                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7694                }
7695                if (!pkgSetting.getInstalled(userId)) {
7696                    pkgSetting.setInstalled(true, userId);
7697                    pkgSetting.setBlocked(false, userId);
7698                    mSettings.writePackageRestrictionsLPr(userId);
7699                    sendAdded = true;
7700                }
7701            }
7702
7703            if (sendAdded) {
7704                sendPackageAddedForUser(packageName, pkgSetting, userId);
7705            }
7706        } finally {
7707            Binder.restoreCallingIdentity(callingId);
7708        }
7709
7710        return PackageManager.INSTALL_SUCCEEDED;
7711    }
7712
7713    private boolean isUserRestricted(int userId, String restrictionKey) {
7714        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7715        if (restrictions.getBoolean(restrictionKey, false)) {
7716            Log.w(TAG, "User is restricted: " + restrictionKey);
7717            return true;
7718        }
7719        return false;
7720    }
7721
7722    @Override
7723    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7724        mContext.enforceCallingOrSelfPermission(
7725                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7726                "Only package verification agents can verify applications");
7727
7728        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7729        final PackageVerificationResponse response = new PackageVerificationResponse(
7730                verificationCode, Binder.getCallingUid());
7731        msg.arg1 = id;
7732        msg.obj = response;
7733        mHandler.sendMessage(msg);
7734    }
7735
7736    @Override
7737    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7738            long millisecondsToDelay) {
7739        mContext.enforceCallingOrSelfPermission(
7740                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7741                "Only package verification agents can extend verification timeouts");
7742
7743        final PackageVerificationState state = mPendingVerification.get(id);
7744        final PackageVerificationResponse response = new PackageVerificationResponse(
7745                verificationCodeAtTimeout, Binder.getCallingUid());
7746
7747        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7748            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7749        }
7750        if (millisecondsToDelay < 0) {
7751            millisecondsToDelay = 0;
7752        }
7753        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7754                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7755            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7756        }
7757
7758        if ((state != null) && !state.timeoutExtended()) {
7759            state.extendTimeout();
7760
7761            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7762            msg.arg1 = id;
7763            msg.obj = response;
7764            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7765        }
7766    }
7767
7768    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7769            int verificationCode, UserHandle user) {
7770        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7771        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7772        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7773        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7774        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7775
7776        mContext.sendBroadcastAsUser(intent, user,
7777                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7778    }
7779
7780    private ComponentName matchComponentForVerifier(String packageName,
7781            List<ResolveInfo> receivers) {
7782        ActivityInfo targetReceiver = null;
7783
7784        final int NR = receivers.size();
7785        for (int i = 0; i < NR; i++) {
7786            final ResolveInfo info = receivers.get(i);
7787            if (info.activityInfo == null) {
7788                continue;
7789            }
7790
7791            if (packageName.equals(info.activityInfo.packageName)) {
7792                targetReceiver = info.activityInfo;
7793                break;
7794            }
7795        }
7796
7797        if (targetReceiver == null) {
7798            return null;
7799        }
7800
7801        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7802    }
7803
7804    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7805            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7806        if (pkgInfo.verifiers.length == 0) {
7807            return null;
7808        }
7809
7810        final int N = pkgInfo.verifiers.length;
7811        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7812        for (int i = 0; i < N; i++) {
7813            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7814
7815            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7816                    receivers);
7817            if (comp == null) {
7818                continue;
7819            }
7820
7821            final int verifierUid = getUidForVerifier(verifierInfo);
7822            if (verifierUid == -1) {
7823                continue;
7824            }
7825
7826            if (DEBUG_VERIFY) {
7827                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
7828                        + " with the correct signature");
7829            }
7830            sufficientVerifiers.add(comp);
7831            verificationState.addSufficientVerifier(verifierUid);
7832        }
7833
7834        return sufficientVerifiers;
7835    }
7836
7837    private int getUidForVerifier(VerifierInfo verifierInfo) {
7838        synchronized (mPackages) {
7839            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
7840            if (pkg == null) {
7841                return -1;
7842            } else if (pkg.mSignatures.length != 1) {
7843                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7844                        + " has more than one signature; ignoring");
7845                return -1;
7846            }
7847
7848            /*
7849             * If the public key of the package's signature does not match
7850             * our expected public key, then this is a different package and
7851             * we should skip.
7852             */
7853
7854            final byte[] expectedPublicKey;
7855            try {
7856                final Signature verifierSig = pkg.mSignatures[0];
7857                final PublicKey publicKey = verifierSig.getPublicKey();
7858                expectedPublicKey = publicKey.getEncoded();
7859            } catch (CertificateException e) {
7860                return -1;
7861            }
7862
7863            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
7864
7865            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
7866                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
7867                        + " does not have the expected public key; ignoring");
7868                return -1;
7869            }
7870
7871            return pkg.applicationInfo.uid;
7872        }
7873    }
7874
7875    public void finishPackageInstall(int token) {
7876        enforceSystemOrRoot("Only the system is allowed to finish installs");
7877
7878        if (DEBUG_INSTALL) {
7879            Slog.v(TAG, "BM finishing package install for " + token);
7880        }
7881
7882        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
7883        mHandler.sendMessage(msg);
7884    }
7885
7886    /**
7887     * Get the verification agent timeout.
7888     *
7889     * @return verification timeout in milliseconds
7890     */
7891    private long getVerificationTimeout() {
7892        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
7893                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
7894                DEFAULT_VERIFICATION_TIMEOUT);
7895    }
7896
7897    /**
7898     * Get the default verification agent response code.
7899     *
7900     * @return default verification response code
7901     */
7902    private int getDefaultVerificationResponse() {
7903        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7904                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
7905                DEFAULT_VERIFICATION_RESPONSE);
7906    }
7907
7908    /**
7909     * Check whether or not package verification has been enabled.
7910     *
7911     * @return true if verification should be performed
7912     */
7913    private boolean isVerificationEnabled(int flags) {
7914        if (!DEFAULT_VERIFY_ENABLE) {
7915            return false;
7916        }
7917
7918        // Check if installing from ADB
7919        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
7920            // Do not run verification in a test harness environment
7921            if (ActivityManager.isRunningInTestHarness()) {
7922                return false;
7923            }
7924            // Check if the developer does not want package verification for ADB installs
7925            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7926                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
7927                return false;
7928            }
7929        }
7930
7931        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7932                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
7933    }
7934
7935    /**
7936     * Get the "allow unknown sources" setting.
7937     *
7938     * @return the current "allow unknown sources" setting
7939     */
7940    private int getUnknownSourcesSettings() {
7941        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
7942                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
7943                -1);
7944    }
7945
7946    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
7947        final int uid = Binder.getCallingUid();
7948        // writer
7949        synchronized (mPackages) {
7950            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
7951            if (targetPackageSetting == null) {
7952                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
7953            }
7954
7955            PackageSetting installerPackageSetting;
7956            if (installerPackageName != null) {
7957                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
7958                if (installerPackageSetting == null) {
7959                    throw new IllegalArgumentException("Unknown installer package: "
7960                            + installerPackageName);
7961                }
7962            } else {
7963                installerPackageSetting = null;
7964            }
7965
7966            Signature[] callerSignature;
7967            Object obj = mSettings.getUserIdLPr(uid);
7968            if (obj != null) {
7969                if (obj instanceof SharedUserSetting) {
7970                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
7971                } else if (obj instanceof PackageSetting) {
7972                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
7973                } else {
7974                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
7975                }
7976            } else {
7977                throw new SecurityException("Unknown calling uid " + uid);
7978            }
7979
7980            // Verify: can't set installerPackageName to a package that is
7981            // not signed with the same cert as the caller.
7982            if (installerPackageSetting != null) {
7983                if (compareSignatures(callerSignature,
7984                        installerPackageSetting.signatures.mSignatures)
7985                        != PackageManager.SIGNATURE_MATCH) {
7986                    throw new SecurityException(
7987                            "Caller does not have same cert as new installer package "
7988                            + installerPackageName);
7989                }
7990            }
7991
7992            // Verify: if target already has an installer package, it must
7993            // be signed with the same cert as the caller.
7994            if (targetPackageSetting.installerPackageName != null) {
7995                PackageSetting setting = mSettings.mPackages.get(
7996                        targetPackageSetting.installerPackageName);
7997                // If the currently set package isn't valid, then it's always
7998                // okay to change it.
7999                if (setting != null) {
8000                    if (compareSignatures(callerSignature,
8001                            setting.signatures.mSignatures)
8002                            != PackageManager.SIGNATURE_MATCH) {
8003                        throw new SecurityException(
8004                                "Caller does not have same cert as old installer package "
8005                                + targetPackageSetting.installerPackageName);
8006                    }
8007                }
8008            }
8009
8010            // Okay!
8011            targetPackageSetting.installerPackageName = installerPackageName;
8012            scheduleWriteSettingsLocked();
8013        }
8014    }
8015
8016    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8017        // Queue up an async operation since the package installation may take a little while.
8018        mHandler.post(new Runnable() {
8019            public void run() {
8020                mHandler.removeCallbacks(this);
8021                 // Result object to be returned
8022                PackageInstalledInfo res = new PackageInstalledInfo();
8023                res.returnCode = currentStatus;
8024                res.uid = -1;
8025                res.pkg = null;
8026                res.removedInfo = new PackageRemovedInfo();
8027                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8028                    args.doPreInstall(res.returnCode);
8029                    synchronized (mInstallLock) {
8030                        installPackageLI(args, true, res);
8031                    }
8032                    args.doPostInstall(res.returnCode, res.uid);
8033                }
8034
8035                // A restore should be performed at this point if (a) the install
8036                // succeeded, (b) the operation is not an update, and (c) the new
8037                // package has a backupAgent defined.
8038                final boolean update = res.removedInfo.removedPackage != null;
8039                boolean doRestore = (!update
8040                        && res.pkg != null
8041                        && res.pkg.applicationInfo.backupAgentName != null);
8042
8043                // Set up the post-install work request bookkeeping.  This will be used
8044                // and cleaned up by the post-install event handling regardless of whether
8045                // there's a restore pass performed.  Token values are >= 1.
8046                int token;
8047                if (mNextInstallToken < 0) mNextInstallToken = 1;
8048                token = mNextInstallToken++;
8049
8050                PostInstallData data = new PostInstallData(args, res);
8051                mRunningInstalls.put(token, data);
8052                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8053
8054                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8055                    // Pass responsibility to the Backup Manager.  It will perform a
8056                    // restore if appropriate, then pass responsibility back to the
8057                    // Package Manager to run the post-install observer callbacks
8058                    // and broadcasts.
8059                    IBackupManager bm = IBackupManager.Stub.asInterface(
8060                            ServiceManager.getService(Context.BACKUP_SERVICE));
8061                    if (bm != null) {
8062                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8063                                + " to BM for possible restore");
8064                        try {
8065                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8066                        } catch (RemoteException e) {
8067                            // can't happen; the backup manager is local
8068                        } catch (Exception e) {
8069                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8070                            doRestore = false;
8071                        }
8072                    } else {
8073                        Slog.e(TAG, "Backup Manager not found!");
8074                        doRestore = false;
8075                    }
8076                }
8077
8078                if (!doRestore) {
8079                    // No restore possible, or the Backup Manager was mysteriously not
8080                    // available -- just fire the post-install work request directly.
8081                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8082                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8083                    mHandler.sendMessage(msg);
8084                }
8085            }
8086        });
8087    }
8088
8089    private abstract class HandlerParams {
8090        private static final int MAX_RETRIES = 4;
8091
8092        /**
8093         * Number of times startCopy() has been attempted and had a non-fatal
8094         * error.
8095         */
8096        private int mRetries = 0;
8097
8098        /** User handle for the user requesting the information or installation. */
8099        private final UserHandle mUser;
8100
8101        HandlerParams(UserHandle user) {
8102            mUser = user;
8103        }
8104
8105        UserHandle getUser() {
8106            return mUser;
8107        }
8108
8109        final boolean startCopy() {
8110            boolean res;
8111            try {
8112                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8113
8114                if (++mRetries > MAX_RETRIES) {
8115                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8116                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8117                    handleServiceError();
8118                    return false;
8119                } else {
8120                    handleStartCopy();
8121                    res = true;
8122                }
8123            } catch (RemoteException e) {
8124                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8125                mHandler.sendEmptyMessage(MCS_RECONNECT);
8126                res = false;
8127            }
8128            handleReturnCode();
8129            return res;
8130        }
8131
8132        final void serviceError() {
8133            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8134            handleServiceError();
8135            handleReturnCode();
8136        }
8137
8138        abstract void handleStartCopy() throws RemoteException;
8139        abstract void handleServiceError();
8140        abstract void handleReturnCode();
8141    }
8142
8143    class MeasureParams extends HandlerParams {
8144        private final PackageStats mStats;
8145        private boolean mSuccess;
8146
8147        private final IPackageStatsObserver mObserver;
8148
8149        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8150            super(new UserHandle(stats.userHandle));
8151            mObserver = observer;
8152            mStats = stats;
8153        }
8154
8155        @Override
8156        public String toString() {
8157            return "MeasureParams{"
8158                + Integer.toHexString(System.identityHashCode(this))
8159                + " " + mStats.packageName + "}";
8160        }
8161
8162        @Override
8163        void handleStartCopy() throws RemoteException {
8164            synchronized (mInstallLock) {
8165                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8166            }
8167
8168            if (mSuccess) {
8169                final boolean mounted;
8170                if (Environment.isExternalStorageEmulated()) {
8171                    mounted = true;
8172                } else {
8173                    final String status = Environment.getExternalStorageState();
8174                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8175                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8176                }
8177
8178                if (mounted) {
8179                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8180
8181                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8182                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8183
8184                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8185                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8186
8187                    // Always subtract cache size, since it's a subdirectory
8188                    mStats.externalDataSize -= mStats.externalCacheSize;
8189
8190                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8191                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8192
8193                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8194                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8195                }
8196            }
8197        }
8198
8199        @Override
8200        void handleReturnCode() {
8201            if (mObserver != null) {
8202                try {
8203                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8204                } catch (RemoteException e) {
8205                    Slog.i(TAG, "Observer no longer exists.");
8206                }
8207            }
8208        }
8209
8210        @Override
8211        void handleServiceError() {
8212            Slog.e(TAG, "Could not measure application " + mStats.packageName
8213                            + " external storage");
8214        }
8215    }
8216
8217    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8218            throws RemoteException {
8219        long result = 0;
8220        for (File path : paths) {
8221            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8222        }
8223        return result;
8224    }
8225
8226    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8227        for (File path : paths) {
8228            try {
8229                mcs.clearDirectory(path.getAbsolutePath());
8230            } catch (RemoteException e) {
8231            }
8232        }
8233    }
8234
8235    class InstallParams extends HandlerParams {
8236        final IPackageInstallObserver observer;
8237        final IPackageInstallObserver2 observer2;
8238        int flags;
8239
8240        private final Uri mPackageURI;
8241        final String installerPackageName;
8242        final VerificationParams verificationParams;
8243        private InstallArgs mArgs;
8244        private int mRet;
8245        private File mTempPackage;
8246        final ContainerEncryptionParams encryptionParams;
8247
8248        InstallParams(Uri packageURI,
8249                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8250                int flags, String installerPackageName, VerificationParams verificationParams,
8251                ContainerEncryptionParams encryptionParams, UserHandle user) {
8252            super(user);
8253            this.mPackageURI = packageURI;
8254            this.flags = flags;
8255            this.observer = observer;
8256            this.observer2 = observer2;
8257            this.installerPackageName = installerPackageName;
8258            this.verificationParams = verificationParams;
8259            this.encryptionParams = encryptionParams;
8260        }
8261
8262        @Override
8263        public String toString() {
8264            return "InstallParams{"
8265                + Integer.toHexString(System.identityHashCode(this))
8266                + " " + mPackageURI + "}";
8267        }
8268
8269        public ManifestDigest getManifestDigest() {
8270            if (verificationParams == null) {
8271                return null;
8272            }
8273            return verificationParams.getManifestDigest();
8274        }
8275
8276        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8277            String packageName = pkgLite.packageName;
8278            int installLocation = pkgLite.installLocation;
8279            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8280            // reader
8281            synchronized (mPackages) {
8282                PackageParser.Package pkg = mPackages.get(packageName);
8283                if (pkg != null) {
8284                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8285                        // Check for downgrading.
8286                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8287                            if (pkgLite.versionCode < pkg.mVersionCode) {
8288                                Slog.w(TAG, "Can't install update of " + packageName
8289                                        + " update version " + pkgLite.versionCode
8290                                        + " is older than installed version "
8291                                        + pkg.mVersionCode);
8292                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8293                            }
8294                        }
8295                        // Check for updated system application.
8296                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8297                            if (onSd) {
8298                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8299                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8300                            }
8301                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8302                        } else {
8303                            if (onSd) {
8304                                // Install flag overrides everything.
8305                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8306                            }
8307                            // If current upgrade specifies particular preference
8308                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8309                                // Application explicitly specified internal.
8310                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8311                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8312                                // App explictly prefers external. Let policy decide
8313                            } else {
8314                                // Prefer previous location
8315                                if (isExternal(pkg)) {
8316                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8317                                }
8318                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8319                            }
8320                        }
8321                    } else {
8322                        // Invalid install. Return error code
8323                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8324                    }
8325                }
8326            }
8327            // All the special cases have been taken care of.
8328            // Return result based on recommended install location.
8329            if (onSd) {
8330                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8331            }
8332            return pkgLite.recommendedInstallLocation;
8333        }
8334
8335        private long getMemoryLowThreshold() {
8336            final DeviceStorageMonitorInternal
8337                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8338            if (dsm == null) {
8339                return 0L;
8340            }
8341            return dsm.getMemoryLowThreshold();
8342        }
8343
8344        /*
8345         * Invoke remote method to get package information and install
8346         * location values. Override install location based on default
8347         * policy if needed and then create install arguments based
8348         * on the install location.
8349         */
8350        public void handleStartCopy() throws RemoteException {
8351            int ret = PackageManager.INSTALL_SUCCEEDED;
8352            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8353            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8354            PackageInfoLite pkgLite = null;
8355
8356            if (onInt && onSd) {
8357                // Check if both bits are set.
8358                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8359                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8360            } else {
8361                final long lowThreshold = getMemoryLowThreshold();
8362                if (lowThreshold == 0L) {
8363                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8364                }
8365
8366                try {
8367                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
8368                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8369
8370                    final File packageFile;
8371                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
8372                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
8373                        if (mTempPackage != null) {
8374                            ParcelFileDescriptor out;
8375                            try {
8376                                out = ParcelFileDescriptor.open(mTempPackage,
8377                                        ParcelFileDescriptor.MODE_READ_WRITE);
8378                            } catch (FileNotFoundException e) {
8379                                out = null;
8380                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
8381                            }
8382
8383                            // Make a temporary file for decryption.
8384                            ret = mContainerService
8385                                    .copyResource(mPackageURI, encryptionParams, out);
8386                            IoUtils.closeQuietly(out);
8387
8388                            packageFile = mTempPackage;
8389
8390                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
8391                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
8392                                            | FileUtils.S_IROTH,
8393                                    -1, -1);
8394                        } else {
8395                            packageFile = null;
8396                        }
8397                    } else {
8398                        packageFile = new File(mPackageURI.getPath());
8399                    }
8400
8401                    if (packageFile != null) {
8402                        // Remote call to find out default install location
8403                        final String packageFilePath = packageFile.getAbsolutePath();
8404                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
8405                                lowThreshold);
8406
8407                        /*
8408                         * If we have too little free space, try to free cache
8409                         * before giving up.
8410                         */
8411                        if (pkgLite.recommendedInstallLocation
8412                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8413                            final long size = mContainerService.calculateInstalledSize(
8414                                    packageFilePath, isForwardLocked());
8415                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8416                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
8417                                        flags, lowThreshold);
8418                            }
8419                            /*
8420                             * The cache free must have deleted the file we
8421                             * downloaded to install.
8422                             *
8423                             * TODO: fix the "freeCache" call to not delete
8424                             *       the file we care about.
8425                             */
8426                            if (pkgLite.recommendedInstallLocation
8427                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8428                                pkgLite.recommendedInstallLocation
8429                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8430                            }
8431                        }
8432                    }
8433                } finally {
8434                    mContext.revokeUriPermission(mPackageURI,
8435                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8436                }
8437            }
8438
8439            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8440                int loc = pkgLite.recommendedInstallLocation;
8441                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8442                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8443                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8444                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8445                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8446                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8447                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8448                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8449                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8450                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8451                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8452                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8453                } else {
8454                    // Override with defaults if needed.
8455                    loc = installLocationPolicy(pkgLite, flags);
8456                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8457                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8458                    } else if (!onSd && !onInt) {
8459                        // Override install location with flags
8460                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8461                            // Set the flag to install on external media.
8462                            flags |= PackageManager.INSTALL_EXTERNAL;
8463                            flags &= ~PackageManager.INSTALL_INTERNAL;
8464                        } else {
8465                            // Make sure the flag for installing on external
8466                            // media is unset
8467                            flags |= PackageManager.INSTALL_INTERNAL;
8468                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8469                        }
8470                    }
8471                }
8472            }
8473
8474            final InstallArgs args = createInstallArgs(this);
8475            mArgs = args;
8476
8477            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8478                 /*
8479                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8480                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8481                 */
8482                int userIdentifier = getUser().getIdentifier();
8483                if (userIdentifier == UserHandle.USER_ALL
8484                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8485                    userIdentifier = UserHandle.USER_OWNER;
8486                }
8487
8488                /*
8489                 * Determine if we have any installed package verifiers. If we
8490                 * do, then we'll defer to them to verify the packages.
8491                 */
8492                final int requiredUid = mRequiredVerifierPackage == null ? -1
8493                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8494                if (requiredUid != -1 && isVerificationEnabled(flags)) {
8495                    final Intent verification = new Intent(
8496                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8497                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
8498                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8499
8500                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8501                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8502                            0 /* TODO: Which userId? */);
8503
8504                    if (DEBUG_VERIFY) {
8505                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8506                                + verification.toString() + " with " + pkgLite.verifiers.length
8507                                + " optional verifiers");
8508                    }
8509
8510                    final int verificationId = mPendingVerificationToken++;
8511
8512                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8513
8514                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8515                            installerPackageName);
8516
8517                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8518
8519                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8520                            pkgLite.packageName);
8521
8522                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8523                            pkgLite.versionCode);
8524
8525                    if (verificationParams != null) {
8526                        if (verificationParams.getVerificationURI() != null) {
8527                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8528                                 verificationParams.getVerificationURI());
8529                        }
8530                        if (verificationParams.getOriginatingURI() != null) {
8531                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8532                                  verificationParams.getOriginatingURI());
8533                        }
8534                        if (verificationParams.getReferrer() != null) {
8535                            verification.putExtra(Intent.EXTRA_REFERRER,
8536                                  verificationParams.getReferrer());
8537                        }
8538                        if (verificationParams.getOriginatingUid() >= 0) {
8539                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8540                                  verificationParams.getOriginatingUid());
8541                        }
8542                        if (verificationParams.getInstallerUid() >= 0) {
8543                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8544                                  verificationParams.getInstallerUid());
8545                        }
8546                    }
8547
8548                    final PackageVerificationState verificationState = new PackageVerificationState(
8549                            requiredUid, args);
8550
8551                    mPendingVerification.append(verificationId, verificationState);
8552
8553                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8554                            receivers, verificationState);
8555
8556                    /*
8557                     * If any sufficient verifiers were listed in the package
8558                     * manifest, attempt to ask them.
8559                     */
8560                    if (sufficientVerifiers != null) {
8561                        final int N = sufficientVerifiers.size();
8562                        if (N == 0) {
8563                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8564                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8565                        } else {
8566                            for (int i = 0; i < N; i++) {
8567                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8568
8569                                final Intent sufficientIntent = new Intent(verification);
8570                                sufficientIntent.setComponent(verifierComponent);
8571
8572                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8573                            }
8574                        }
8575                    }
8576
8577                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8578                            mRequiredVerifierPackage, receivers);
8579                    if (ret == PackageManager.INSTALL_SUCCEEDED
8580                            && mRequiredVerifierPackage != null) {
8581                        /*
8582                         * Send the intent to the required verification agent,
8583                         * but only start the verification timeout after the
8584                         * target BroadcastReceivers have run.
8585                         */
8586                        verification.setComponent(requiredVerifierComponent);
8587                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8588                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8589                                new BroadcastReceiver() {
8590                                    @Override
8591                                    public void onReceive(Context context, Intent intent) {
8592                                        final Message msg = mHandler
8593                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8594                                        msg.arg1 = verificationId;
8595                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8596                                    }
8597                                }, null, 0, null, null);
8598
8599                        /*
8600                         * We don't want the copy to proceed until verification
8601                         * succeeds, so null out this field.
8602                         */
8603                        mArgs = null;
8604                    }
8605                } else {
8606                    /*
8607                     * No package verification is enabled, so immediately start
8608                     * the remote call to initiate copy using temporary file.
8609                     */
8610                    ret = args.copyApk(mContainerService, true);
8611                }
8612            }
8613
8614            mRet = ret;
8615        }
8616
8617        @Override
8618        void handleReturnCode() {
8619            // If mArgs is null, then MCS couldn't be reached. When it
8620            // reconnects, it will try again to install. At that point, this
8621            // will succeed.
8622            if (mArgs != null) {
8623                processPendingInstall(mArgs, mRet);
8624
8625                if (mTempPackage != null) {
8626                    if (!mTempPackage.delete()) {
8627                        Slog.w(TAG, "Couldn't delete temporary file: " +
8628                                mTempPackage.getAbsolutePath());
8629                    }
8630                }
8631            }
8632        }
8633
8634        @Override
8635        void handleServiceError() {
8636            mArgs = createInstallArgs(this);
8637            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8638        }
8639
8640        public boolean isForwardLocked() {
8641            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8642        }
8643
8644        public Uri getPackageUri() {
8645            if (mTempPackage != null) {
8646                return Uri.fromFile(mTempPackage);
8647            } else {
8648                return mPackageURI;
8649            }
8650        }
8651    }
8652
8653    /*
8654     * Utility class used in movePackage api.
8655     * srcArgs and targetArgs are not set for invalid flags and make
8656     * sure to do null checks when invoking methods on them.
8657     * We probably want to return ErrorPrams for both failed installs
8658     * and moves.
8659     */
8660    class MoveParams extends HandlerParams {
8661        final IPackageMoveObserver observer;
8662        final int flags;
8663        final String packageName;
8664        final InstallArgs srcArgs;
8665        final InstallArgs targetArgs;
8666        int uid;
8667        int mRet;
8668
8669        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8670                String packageName, String dataDir, String instructionSet,
8671                int uid, UserHandle user) {
8672            super(user);
8673            this.srcArgs = srcArgs;
8674            this.observer = observer;
8675            this.flags = flags;
8676            this.packageName = packageName;
8677            this.uid = uid;
8678            if (srcArgs != null) {
8679                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8680                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet);
8681            } else {
8682                targetArgs = null;
8683            }
8684        }
8685
8686        @Override
8687        public String toString() {
8688            return "MoveParams{"
8689                + Integer.toHexString(System.identityHashCode(this))
8690                + " " + packageName + "}";
8691        }
8692
8693        public void handleStartCopy() throws RemoteException {
8694            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8695            // Check for storage space on target medium
8696            if (!targetArgs.checkFreeStorage(mContainerService)) {
8697                Log.w(TAG, "Insufficient storage to install");
8698                return;
8699            }
8700
8701            mRet = srcArgs.doPreCopy();
8702            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8703                return;
8704            }
8705
8706            mRet = targetArgs.copyApk(mContainerService, false);
8707            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8708                srcArgs.doPostCopy(uid);
8709                return;
8710            }
8711
8712            mRet = srcArgs.doPostCopy(uid);
8713            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8714                return;
8715            }
8716
8717            mRet = targetArgs.doPreInstall(mRet);
8718            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8719                return;
8720            }
8721
8722            if (DEBUG_SD_INSTALL) {
8723                StringBuilder builder = new StringBuilder();
8724                if (srcArgs != null) {
8725                    builder.append("src: ");
8726                    builder.append(srcArgs.getCodePath());
8727                }
8728                if (targetArgs != null) {
8729                    builder.append(" target : ");
8730                    builder.append(targetArgs.getCodePath());
8731                }
8732                Log.i(TAG, builder.toString());
8733            }
8734        }
8735
8736        @Override
8737        void handleReturnCode() {
8738            targetArgs.doPostInstall(mRet, uid);
8739            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8740            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8741                currentStatus = PackageManager.MOVE_SUCCEEDED;
8742            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8743                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8744            }
8745            processPendingMove(this, currentStatus);
8746        }
8747
8748        @Override
8749        void handleServiceError() {
8750            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8751        }
8752    }
8753
8754    /**
8755     * Used during creation of InstallArgs
8756     *
8757     * @param flags package installation flags
8758     * @return true if should be installed on external storage
8759     */
8760    private static boolean installOnSd(int flags) {
8761        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8762            return false;
8763        }
8764        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8765            return true;
8766        }
8767        return false;
8768    }
8769
8770    /**
8771     * Used during creation of InstallArgs
8772     *
8773     * @param flags package installation flags
8774     * @return true if should be installed as forward locked
8775     */
8776    private static boolean installForwardLocked(int flags) {
8777        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8778    }
8779
8780    private InstallArgs createInstallArgs(InstallParams params) {
8781        if (installOnSd(params.flags) || params.isForwardLocked()) {
8782            return new AsecInstallArgs(params);
8783        } else {
8784            return new FileInstallArgs(params);
8785        }
8786    }
8787
8788    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
8789            String nativeLibraryPath, String instructionSet) {
8790        final boolean isInAsec;
8791        if (installOnSd(flags)) {
8792            /* Apps on SD card are always in ASEC containers. */
8793            isInAsec = true;
8794        } else if (installForwardLocked(flags)
8795                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8796            /*
8797             * Forward-locked apps are only in ASEC containers if they're the
8798             * new style
8799             */
8800            isInAsec = true;
8801        } else {
8802            isInAsec = false;
8803        }
8804
8805        if (isInAsec) {
8806            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8807                    instructionSet, installOnSd(flags), installForwardLocked(flags));
8808        } else {
8809            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8810                    instructionSet);
8811        }
8812    }
8813
8814    // Used by package mover
8815    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir,
8816            String instructionSet) {
8817        if (installOnSd(flags) || installForwardLocked(flags)) {
8818            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
8819                    + AsecInstallArgs.RES_FILE_NAME);
8820            return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags),
8821                    installForwardLocked(flags));
8822        } else {
8823            return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet);
8824        }
8825    }
8826
8827    static abstract class InstallArgs {
8828        final IPackageInstallObserver observer;
8829        final IPackageInstallObserver2 observer2;
8830        // Always refers to PackageManager flags only
8831        final int flags;
8832        final Uri packageURI;
8833        final String installerPackageName;
8834        final ManifestDigest manifestDigest;
8835        final UserHandle user;
8836        final String instructionSet;
8837
8838        InstallArgs(Uri packageURI,
8839                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8840                int flags, String installerPackageName, ManifestDigest manifestDigest,
8841                UserHandle user, String instructionSet) {
8842            this.packageURI = packageURI;
8843            this.flags = flags;
8844            this.observer = observer;
8845            this.observer2 = observer2;
8846            this.installerPackageName = installerPackageName;
8847            this.manifestDigest = manifestDigest;
8848            this.user = user;
8849            this.instructionSet = instructionSet;
8850        }
8851
8852        abstract void createCopyFile();
8853        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8854        abstract int doPreInstall(int status);
8855        abstract boolean doRename(int status, String pkgName, String oldCodePath);
8856
8857        abstract int doPostInstall(int status, int uid);
8858        abstract String getCodePath();
8859        abstract String getResourcePath();
8860        abstract String getNativeLibraryPath();
8861        // Need installer lock especially for dex file removal.
8862        abstract void cleanUpResourcesLI();
8863        abstract boolean doPostDeleteLI(boolean delete);
8864        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
8865
8866        /**
8867         * Called before the source arguments are copied. This is used mostly
8868         * for MoveParams when it needs to read the source file to put it in the
8869         * destination.
8870         */
8871        int doPreCopy() {
8872            return PackageManager.INSTALL_SUCCEEDED;
8873        }
8874
8875        /**
8876         * Called after the source arguments are copied. This is used mostly for
8877         * MoveParams when it needs to read the source file to put it in the
8878         * destination.
8879         *
8880         * @return
8881         */
8882        int doPostCopy(int uid) {
8883            return PackageManager.INSTALL_SUCCEEDED;
8884        }
8885
8886        protected boolean isFwdLocked() {
8887            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8888        }
8889
8890        UserHandle getUser() {
8891            return user;
8892        }
8893    }
8894
8895    class FileInstallArgs extends InstallArgs {
8896        File installDir;
8897        String codeFileName;
8898        String resourceFileName;
8899        String libraryPath;
8900        boolean created = false;
8901
8902        FileInstallArgs(InstallParams params) {
8903            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
8904                    params.installerPackageName, params.getManifestDigest(),
8905                    params.getUser(), null /* instruction set */);
8906        }
8907
8908        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
8909                String instructionSet) {
8910            super(null, null, null, 0, null, null, null, instructionSet);
8911            File codeFile = new File(fullCodePath);
8912            installDir = codeFile.getParentFile();
8913            codeFileName = fullCodePath;
8914            resourceFileName = fullResourcePath;
8915            libraryPath = nativeLibraryPath;
8916        }
8917
8918        FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) {
8919            super(packageURI, null, null, 0, null, null, null, instructionSet);
8920            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8921            String apkName = getNextCodePath(null, pkgName, ".apk");
8922            codeFileName = new File(installDir, apkName + ".apk").getPath();
8923            resourceFileName = getResourcePathFromCodePath();
8924            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
8925        }
8926
8927        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
8928            final long lowThreshold;
8929
8930            final DeviceStorageMonitorInternal
8931                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8932            if (dsm == null) {
8933                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8934                lowThreshold = 0L;
8935            } else {
8936                if (dsm.isMemoryLow()) {
8937                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
8938                    return false;
8939                }
8940
8941                lowThreshold = dsm.getMemoryLowThreshold();
8942            }
8943
8944            try {
8945                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8946                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8947                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
8948            } finally {
8949                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
8950            }
8951        }
8952
8953        String getCodePath() {
8954            return codeFileName;
8955        }
8956
8957        void createCopyFile() {
8958            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
8959            codeFileName = createTempPackageFile(installDir).getPath();
8960            resourceFileName = getResourcePathFromCodePath();
8961            libraryPath = getLibraryPathFromCodePath();
8962            created = true;
8963        }
8964
8965        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
8966            if (temp) {
8967                // Generate temp file name
8968                createCopyFile();
8969            }
8970            // Get a ParcelFileDescriptor to write to the output file
8971            File codeFile = new File(codeFileName);
8972            if (!created) {
8973                try {
8974                    codeFile.createNewFile();
8975                    // Set permissions
8976                    if (!setPermissions()) {
8977                        // Failed setting permissions.
8978                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8979                    }
8980                } catch (IOException e) {
8981                   Slog.w(TAG, "Failed to create file " + codeFile);
8982                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8983                }
8984            }
8985            ParcelFileDescriptor out = null;
8986            try {
8987                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
8988            } catch (FileNotFoundException e) {
8989                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
8990                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8991            }
8992            // Copy the resource now
8993            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8994            try {
8995                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
8996                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
8997                ret = imcs.copyResource(packageURI, null, out);
8998            } finally {
8999                IoUtils.closeQuietly(out);
9000                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9001            }
9002
9003            if (isFwdLocked()) {
9004                final File destResourceFile = new File(getResourcePath());
9005
9006                // Copy the public files
9007                try {
9008                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
9009                } catch (IOException e) {
9010                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
9011                            + " forward-locked app.");
9012                    destResourceFile.delete();
9013                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9014                }
9015            }
9016
9017            final File nativeLibraryFile = new File(getNativeLibraryPath());
9018            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
9019            if (nativeLibraryFile.exists()) {
9020                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9021                nativeLibraryFile.delete();
9022            }
9023            try {
9024                int copyRet = copyNativeLibrariesForInternalApp(codeFile, nativeLibraryFile);
9025                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9026                    return copyRet;
9027                }
9028            } catch (IOException e) {
9029                Slog.e(TAG, "Copying native libraries failed", e);
9030                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9031            }
9032
9033            return ret;
9034        }
9035
9036        int doPreInstall(int status) {
9037            if (status != PackageManager.INSTALL_SUCCEEDED) {
9038                cleanUp();
9039            }
9040            return status;
9041        }
9042
9043        boolean doRename(int status, final String pkgName, String oldCodePath) {
9044            if (status != PackageManager.INSTALL_SUCCEEDED) {
9045                cleanUp();
9046                return false;
9047            } else {
9048                final File oldCodeFile = new File(getCodePath());
9049                final File oldResourceFile = new File(getResourcePath());
9050                final File oldLibraryFile = new File(getNativeLibraryPath());
9051
9052                // Rename APK file based on packageName
9053                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
9054                final File newCodeFile = new File(installDir, apkName + ".apk");
9055                if (!oldCodeFile.renameTo(newCodeFile)) {
9056                    return false;
9057                }
9058                codeFileName = newCodeFile.getPath();
9059
9060                // Rename public resource file if it's forward-locked.
9061                final File newResFile = new File(getResourcePathFromCodePath());
9062                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
9063                    return false;
9064                }
9065                resourceFileName = newResFile.getPath();
9066
9067                // Rename library path
9068                final File newLibraryFile = new File(getLibraryPathFromCodePath());
9069                if (newLibraryFile.exists()) {
9070                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
9071                    newLibraryFile.delete();
9072                }
9073                if (!oldLibraryFile.renameTo(newLibraryFile)) {
9074                    Slog.e(TAG, "Cannot rename native library directory "
9075                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
9076                    return false;
9077                }
9078                libraryPath = newLibraryFile.getPath();
9079
9080                // Attempt to set permissions
9081                if (!setPermissions()) {
9082                    return false;
9083                }
9084
9085                if (!SELinux.restorecon(newCodeFile)) {
9086                    return false;
9087                }
9088
9089                return true;
9090            }
9091        }
9092
9093        int doPostInstall(int status, int uid) {
9094            if (status != PackageManager.INSTALL_SUCCEEDED) {
9095                cleanUp();
9096            }
9097            return status;
9098        }
9099
9100        String getResourcePath() {
9101            return resourceFileName;
9102        }
9103
9104        private String getResourcePathFromCodePath() {
9105            final String codePath = getCodePath();
9106            if (isFwdLocked()) {
9107                final StringBuilder sb = new StringBuilder();
9108
9109                sb.append(mAppInstallDir.getPath());
9110                sb.append('/');
9111                sb.append(getApkName(codePath));
9112                sb.append(".zip");
9113
9114                /*
9115                 * If our APK is a temporary file, mark the resource as a
9116                 * temporary file as well so it can be cleaned up after
9117                 * catastrophic failure.
9118                 */
9119                if (codePath.endsWith(".tmp")) {
9120                    sb.append(".tmp");
9121                }
9122
9123                return sb.toString();
9124            } else {
9125                return codePath;
9126            }
9127        }
9128
9129        private String getLibraryPathFromCodePath() {
9130            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
9131        }
9132
9133        @Override
9134        String getNativeLibraryPath() {
9135            if (libraryPath == null) {
9136                libraryPath = getLibraryPathFromCodePath();
9137            }
9138            return libraryPath;
9139        }
9140
9141        private boolean cleanUp() {
9142            boolean ret = true;
9143            String sourceDir = getCodePath();
9144            String publicSourceDir = getResourcePath();
9145            if (sourceDir != null) {
9146                File sourceFile = new File(sourceDir);
9147                if (!sourceFile.exists()) {
9148                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
9149                    ret = false;
9150                }
9151                // Delete application's code and resources
9152                sourceFile.delete();
9153            }
9154            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
9155                final File publicSourceFile = new File(publicSourceDir);
9156                if (!publicSourceFile.exists()) {
9157                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
9158                }
9159                if (publicSourceFile.exists()) {
9160                    publicSourceFile.delete();
9161                }
9162            }
9163
9164            if (libraryPath != null) {
9165                File nativeLibraryFile = new File(libraryPath);
9166                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9167                if (!nativeLibraryFile.delete()) {
9168                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
9169                }
9170            }
9171
9172            return ret;
9173        }
9174
9175        void cleanUpResourcesLI() {
9176            String sourceDir = getCodePath();
9177            if (cleanUp()) {
9178                if (instructionSet == null) {
9179                    throw new IllegalStateException("instructionSet == null");
9180                }
9181                int retCode = mInstaller.rmdex(sourceDir, instructionSet);
9182                if (retCode < 0) {
9183                    Slog.w(TAG, "Couldn't remove dex file for package: "
9184                            +  " at location "
9185                            + sourceDir + ", retcode=" + retCode);
9186                    // we don't consider this to be a failure of the core package deletion
9187                }
9188            }
9189        }
9190
9191        private boolean setPermissions() {
9192            // TODO Do this in a more elegant way later on. for now just a hack
9193            if (!isFwdLocked()) {
9194                final int filePermissions =
9195                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
9196                    |FileUtils.S_IROTH;
9197                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
9198                if (retCode != 0) {
9199                    Slog.e(TAG, "Couldn't set new package file permissions for " +
9200                            getCodePath()
9201                            + ". The return code was: " + retCode);
9202                    // TODO Define new internal error
9203                    return false;
9204                }
9205                return true;
9206            }
9207            return true;
9208        }
9209
9210        boolean doPostDeleteLI(boolean delete) {
9211            // XXX err, shouldn't we respect the delete flag?
9212            cleanUpResourcesLI();
9213            return true;
9214        }
9215    }
9216
9217    private boolean isAsecExternal(String cid) {
9218        final String asecPath = PackageHelper.getSdFilesystem(cid);
9219        return !asecPath.startsWith(mAsecInternalPath);
9220    }
9221
9222    /**
9223     * Extract the MountService "container ID" from the full code path of an
9224     * .apk.
9225     */
9226    static String cidFromCodePath(String fullCodePath) {
9227        int eidx = fullCodePath.lastIndexOf("/");
9228        String subStr1 = fullCodePath.substring(0, eidx);
9229        int sidx = subStr1.lastIndexOf("/");
9230        return subStr1.substring(sidx+1, eidx);
9231    }
9232
9233    class AsecInstallArgs extends InstallArgs {
9234        static final String RES_FILE_NAME = "pkg.apk";
9235        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9236
9237        String cid;
9238        String packagePath;
9239        String resourcePath;
9240        String libraryPath;
9241
9242        AsecInstallArgs(InstallParams params) {
9243            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9244                    params.installerPackageName, params.getManifestDigest(),
9245                    params.getUser(), null /* instruction set */);
9246        }
9247
9248        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9249                String instructionSet, boolean isExternal, boolean isForwardLocked) {
9250            super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9251                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9252                    null, null, null, instructionSet);
9253            // Extract cid from fullCodePath
9254            int eidx = fullCodePath.lastIndexOf("/");
9255            String subStr1 = fullCodePath.substring(0, eidx);
9256            int sidx = subStr1.lastIndexOf("/");
9257            cid = subStr1.substring(sidx+1, eidx);
9258            setCachePath(subStr1);
9259        }
9260
9261        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
9262            super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
9263                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9264                    null, null, null, instructionSet);
9265            this.cid = cid;
9266            setCachePath(PackageHelper.getSdDir(cid));
9267        }
9268
9269        AsecInstallArgs(Uri packageURI, String cid, String instructionSet,
9270                boolean isExternal, boolean isForwardLocked) {
9271            super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9272                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9273                    null, null, null, instructionSet);
9274            this.cid = cid;
9275        }
9276
9277        void createCopyFile() {
9278            cid = getTempContainerId();
9279        }
9280
9281        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9282            try {
9283                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9284                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9285                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked());
9286            } finally {
9287                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9288            }
9289        }
9290
9291        private final boolean isExternal() {
9292            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9293        }
9294
9295        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9296            if (temp) {
9297                createCopyFile();
9298            } else {
9299                /*
9300                 * Pre-emptively destroy the container since it's destroyed if
9301                 * copying fails due to it existing anyway.
9302                 */
9303                PackageHelper.destroySdDir(cid);
9304            }
9305
9306            final String newCachePath;
9307            try {
9308                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9309                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9310                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
9311                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked());
9312            } finally {
9313                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9314            }
9315
9316            if (newCachePath != null) {
9317                setCachePath(newCachePath);
9318                return PackageManager.INSTALL_SUCCEEDED;
9319            } else {
9320                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9321            }
9322        }
9323
9324        @Override
9325        String getCodePath() {
9326            return packagePath;
9327        }
9328
9329        @Override
9330        String getResourcePath() {
9331            return resourcePath;
9332        }
9333
9334        @Override
9335        String getNativeLibraryPath() {
9336            return libraryPath;
9337        }
9338
9339        int doPreInstall(int status) {
9340            if (status != PackageManager.INSTALL_SUCCEEDED) {
9341                // Destroy container
9342                PackageHelper.destroySdDir(cid);
9343            } else {
9344                boolean mounted = PackageHelper.isContainerMounted(cid);
9345                if (!mounted) {
9346                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9347                            Process.SYSTEM_UID);
9348                    if (newCachePath != null) {
9349                        setCachePath(newCachePath);
9350                    } else {
9351                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9352                    }
9353                }
9354            }
9355            return status;
9356        }
9357
9358        boolean doRename(int status, final String pkgName,
9359                String oldCodePath) {
9360            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
9361            String newCachePath = null;
9362            if (PackageHelper.isContainerMounted(cid)) {
9363                // Unmount the container
9364                if (!PackageHelper.unMountSdDir(cid)) {
9365                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9366                    return false;
9367                }
9368            }
9369            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9370                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9371                        " which might be stale. Will try to clean up.");
9372                // Clean up the stale container and proceed to recreate.
9373                if (!PackageHelper.destroySdDir(newCacheId)) {
9374                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9375                    return false;
9376                }
9377                // Successfully cleaned up stale container. Try to rename again.
9378                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9379                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9380                            + " inspite of cleaning it up.");
9381                    return false;
9382                }
9383            }
9384            if (!PackageHelper.isContainerMounted(newCacheId)) {
9385                Slog.w(TAG, "Mounting container " + newCacheId);
9386                newCachePath = PackageHelper.mountSdDir(newCacheId,
9387                        getEncryptKey(), Process.SYSTEM_UID);
9388            } else {
9389                newCachePath = PackageHelper.getSdDir(newCacheId);
9390            }
9391            if (newCachePath == null) {
9392                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9393                return false;
9394            }
9395            Log.i(TAG, "Succesfully renamed " + cid +
9396                    " to " + newCacheId +
9397                    " at new path: " + newCachePath);
9398            cid = newCacheId;
9399            setCachePath(newCachePath);
9400            return true;
9401        }
9402
9403        private void setCachePath(String newCachePath) {
9404            File cachePath = new File(newCachePath);
9405            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
9406            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9407
9408            if (isFwdLocked()) {
9409                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9410            } else {
9411                resourcePath = packagePath;
9412            }
9413        }
9414
9415        int doPostInstall(int status, int uid) {
9416            if (status != PackageManager.INSTALL_SUCCEEDED) {
9417                cleanUp();
9418            } else {
9419                final int groupOwner;
9420                final String protectedFile;
9421                if (isFwdLocked()) {
9422                    groupOwner = UserHandle.getSharedAppGid(uid);
9423                    protectedFile = RES_FILE_NAME;
9424                } else {
9425                    groupOwner = -1;
9426                    protectedFile = null;
9427                }
9428
9429                if (uid < Process.FIRST_APPLICATION_UID
9430                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9431                    Slog.e(TAG, "Failed to finalize " + cid);
9432                    PackageHelper.destroySdDir(cid);
9433                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9434                }
9435
9436                boolean mounted = PackageHelper.isContainerMounted(cid);
9437                if (!mounted) {
9438                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9439                }
9440            }
9441            return status;
9442        }
9443
9444        private void cleanUp() {
9445            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9446
9447            // Destroy secure container
9448            PackageHelper.destroySdDir(cid);
9449        }
9450
9451        void cleanUpResourcesLI() {
9452            String sourceFile = getCodePath();
9453            // Remove dex file
9454            if (instructionSet == null) {
9455                throw new IllegalStateException("instructionSet == null");
9456            }
9457            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9458            if (retCode < 0) {
9459                Slog.w(TAG, "Couldn't remove dex file for package: "
9460                        + " at location "
9461                        + sourceFile.toString() + ", retcode=" + retCode);
9462                // we don't consider this to be a failure of the core package deletion
9463            }
9464            cleanUp();
9465        }
9466
9467        boolean matchContainer(String app) {
9468            if (cid.startsWith(app)) {
9469                return true;
9470            }
9471            return false;
9472        }
9473
9474        String getPackageName() {
9475            return getAsecPackageName(cid);
9476        }
9477
9478        boolean doPostDeleteLI(boolean delete) {
9479            boolean ret = false;
9480            boolean mounted = PackageHelper.isContainerMounted(cid);
9481            if (mounted) {
9482                // Unmount first
9483                ret = PackageHelper.unMountSdDir(cid);
9484            }
9485            if (ret && delete) {
9486                cleanUpResourcesLI();
9487            }
9488            return ret;
9489        }
9490
9491        @Override
9492        int doPreCopy() {
9493            if (isFwdLocked()) {
9494                if (!PackageHelper.fixSdPermissions(cid,
9495                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9496                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9497                }
9498            }
9499
9500            return PackageManager.INSTALL_SUCCEEDED;
9501        }
9502
9503        @Override
9504        int doPostCopy(int uid) {
9505            if (isFwdLocked()) {
9506                if (uid < Process.FIRST_APPLICATION_UID
9507                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9508                                RES_FILE_NAME)) {
9509                    Slog.e(TAG, "Failed to finalize " + cid);
9510                    PackageHelper.destroySdDir(cid);
9511                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9512                }
9513            }
9514
9515            return PackageManager.INSTALL_SUCCEEDED;
9516        }
9517    };
9518
9519    static String getAsecPackageName(String packageCid) {
9520        int idx = packageCid.lastIndexOf("-");
9521        if (idx == -1) {
9522            return packageCid;
9523        }
9524        return packageCid.substring(0, idx);
9525    }
9526
9527    // Utility method used to create code paths based on package name and available index.
9528    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9529        String idxStr = "";
9530        int idx = 1;
9531        // Fall back to default value of idx=1 if prefix is not
9532        // part of oldCodePath
9533        if (oldCodePath != null) {
9534            String subStr = oldCodePath;
9535            // Drop the suffix right away
9536            if (subStr.endsWith(suffix)) {
9537                subStr = subStr.substring(0, subStr.length() - suffix.length());
9538            }
9539            // If oldCodePath already contains prefix find out the
9540            // ending index to either increment or decrement.
9541            int sidx = subStr.lastIndexOf(prefix);
9542            if (sidx != -1) {
9543                subStr = subStr.substring(sidx + prefix.length());
9544                if (subStr != null) {
9545                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9546                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9547                    }
9548                    try {
9549                        idx = Integer.parseInt(subStr);
9550                        if (idx <= 1) {
9551                            idx++;
9552                        } else {
9553                            idx--;
9554                        }
9555                    } catch(NumberFormatException e) {
9556                    }
9557                }
9558            }
9559        }
9560        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9561        return prefix + idxStr;
9562    }
9563
9564    // Utility method used to ignore ADD/REMOVE events
9565    // by directory observer.
9566    private static boolean ignoreCodePath(String fullPathStr) {
9567        String apkName = getApkName(fullPathStr);
9568        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9569        if (idx != -1 && ((idx+1) < apkName.length())) {
9570            // Make sure the package ends with a numeral
9571            String version = apkName.substring(idx+1);
9572            try {
9573                Integer.parseInt(version);
9574                return true;
9575            } catch (NumberFormatException e) {}
9576        }
9577        return false;
9578    }
9579
9580    // Utility method that returns the relative package path with respect
9581    // to the installation directory. Like say for /data/data/com.test-1.apk
9582    // string com.test-1 is returned.
9583    static String getApkName(String codePath) {
9584        if (codePath == null) {
9585            return null;
9586        }
9587        int sidx = codePath.lastIndexOf("/");
9588        int eidx = codePath.lastIndexOf(".");
9589        if (eidx == -1) {
9590            eidx = codePath.length();
9591        } else if (eidx == 0) {
9592            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
9593            return null;
9594        }
9595        return codePath.substring(sidx+1, eidx);
9596    }
9597
9598    class PackageInstalledInfo {
9599        String name;
9600        int uid;
9601        // The set of users that originally had this package installed.
9602        int[] origUsers;
9603        // The set of users that now have this package installed.
9604        int[] newUsers;
9605        PackageParser.Package pkg;
9606        int returnCode;
9607        PackageRemovedInfo removedInfo;
9608
9609        // In some error cases we want to convey more info back to the observer
9610        String origPackage;
9611        String origPermission;
9612    }
9613
9614    /*
9615     * Install a non-existing package.
9616     */
9617    private void installNewPackageLI(PackageParser.Package pkg,
9618            int parseFlags, int scanMode, UserHandle user,
9619            String installerPackageName, PackageInstalledInfo res) {
9620        // Remember this for later, in case we need to rollback this install
9621        String pkgName = pkg.packageName;
9622
9623        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9624        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9625        synchronized(mPackages) {
9626            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9627                // A package with the same name is already installed, though
9628                // it has been renamed to an older name.  The package we
9629                // are trying to install should be installed as an update to
9630                // the existing one, but that has not been requested, so bail.
9631                Slog.w(TAG, "Attempt to re-install " + pkgName
9632                        + " without first uninstalling package running as "
9633                        + mSettings.mRenamedPackages.get(pkgName));
9634                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9635                return;
9636            }
9637            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.mPath)) {
9638                // Don't allow installation over an existing package with the same name.
9639                Slog.w(TAG, "Attempt to re-install " + pkgName
9640                        + " without first uninstalling.");
9641                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9642                return;
9643            }
9644        }
9645        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9646        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9647                System.currentTimeMillis(), user);
9648        if (newPackage == null) {
9649            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9650            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9651                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9652            }
9653        } else {
9654            updateSettingsLI(newPackage,
9655                    installerPackageName,
9656                    null, null,
9657                    res);
9658            // delete the partially installed application. the data directory will have to be
9659            // restored if it was already existing
9660            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9661                // remove package from internal structures.  Note that we want deletePackageX to
9662                // delete the package data and cache directories that it created in
9663                // scanPackageLocked, unless those directories existed before we even tried to
9664                // install.
9665                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9666                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9667                                res.removedInfo, true);
9668            }
9669        }
9670    }
9671
9672    private void replacePackageLI(PackageParser.Package pkg,
9673            int parseFlags, int scanMode, UserHandle user,
9674            String installerPackageName, PackageInstalledInfo res) {
9675
9676        PackageParser.Package oldPackage;
9677        String pkgName = pkg.packageName;
9678        int[] allUsers;
9679        boolean[] perUserInstalled;
9680
9681        // First find the old package info and check signatures
9682        synchronized(mPackages) {
9683            oldPackage = mPackages.get(pkgName);
9684            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9685            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9686                    != PackageManager.SIGNATURE_MATCH) {
9687                Slog.w(TAG, "New package has a different signature: " + pkgName);
9688                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9689                return;
9690            }
9691
9692            // In case of rollback, remember per-user/profile install state
9693            PackageSetting ps = mSettings.mPackages.get(pkgName);
9694            allUsers = sUserManager.getUserIds();
9695            perUserInstalled = new boolean[allUsers.length];
9696            for (int i = 0; i < allUsers.length; i++) {
9697                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9698            }
9699        }
9700        boolean sysPkg = (isSystemApp(oldPackage));
9701        if (sysPkg) {
9702            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9703                    user, allUsers, perUserInstalled, installerPackageName, res);
9704        } else {
9705            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9706                    user, allUsers, perUserInstalled, installerPackageName, res);
9707        }
9708    }
9709
9710    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9711            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9712            int[] allUsers, boolean[] perUserInstalled,
9713            String installerPackageName, PackageInstalledInfo res) {
9714        PackageParser.Package newPackage = null;
9715        String pkgName = deletedPackage.packageName;
9716        boolean deletedPkg = true;
9717        boolean updatedSettings = false;
9718
9719        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9720                + deletedPackage);
9721        long origUpdateTime;
9722        if (pkg.mExtras != null) {
9723            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9724        } else {
9725            origUpdateTime = 0;
9726        }
9727
9728        // First delete the existing package while retaining the data directory
9729        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9730                res.removedInfo, true)) {
9731            // If the existing package wasn't successfully deleted
9732            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9733            deletedPkg = false;
9734        } else {
9735            // Successfully deleted the old package. Now proceed with re-installation
9736            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9737            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9738                    System.currentTimeMillis(), user);
9739            if (newPackage == null) {
9740                Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9741                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9742                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9743                }
9744            } else {
9745                updateSettingsLI(newPackage,
9746                        installerPackageName,
9747                        allUsers, perUserInstalled,
9748                        res);
9749                updatedSettings = true;
9750            }
9751        }
9752
9753        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9754            // remove package from internal structures.  Note that we want deletePackageX to
9755            // delete the package data and cache directories that it created in
9756            // scanPackageLocked, unless those directories existed before we even tried to
9757            // install.
9758            if(updatedSettings) {
9759                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9760                deletePackageLI(
9761                        pkgName, null, true, allUsers, perUserInstalled,
9762                        PackageManager.DELETE_KEEP_DATA,
9763                                res.removedInfo, true);
9764            }
9765            // Since we failed to install the new package we need to restore the old
9766            // package that we deleted.
9767            if(deletedPkg) {
9768                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9769                File restoreFile = new File(deletedPackage.mPath);
9770                // Parse old package
9771                boolean oldOnSd = isExternal(deletedPackage);
9772                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9773                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9774                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9775                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9776                        | SCAN_UPDATE_TIME;
9777                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9778                        origUpdateTime, null) == null) {
9779                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9780                    return;
9781                }
9782                // Restore of old package succeeded. Update permissions.
9783                // writer
9784                synchronized (mPackages) {
9785                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9786                            UPDATE_PERMISSIONS_ALL);
9787                    // can downgrade to reader
9788                    mSettings.writeLPr();
9789                }
9790                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9791            }
9792        }
9793    }
9794
9795    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9796            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9797            int[] allUsers, boolean[] perUserInstalled,
9798            String installerPackageName, PackageInstalledInfo res) {
9799        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9800                + ", old=" + deletedPackage);
9801        PackageParser.Package newPackage = null;
9802        boolean updatedSettings = false;
9803        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
9804                PackageParser.PARSE_IS_SYSTEM;
9805        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9806            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9807        }
9808        String packageName = deletedPackage.packageName;
9809        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9810        if (packageName == null) {
9811            Slog.w(TAG, "Attempt to delete null packageName.");
9812            return;
9813        }
9814        PackageParser.Package oldPkg;
9815        PackageSetting oldPkgSetting;
9816        // reader
9817        synchronized (mPackages) {
9818            oldPkg = mPackages.get(packageName);
9819            oldPkgSetting = mSettings.mPackages.get(packageName);
9820            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9821                    (oldPkgSetting == null)) {
9822                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
9823                return;
9824            }
9825        }
9826
9827        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
9828
9829        res.removedInfo.uid = oldPkg.applicationInfo.uid;
9830        res.removedInfo.removedPackage = packageName;
9831        // Remove existing system package
9832        removePackageLI(oldPkgSetting, true);
9833        // writer
9834        synchronized (mPackages) {
9835            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
9836                // We didn't need to disable the .apk as a current system package,
9837                // which means we are replacing another update that is already
9838                // installed.  We need to make sure to delete the older one's .apk.
9839                res.removedInfo.args = createInstallArgs(0,
9840                        deletedPackage.applicationInfo.sourceDir,
9841                        deletedPackage.applicationInfo.publicSourceDir,
9842                        deletedPackage.applicationInfo.nativeLibraryDir,
9843                        getAppInstructionSet(deletedPackage.applicationInfo));
9844            } else {
9845                res.removedInfo.args = null;
9846            }
9847        }
9848
9849        // Successfully disabled the old package. Now proceed with re-installation
9850        res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9851        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
9852        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user);
9853        if (newPackage == null) {
9854            Slog.w(TAG, "Package couldn't be installed in " + pkg.mPath);
9855            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9856                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9857            }
9858        } else {
9859            if (newPackage.mExtras != null) {
9860                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
9861                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
9862                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
9863
9864                // is the update attempting to change shared user? that isn't going to work...
9865                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
9866                    Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser
9867                            + " to " + newPkgSetting.sharedUser);
9868                    res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
9869                    updatedSettings = true;
9870                }
9871            }
9872
9873            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
9874                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9875                updatedSettings = true;
9876            }
9877        }
9878
9879        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9880            // Re installation failed. Restore old information
9881            // Remove new pkg information
9882            if (newPackage != null) {
9883                removeInstalledPackageLI(newPackage, true);
9884            }
9885            // Add back the old system package
9886            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user);
9887            // Restore the old system information in Settings
9888            synchronized(mPackages) {
9889                if (updatedSettings) {
9890                    mSettings.enableSystemPackageLPw(packageName);
9891                    mSettings.setInstallerPackageName(packageName,
9892                            oldPkgSetting.installerPackageName);
9893                }
9894                mSettings.writeLPr();
9895            }
9896        }
9897    }
9898
9899    // Utility method used to move dex files during install.
9900    private int moveDexFilesLI(PackageParser.Package newPackage) {
9901        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
9902            final String instructionSet = getAppInstructionSet(newPackage.applicationInfo);
9903            int retCode = mInstaller.movedex(newPackage.mScanPath, newPackage.mPath,
9904                                             instructionSet);
9905            if (retCode != 0) {
9906                /*
9907                 * Programs may be lazily run through dexopt, so the
9908                 * source may not exist. However, something seems to
9909                 * have gone wrong, so note that dexopt needs to be
9910                 * run again and remove the source file. In addition,
9911                 * remove the target to make sure there isn't a stale
9912                 * file from a previous version of the package.
9913                 */
9914                newPackage.mDexOptNeeded = true;
9915                mInstaller.rmdex(newPackage.mScanPath, instructionSet);
9916                mInstaller.rmdex(newPackage.mPath, instructionSet);
9917            }
9918        }
9919        return PackageManager.INSTALL_SUCCEEDED;
9920    }
9921
9922    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
9923            int[] allUsers, boolean[] perUserInstalled,
9924            PackageInstalledInfo res) {
9925        String pkgName = newPackage.packageName;
9926        synchronized (mPackages) {
9927            //write settings. the installStatus will be incomplete at this stage.
9928            //note that the new package setting would have already been
9929            //added to mPackages. It hasn't been persisted yet.
9930            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
9931            mSettings.writeLPr();
9932        }
9933
9934        if ((res.returnCode = moveDexFilesLI(newPackage))
9935                != PackageManager.INSTALL_SUCCEEDED) {
9936            // Discontinue if moving dex files failed.
9937            return;
9938        }
9939
9940        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.mPath);
9941
9942        synchronized (mPackages) {
9943            updatePermissionsLPw(newPackage.packageName, newPackage,
9944                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
9945                            ? UPDATE_PERMISSIONS_ALL : 0));
9946            // For system-bundled packages, we assume that installing an upgraded version
9947            // of the package implies that the user actually wants to run that new code,
9948            // so we enable the package.
9949            if (isSystemApp(newPackage)) {
9950                // NB: implicit assumption that system package upgrades apply to all users
9951                if (DEBUG_INSTALL) {
9952                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
9953                }
9954                PackageSetting ps = mSettings.mPackages.get(pkgName);
9955                if (ps != null) {
9956                    if (res.origUsers != null) {
9957                        for (int userHandle : res.origUsers) {
9958                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
9959                                    userHandle, installerPackageName);
9960                        }
9961                    }
9962                    // Also convey the prior install/uninstall state
9963                    if (allUsers != null && perUserInstalled != null) {
9964                        for (int i = 0; i < allUsers.length; i++) {
9965                            if (DEBUG_INSTALL) {
9966                                Slog.d(TAG, "    user " + allUsers[i]
9967                                        + " => " + perUserInstalled[i]);
9968                            }
9969                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
9970                        }
9971                        // these install state changes will be persisted in the
9972                        // upcoming call to mSettings.writeLPr().
9973                    }
9974                }
9975            }
9976            res.name = pkgName;
9977            res.uid = newPackage.applicationInfo.uid;
9978            res.pkg = newPackage;
9979            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
9980            mSettings.setInstallerPackageName(pkgName, installerPackageName);
9981            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9982            //to update install status
9983            mSettings.writeLPr();
9984        }
9985    }
9986
9987    private void installPackageLI(InstallArgs args,
9988            boolean newInstall, PackageInstalledInfo res) {
9989        int pFlags = args.flags;
9990        String installerPackageName = args.installerPackageName;
9991        File tmpPackageFile = new File(args.getCodePath());
9992        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
9993        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
9994        boolean replace = false;
9995        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
9996                | (newInstall ? SCAN_NEW_INSTALL : 0);
9997        // Result object to be returned
9998        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
9999
10000        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10001        // Retrieve PackageSettings and parse package
10002        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10003                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10004                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10005        PackageParser pp = new PackageParser(tmpPackageFile.getPath());
10006        pp.setSeparateProcesses(mSeparateProcesses);
10007        final PackageParser.Package pkg = pp.parsePackage(tmpPackageFile,
10008                null, mMetrics, parseFlags);
10009        if (pkg == null) {
10010            res.returnCode = pp.getParseError();
10011            return;
10012        }
10013        String pkgName = res.name = pkg.packageName;
10014        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10015            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10016                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
10017                return;
10018            }
10019        }
10020        if (!pp.collectCertificates(pkg, parseFlags)) {
10021            res.returnCode = pp.getParseError();
10022            return;
10023        }
10024
10025        /* If the installer passed in a manifest digest, compare it now. */
10026        if (args.manifestDigest != null) {
10027            if (DEBUG_INSTALL) {
10028                final String parsedManifest = pkg.manifestDigest == null ? "null"
10029                        : pkg.manifestDigest.toString();
10030                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10031                        + parsedManifest);
10032            }
10033
10034            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10035                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
10036                return;
10037            }
10038        } else if (DEBUG_INSTALL) {
10039            final String parsedManifest = pkg.manifestDigest == null
10040                    ? "null" : pkg.manifestDigest.toString();
10041            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10042        }
10043
10044        // Get rid of all references to package scan path via parser.
10045        pp = null;
10046        String oldCodePath = null;
10047        boolean systemApp = false;
10048        synchronized (mPackages) {
10049            // Check whether the newly-scanned package wants to define an already-defined perm
10050            int N = pkg.permissions.size();
10051            for (int i = 0; i < N; i++) {
10052                PackageParser.Permission perm = pkg.permissions.get(i);
10053                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10054                if (bp != null) {
10055                    // If the defining package is signed with our cert, it's okay.  This
10056                    // also includes the "updating the same package" case, of course.
10057                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10058                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10059                        Slog.w(TAG, "Package " + pkg.packageName
10060                                + " attempting to redeclare permission " + perm.info.name
10061                                + " already owned by " + bp.sourcePackage);
10062                        res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
10063                        res.origPermission = perm.info.name;
10064                        res.origPackage = bp.sourcePackage;
10065                        return;
10066                    }
10067                }
10068            }
10069
10070            // Check if installing already existing package
10071            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10072                String oldName = mSettings.mRenamedPackages.get(pkgName);
10073                if (pkg.mOriginalPackages != null
10074                        && pkg.mOriginalPackages.contains(oldName)
10075                        && mPackages.containsKey(oldName)) {
10076                    // This package is derived from an original package,
10077                    // and this device has been updating from that original
10078                    // name.  We must continue using the original name, so
10079                    // rename the new package here.
10080                    pkg.setPackageName(oldName);
10081                    pkgName = pkg.packageName;
10082                    replace = true;
10083                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10084                            + oldName + " pkgName=" + pkgName);
10085                } else if (mPackages.containsKey(pkgName)) {
10086                    // This package, under its official name, already exists
10087                    // on the device; we should replace it.
10088                    replace = true;
10089                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10090                }
10091            }
10092            PackageSetting ps = mSettings.mPackages.get(pkgName);
10093            if (ps != null) {
10094                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10095                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10096                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10097                    systemApp = (ps.pkg.applicationInfo.flags &
10098                            ApplicationInfo.FLAG_SYSTEM) != 0;
10099                }
10100                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10101            }
10102        }
10103
10104        if (systemApp && onSd) {
10105            // Disable updates to system apps on sdcard
10106            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
10107            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10108            return;
10109        }
10110
10111        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
10112            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10113            return;
10114        }
10115        // Set application objects path explicitly after the rename
10116        setApplicationInfoPaths(pkg, args.getCodePath(), args.getResourcePath());
10117        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
10118        if (replace) {
10119            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10120                    installerPackageName, res);
10121        } else {
10122            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10123                    installerPackageName, res);
10124        }
10125        synchronized (mPackages) {
10126            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10127            if (ps != null) {
10128                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10129            }
10130        }
10131    }
10132
10133    private static boolean isForwardLocked(PackageParser.Package pkg) {
10134        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10135    }
10136
10137
10138    private boolean isForwardLocked(PackageSetting ps) {
10139        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10140    }
10141
10142    private static boolean isExternal(PackageParser.Package pkg) {
10143        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10144    }
10145
10146    private static boolean isExternal(PackageSetting ps) {
10147        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10148    }
10149
10150    private static boolean isSystemApp(PackageParser.Package pkg) {
10151        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10152    }
10153
10154    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10155        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10156    }
10157
10158    private static boolean isSystemApp(ApplicationInfo info) {
10159        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10160    }
10161
10162    private static boolean isSystemApp(PackageSetting ps) {
10163        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10164    }
10165
10166    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10167        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10168    }
10169
10170    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10171        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10172    }
10173
10174    private int packageFlagsToInstallFlags(PackageSetting ps) {
10175        int installFlags = 0;
10176        if (isExternal(ps)) {
10177            installFlags |= PackageManager.INSTALL_EXTERNAL;
10178        }
10179        if (isForwardLocked(ps)) {
10180            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10181        }
10182        return installFlags;
10183    }
10184
10185    private void deleteTempPackageFiles() {
10186        final FilenameFilter filter = new FilenameFilter() {
10187            public boolean accept(File dir, String name) {
10188                return name.startsWith("vmdl") && name.endsWith(".tmp");
10189            }
10190        };
10191        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
10192        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
10193    }
10194
10195    private static final void deleteTempPackageFilesInDirectory(File directory,
10196            FilenameFilter filter) {
10197        final String[] tmpFilesList = directory.list(filter);
10198        if (tmpFilesList == null) {
10199            return;
10200        }
10201        for (int i = 0; i < tmpFilesList.length; i++) {
10202            final File tmpFile = new File(directory, tmpFilesList[i]);
10203            tmpFile.delete();
10204        }
10205    }
10206
10207    private File createTempPackageFile(File installDir) {
10208        File tmpPackageFile;
10209        try {
10210            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
10211        } catch (IOException e) {
10212            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
10213            return null;
10214        }
10215        try {
10216            FileUtils.setPermissions(
10217                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
10218                    -1, -1);
10219            if (!SELinux.restorecon(tmpPackageFile)) {
10220                return null;
10221            }
10222        } catch (IOException e) {
10223            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
10224            return null;
10225        }
10226        return tmpPackageFile;
10227    }
10228
10229    @Override
10230    public void deletePackageAsUser(final String packageName,
10231                                    final IPackageDeleteObserver observer,
10232                                    final int userId, final int flags) {
10233        mContext.enforceCallingOrSelfPermission(
10234                android.Manifest.permission.DELETE_PACKAGES, null);
10235        final int uid = Binder.getCallingUid();
10236        if (UserHandle.getUserId(uid) != userId) {
10237            mContext.enforceCallingPermission(
10238                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10239                    "deletePackage for user " + userId);
10240        }
10241        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10242            try {
10243                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10244            } catch (RemoteException re) {
10245            }
10246            return;
10247        }
10248
10249        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10250        // Queue up an async operation since the package deletion may take a little while.
10251        mHandler.post(new Runnable() {
10252            public void run() {
10253                mHandler.removeCallbacks(this);
10254                final int returnCode = deletePackageX(packageName, userId, flags);
10255                if (observer != null) {
10256                    try {
10257                        observer.packageDeleted(packageName, returnCode);
10258                    } catch (RemoteException e) {
10259                        Log.i(TAG, "Observer no longer exists.");
10260                    } //end catch
10261                } //end if
10262            } //end run
10263        });
10264    }
10265
10266    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10267        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10268                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10269        try {
10270            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10271                    || dpm.isDeviceOwner(packageName))) {
10272                return true;
10273            }
10274        } catch (RemoteException e) {
10275        }
10276        return false;
10277    }
10278
10279    /**
10280     *  This method is an internal method that could be get invoked either
10281     *  to delete an installed package or to clean up a failed installation.
10282     *  After deleting an installed package, a broadcast is sent to notify any
10283     *  listeners that the package has been installed. For cleaning up a failed
10284     *  installation, the broadcast is not necessary since the package's
10285     *  installation wouldn't have sent the initial broadcast either
10286     *  The key steps in deleting a package are
10287     *  deleting the package information in internal structures like mPackages,
10288     *  deleting the packages base directories through installd
10289     *  updating mSettings to reflect current status
10290     *  persisting settings for later use
10291     *  sending a broadcast if necessary
10292     */
10293    private int deletePackageX(String packageName, int userId, int flags) {
10294        final PackageRemovedInfo info = new PackageRemovedInfo();
10295        final boolean res;
10296
10297        if (isPackageDeviceAdmin(packageName, userId)) {
10298            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10299            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10300        }
10301
10302        boolean removedForAllUsers = false;
10303        boolean systemUpdate = false;
10304
10305        // for the uninstall-updates case and restricted profiles, remember the per-
10306        // userhandle installed state
10307        int[] allUsers;
10308        boolean[] perUserInstalled;
10309        synchronized (mPackages) {
10310            PackageSetting ps = mSettings.mPackages.get(packageName);
10311            allUsers = sUserManager.getUserIds();
10312            perUserInstalled = new boolean[allUsers.length];
10313            for (int i = 0; i < allUsers.length; i++) {
10314                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10315            }
10316        }
10317
10318        synchronized (mInstallLock) {
10319            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10320            res = deletePackageLI(packageName,
10321                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10322                            ? UserHandle.ALL : new UserHandle(userId),
10323                    true, allUsers, perUserInstalled,
10324                    flags | REMOVE_CHATTY, info, true);
10325            systemUpdate = info.isRemovedPackageSystemUpdate;
10326            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10327                removedForAllUsers = true;
10328            }
10329            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10330                    + " removedForAllUsers=" + removedForAllUsers);
10331        }
10332
10333        if (res) {
10334            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10335
10336            // If the removed package was a system update, the old system package
10337            // was re-enabled; we need to broadcast this information
10338            if (systemUpdate) {
10339                Bundle extras = new Bundle(1);
10340                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10341                        ? info.removedAppId : info.uid);
10342                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10343
10344                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10345                        extras, null, null, null);
10346                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10347                        extras, null, null, null);
10348                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10349                        null, packageName, null, null);
10350            }
10351        }
10352        // Force a gc here.
10353        Runtime.getRuntime().gc();
10354        // Delete the resources here after sending the broadcast to let
10355        // other processes clean up before deleting resources.
10356        if (info.args != null) {
10357            synchronized (mInstallLock) {
10358                info.args.doPostDeleteLI(true);
10359            }
10360        }
10361
10362        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10363    }
10364
10365    static class PackageRemovedInfo {
10366        String removedPackage;
10367        int uid = -1;
10368        int removedAppId = -1;
10369        int[] removedUsers = null;
10370        boolean isRemovedPackageSystemUpdate = false;
10371        // Clean up resources deleted packages.
10372        InstallArgs args = null;
10373
10374        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10375            Bundle extras = new Bundle(1);
10376            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10377            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10378            if (replacing) {
10379                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10380            }
10381            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10382            if (removedPackage != null) {
10383                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10384                        extras, null, null, removedUsers);
10385                if (fullRemove && !replacing) {
10386                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10387                            extras, null, null, removedUsers);
10388                }
10389            }
10390            if (removedAppId >= 0) {
10391                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10392                        removedUsers);
10393            }
10394        }
10395    }
10396
10397    /*
10398     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10399     * flag is not set, the data directory is removed as well.
10400     * make sure this flag is set for partially installed apps. If not its meaningless to
10401     * delete a partially installed application.
10402     */
10403    private void removePackageDataLI(PackageSetting ps,
10404            int[] allUserHandles, boolean[] perUserInstalled,
10405            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10406        String packageName = ps.name;
10407        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10408        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10409        // Retrieve object to delete permissions for shared user later on
10410        final PackageSetting deletedPs;
10411        // reader
10412        synchronized (mPackages) {
10413            deletedPs = mSettings.mPackages.get(packageName);
10414            if (outInfo != null) {
10415                outInfo.removedPackage = packageName;
10416                outInfo.removedUsers = deletedPs != null
10417                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10418                        : null;
10419            }
10420        }
10421        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10422            removeDataDirsLI(packageName);
10423            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10424        }
10425        // writer
10426        synchronized (mPackages) {
10427            if (deletedPs != null) {
10428                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10429                    if (outInfo != null) {
10430                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10431                    }
10432                    if (deletedPs != null) {
10433                        updatePermissionsLPw(deletedPs.name, null, 0);
10434                        if (deletedPs.sharedUser != null) {
10435                            // remove permissions associated with package
10436                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10437                        }
10438                    }
10439                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10440                }
10441                // make sure to preserve per-user disabled state if this removal was just
10442                // a downgrade of a system app to the factory package
10443                if (allUserHandles != null && perUserInstalled != null) {
10444                    if (DEBUG_REMOVE) {
10445                        Slog.d(TAG, "Propagating install state across downgrade");
10446                    }
10447                    for (int i = 0; i < allUserHandles.length; i++) {
10448                        if (DEBUG_REMOVE) {
10449                            Slog.d(TAG, "    user " + allUserHandles[i]
10450                                    + " => " + perUserInstalled[i]);
10451                        }
10452                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10453                    }
10454                }
10455            }
10456            // can downgrade to reader
10457            if (writeSettings) {
10458                // Save settings now
10459                mSettings.writeLPr();
10460            }
10461        }
10462        if (outInfo != null) {
10463            // A user ID was deleted here. Go through all users and remove it
10464            // from KeyStore.
10465            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10466        }
10467    }
10468
10469    static boolean locationIsPrivileged(File path) {
10470        try {
10471            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10472                    .getCanonicalPath();
10473            return path.getCanonicalPath().startsWith(privilegedAppDir);
10474        } catch (IOException e) {
10475            Slog.e(TAG, "Unable to access code path " + path);
10476        }
10477        return false;
10478    }
10479
10480    /*
10481     * Tries to delete system package.
10482     */
10483    private boolean deleteSystemPackageLI(PackageSetting newPs,
10484            int[] allUserHandles, boolean[] perUserInstalled,
10485            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10486        final boolean applyUserRestrictions
10487                = (allUserHandles != null) && (perUserInstalled != null);
10488        PackageSetting disabledPs = null;
10489        // Confirm if the system package has been updated
10490        // An updated system app can be deleted. This will also have to restore
10491        // the system pkg from system partition
10492        // reader
10493        synchronized (mPackages) {
10494            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10495        }
10496        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10497                + " disabledPs=" + disabledPs);
10498        if (disabledPs == null) {
10499            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10500            return false;
10501        } else if (DEBUG_REMOVE) {
10502            Slog.d(TAG, "Deleting system pkg from data partition");
10503        }
10504        if (DEBUG_REMOVE) {
10505            if (applyUserRestrictions) {
10506                Slog.d(TAG, "Remembering install states:");
10507                for (int i = 0; i < allUserHandles.length; i++) {
10508                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10509                }
10510            }
10511        }
10512        // Delete the updated package
10513        outInfo.isRemovedPackageSystemUpdate = true;
10514        if (disabledPs.versionCode < newPs.versionCode) {
10515            // Delete data for downgrades
10516            flags &= ~PackageManager.DELETE_KEEP_DATA;
10517        } else {
10518            // Preserve data by setting flag
10519            flags |= PackageManager.DELETE_KEEP_DATA;
10520        }
10521        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10522                allUserHandles, perUserInstalled, outInfo, writeSettings);
10523        if (!ret) {
10524            return false;
10525        }
10526        // writer
10527        synchronized (mPackages) {
10528            // Reinstate the old system package
10529            mSettings.enableSystemPackageLPw(newPs.name);
10530            // Remove any native libraries from the upgraded package.
10531            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10532        }
10533        // Install the system package
10534        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10535        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10536        if (locationIsPrivileged(disabledPs.codePath)) {
10537            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10538        }
10539        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10540                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null);
10541
10542        if (newPkg == null) {
10543            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10544                    + " with error:" + mLastScanError);
10545            return false;
10546        }
10547        // writer
10548        synchronized (mPackages) {
10549            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10550            setInternalAppNativeLibraryPath(newPkg, ps);
10551            updatePermissionsLPw(newPkg.packageName, newPkg,
10552                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10553            if (applyUserRestrictions) {
10554                if (DEBUG_REMOVE) {
10555                    Slog.d(TAG, "Propagating install state across reinstall");
10556                }
10557                for (int i = 0; i < allUserHandles.length; i++) {
10558                    if (DEBUG_REMOVE) {
10559                        Slog.d(TAG, "    user " + allUserHandles[i]
10560                                + " => " + perUserInstalled[i]);
10561                    }
10562                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10563                }
10564                // Regardless of writeSettings we need to ensure that this restriction
10565                // state propagation is persisted
10566                mSettings.writeAllUsersPackageRestrictionsLPr();
10567            }
10568            // can downgrade to reader here
10569            if (writeSettings) {
10570                mSettings.writeLPr();
10571            }
10572        }
10573        return true;
10574    }
10575
10576    private boolean deleteInstalledPackageLI(PackageSetting ps,
10577            boolean deleteCodeAndResources, int flags,
10578            int[] allUserHandles, boolean[] perUserInstalled,
10579            PackageRemovedInfo outInfo, boolean writeSettings) {
10580        if (outInfo != null) {
10581            outInfo.uid = ps.appId;
10582        }
10583
10584        // Delete package data from internal structures and also remove data if flag is set
10585        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10586
10587        // Delete application code and resources
10588        if (deleteCodeAndResources && (outInfo != null)) {
10589            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
10590                    ps.resourcePathString, ps.nativeLibraryPathString,
10591                    getAppInstructionSetFromSettings(ps));
10592        }
10593        return true;
10594    }
10595
10596    /*
10597     * This method handles package deletion in general
10598     */
10599    private boolean deletePackageLI(String packageName, UserHandle user,
10600            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10601            int flags, PackageRemovedInfo outInfo,
10602            boolean writeSettings) {
10603        if (packageName == null) {
10604            Slog.w(TAG, "Attempt to delete null packageName.");
10605            return false;
10606        }
10607        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10608        PackageSetting ps;
10609        boolean dataOnly = false;
10610        int removeUser = -1;
10611        int appId = -1;
10612        synchronized (mPackages) {
10613            ps = mSettings.mPackages.get(packageName);
10614            if (ps == null) {
10615                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10616                return false;
10617            }
10618            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10619                    && user.getIdentifier() != UserHandle.USER_ALL) {
10620                // The caller is asking that the package only be deleted for a single
10621                // user.  To do this, we just mark its uninstalled state and delete
10622                // its data.  If this is a system app, we only allow this to happen if
10623                // they have set the special DELETE_SYSTEM_APP which requests different
10624                // semantics than normal for uninstalling system apps.
10625                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10626                ps.setUserState(user.getIdentifier(),
10627                        COMPONENT_ENABLED_STATE_DEFAULT,
10628                        false, //installed
10629                        true,  //stopped
10630                        true,  //notLaunched
10631                        false, //blocked
10632                        null, null, null);
10633                if (!isSystemApp(ps)) {
10634                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10635                        // Other user still have this package installed, so all
10636                        // we need to do is clear this user's data and save that
10637                        // it is uninstalled.
10638                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10639                        removeUser = user.getIdentifier();
10640                        appId = ps.appId;
10641                        mSettings.writePackageRestrictionsLPr(removeUser);
10642                    } else {
10643                        // We need to set it back to 'installed' so the uninstall
10644                        // broadcasts will be sent correctly.
10645                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10646                        ps.setInstalled(true, user.getIdentifier());
10647                    }
10648                } else {
10649                    // This is a system app, so we assume that the
10650                    // other users still have this package installed, so all
10651                    // we need to do is clear this user's data and save that
10652                    // it is uninstalled.
10653                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10654                    removeUser = user.getIdentifier();
10655                    appId = ps.appId;
10656                    mSettings.writePackageRestrictionsLPr(removeUser);
10657                }
10658            }
10659        }
10660
10661        if (removeUser >= 0) {
10662            // From above, we determined that we are deleting this only
10663            // for a single user.  Continue the work here.
10664            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10665            if (outInfo != null) {
10666                outInfo.removedPackage = packageName;
10667                outInfo.removedAppId = appId;
10668                outInfo.removedUsers = new int[] {removeUser};
10669            }
10670            mInstaller.clearUserData(packageName, removeUser);
10671            removeKeystoreDataIfNeeded(removeUser, appId);
10672            schedulePackageCleaning(packageName, removeUser, false);
10673            return true;
10674        }
10675
10676        if (dataOnly) {
10677            // Delete application data first
10678            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10679            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10680            return true;
10681        }
10682
10683        boolean ret = false;
10684        mSettings.mKeySetManager.removeAppKeySetData(packageName);
10685        if (isSystemApp(ps)) {
10686            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10687            // When an updated system application is deleted we delete the existing resources as well and
10688            // fall back to existing code in system partition
10689            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10690                    flags, outInfo, writeSettings);
10691        } else {
10692            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10693            // Kill application pre-emptively especially for apps on sd.
10694            killApplication(packageName, ps.appId, "uninstall pkg");
10695            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10696                    allUserHandles, perUserInstalled,
10697                    outInfo, writeSettings);
10698        }
10699
10700        return ret;
10701    }
10702
10703    private final class ClearStorageConnection implements ServiceConnection {
10704        IMediaContainerService mContainerService;
10705
10706        @Override
10707        public void onServiceConnected(ComponentName name, IBinder service) {
10708            synchronized (this) {
10709                mContainerService = IMediaContainerService.Stub.asInterface(service);
10710                notifyAll();
10711            }
10712        }
10713
10714        @Override
10715        public void onServiceDisconnected(ComponentName name) {
10716        }
10717    }
10718
10719    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10720        final boolean mounted;
10721        if (Environment.isExternalStorageEmulated()) {
10722            mounted = true;
10723        } else {
10724            final String status = Environment.getExternalStorageState();
10725
10726            mounted = status.equals(Environment.MEDIA_MOUNTED)
10727                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10728        }
10729
10730        if (!mounted) {
10731            return;
10732        }
10733
10734        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10735        int[] users;
10736        if (userId == UserHandle.USER_ALL) {
10737            users = sUserManager.getUserIds();
10738        } else {
10739            users = new int[] { userId };
10740        }
10741        final ClearStorageConnection conn = new ClearStorageConnection();
10742        if (mContext.bindServiceAsUser(
10743                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10744            try {
10745                for (int curUser : users) {
10746                    long timeout = SystemClock.uptimeMillis() + 5000;
10747                    synchronized (conn) {
10748                        long now = SystemClock.uptimeMillis();
10749                        while (conn.mContainerService == null && now < timeout) {
10750                            try {
10751                                conn.wait(timeout - now);
10752                            } catch (InterruptedException e) {
10753                            }
10754                        }
10755                    }
10756                    if (conn.mContainerService == null) {
10757                        return;
10758                    }
10759
10760                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10761                    clearDirectory(conn.mContainerService,
10762                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10763                    if (allData) {
10764                        clearDirectory(conn.mContainerService,
10765                                userEnv.buildExternalStorageAppDataDirs(packageName));
10766                        clearDirectory(conn.mContainerService,
10767                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10768                    }
10769                }
10770            } finally {
10771                mContext.unbindService(conn);
10772            }
10773        }
10774    }
10775
10776    @Override
10777    public void clearApplicationUserData(final String packageName,
10778            final IPackageDataObserver observer, final int userId) {
10779        mContext.enforceCallingOrSelfPermission(
10780                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
10781        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
10782        // Queue up an async operation since the package deletion may take a little while.
10783        mHandler.post(new Runnable() {
10784            public void run() {
10785                mHandler.removeCallbacks(this);
10786                final boolean succeeded;
10787                synchronized (mInstallLock) {
10788                    succeeded = clearApplicationUserDataLI(packageName, userId);
10789                }
10790                clearExternalStorageDataSync(packageName, userId, true);
10791                if (succeeded) {
10792                    // invoke DeviceStorageMonitor's update method to clear any notifications
10793                    DeviceStorageMonitorInternal
10794                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
10795                    if (dsm != null) {
10796                        dsm.checkMemory();
10797                    }
10798                }
10799                if(observer != null) {
10800                    try {
10801                        observer.onRemoveCompleted(packageName, succeeded);
10802                    } catch (RemoteException e) {
10803                        Log.i(TAG, "Observer no longer exists.");
10804                    }
10805                } //end if observer
10806            } //end run
10807        });
10808    }
10809
10810    private boolean clearApplicationUserDataLI(String packageName, int userId) {
10811        if (packageName == null) {
10812            Slog.w(TAG, "Attempt to delete null packageName.");
10813            return false;
10814        }
10815        PackageParser.Package p;
10816        boolean dataOnly = false;
10817        final int appId;
10818        synchronized (mPackages) {
10819            p = mPackages.get(packageName);
10820            if (p == null) {
10821                dataOnly = true;
10822                PackageSetting ps = mSettings.mPackages.get(packageName);
10823                if ((ps == null) || (ps.pkg == null)) {
10824                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10825                    return false;
10826                }
10827                p = ps.pkg;
10828            }
10829            if (!dataOnly) {
10830                // need to check this only for fully installed applications
10831                if (p == null) {
10832                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10833                    return false;
10834                }
10835                final ApplicationInfo applicationInfo = p.applicationInfo;
10836                if (applicationInfo == null) {
10837                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10838                    return false;
10839                }
10840            }
10841            if (p != null && p.applicationInfo != null) {
10842                appId = p.applicationInfo.uid;
10843            } else {
10844                appId = -1;
10845            }
10846        }
10847        int retCode = mInstaller.clearUserData(packageName, userId);
10848        if (retCode < 0) {
10849            Slog.w(TAG, "Couldn't remove cache files for package: "
10850                    + packageName);
10851            return false;
10852        }
10853        removeKeystoreDataIfNeeded(userId, appId);
10854        return true;
10855    }
10856
10857    /**
10858     * Remove entries from the keystore daemon. Will only remove it if the
10859     * {@code appId} is valid.
10860     */
10861    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
10862        if (appId < 0) {
10863            return;
10864        }
10865
10866        final KeyStore keyStore = KeyStore.getInstance();
10867        if (keyStore != null) {
10868            if (userId == UserHandle.USER_ALL) {
10869                for (final int individual : sUserManager.getUserIds()) {
10870                    keyStore.clearUid(UserHandle.getUid(individual, appId));
10871                }
10872            } else {
10873                keyStore.clearUid(UserHandle.getUid(userId, appId));
10874            }
10875        } else {
10876            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
10877        }
10878    }
10879
10880    public void deleteApplicationCacheFiles(final String packageName,
10881            final IPackageDataObserver observer) {
10882        mContext.enforceCallingOrSelfPermission(
10883                android.Manifest.permission.DELETE_CACHE_FILES, null);
10884        // Queue up an async operation since the package deletion may take a little while.
10885        final int userId = UserHandle.getCallingUserId();
10886        mHandler.post(new Runnable() {
10887            public void run() {
10888                mHandler.removeCallbacks(this);
10889                final boolean succeded;
10890                synchronized (mInstallLock) {
10891                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
10892                }
10893                clearExternalStorageDataSync(packageName, userId, false);
10894                if(observer != null) {
10895                    try {
10896                        observer.onRemoveCompleted(packageName, succeded);
10897                    } catch (RemoteException e) {
10898                        Log.i(TAG, "Observer no longer exists.");
10899                    }
10900                } //end if observer
10901            } //end run
10902        });
10903    }
10904
10905    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
10906        if (packageName == null) {
10907            Slog.w(TAG, "Attempt to delete null packageName.");
10908            return false;
10909        }
10910        PackageParser.Package p;
10911        synchronized (mPackages) {
10912            p = mPackages.get(packageName);
10913        }
10914        if (p == null) {
10915            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10916            return false;
10917        }
10918        final ApplicationInfo applicationInfo = p.applicationInfo;
10919        if (applicationInfo == null) {
10920            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10921            return false;
10922        }
10923        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
10924        if (retCode < 0) {
10925            Slog.w(TAG, "Couldn't remove cache files for package: "
10926                       + packageName + " u" + userId);
10927            return false;
10928        }
10929        return true;
10930    }
10931
10932    public void getPackageSizeInfo(final String packageName, int userHandle,
10933            final IPackageStatsObserver observer) {
10934        mContext.enforceCallingOrSelfPermission(
10935                android.Manifest.permission.GET_PACKAGE_SIZE, null);
10936        if (packageName == null) {
10937            throw new IllegalArgumentException("Attempt to get size of null packageName");
10938        }
10939
10940        PackageStats stats = new PackageStats(packageName, userHandle);
10941
10942        /*
10943         * Queue up an async operation since the package measurement may take a
10944         * little while.
10945         */
10946        Message msg = mHandler.obtainMessage(INIT_COPY);
10947        msg.obj = new MeasureParams(stats, observer);
10948        mHandler.sendMessage(msg);
10949    }
10950
10951    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
10952            PackageStats pStats) {
10953        if (packageName == null) {
10954            Slog.w(TAG, "Attempt to get size of null packageName.");
10955            return false;
10956        }
10957        PackageParser.Package p;
10958        boolean dataOnly = false;
10959        String libDirPath = null;
10960        String asecPath = null;
10961        PackageSetting ps = null;
10962        synchronized (mPackages) {
10963            p = mPackages.get(packageName);
10964            ps = mSettings.mPackages.get(packageName);
10965            if(p == null) {
10966                dataOnly = true;
10967                if((ps == null) || (ps.pkg == null)) {
10968                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
10969                    return false;
10970                }
10971                p = ps.pkg;
10972            }
10973            if (ps != null) {
10974                libDirPath = ps.nativeLibraryPathString;
10975            }
10976            if (p != null && (isExternal(p) || isForwardLocked(p))) {
10977                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
10978                if (secureContainerId != null) {
10979                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
10980                }
10981            }
10982        }
10983        String publicSrcDir = null;
10984        if(!dataOnly) {
10985            final ApplicationInfo applicationInfo = p.applicationInfo;
10986            if (applicationInfo == null) {
10987                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
10988                return false;
10989            }
10990            if (isForwardLocked(p)) {
10991                publicSrcDir = applicationInfo.publicSourceDir;
10992            }
10993        }
10994        int res = mInstaller.getSizeInfo(packageName, userHandle, p.mPath, libDirPath,
10995                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
10996                pStats);
10997        if (res < 0) {
10998            return false;
10999        }
11000
11001        // Fix-up for forward-locked applications in ASEC containers.
11002        if (!isExternal(p)) {
11003            pStats.codeSize += pStats.externalCodeSize;
11004            pStats.externalCodeSize = 0L;
11005        }
11006
11007        return true;
11008    }
11009
11010
11011    public void addPackageToPreferred(String packageName) {
11012        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11013    }
11014
11015    public void removePackageFromPreferred(String packageName) {
11016        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11017    }
11018
11019    public List<PackageInfo> getPreferredPackages(int flags) {
11020        return new ArrayList<PackageInfo>();
11021    }
11022
11023    private int getUidTargetSdkVersionLockedLPr(int uid) {
11024        Object obj = mSettings.getUserIdLPr(uid);
11025        if (obj instanceof SharedUserSetting) {
11026            final SharedUserSetting sus = (SharedUserSetting) obj;
11027            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11028            final Iterator<PackageSetting> it = sus.packages.iterator();
11029            while (it.hasNext()) {
11030                final PackageSetting ps = it.next();
11031                if (ps.pkg != null) {
11032                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11033                    if (v < vers) vers = v;
11034                }
11035            }
11036            return vers;
11037        } else if (obj instanceof PackageSetting) {
11038            final PackageSetting ps = (PackageSetting) obj;
11039            if (ps.pkg != null) {
11040                return ps.pkg.applicationInfo.targetSdkVersion;
11041            }
11042        }
11043        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11044    }
11045
11046    public void addPreferredActivity(IntentFilter filter, int match,
11047            ComponentName[] set, ComponentName activity, int userId) {
11048        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11049    }
11050
11051    private void addPreferredActivityInternal(IntentFilter filter, int match,
11052            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11053        // writer
11054        int callingUid = Binder.getCallingUid();
11055        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11056        if (filter.countActions() == 0) {
11057            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11058            return;
11059        }
11060        synchronized (mPackages) {
11061            if (mContext.checkCallingOrSelfPermission(
11062                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11063                    != PackageManager.PERMISSION_GRANTED) {
11064                if (getUidTargetSdkVersionLockedLPr(callingUid)
11065                        < Build.VERSION_CODES.FROYO) {
11066                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11067                            + callingUid);
11068                    return;
11069                }
11070                mContext.enforceCallingOrSelfPermission(
11071                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11072            }
11073
11074            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11075            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11076            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11077                    new PreferredActivity(filter, match, set, activity, always));
11078            mSettings.writePackageRestrictionsLPr(userId);
11079        }
11080    }
11081
11082    public void replacePreferredActivity(IntentFilter filter, int match,
11083            ComponentName[] set, ComponentName activity) {
11084        if (filter.countActions() != 1) {
11085            throw new IllegalArgumentException(
11086                    "replacePreferredActivity expects filter to have only 1 action.");
11087        }
11088        if (filter.countDataAuthorities() != 0
11089                || filter.countDataPaths() != 0
11090                || filter.countDataSchemes() > 1
11091                || filter.countDataTypes() != 0) {
11092            throw new IllegalArgumentException(
11093                    "replacePreferredActivity expects filter to have no data authorities, " +
11094                    "paths, or types; and at most one scheme.");
11095        }
11096        synchronized (mPackages) {
11097            if (mContext.checkCallingOrSelfPermission(
11098                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11099                    != PackageManager.PERMISSION_GRANTED) {
11100                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11101                        < Build.VERSION_CODES.FROYO) {
11102                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11103                            + Binder.getCallingUid());
11104                    return;
11105                }
11106                mContext.enforceCallingOrSelfPermission(
11107                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11108            }
11109
11110            final int callingUserId = UserHandle.getCallingUserId();
11111            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11112            if (pir != null) {
11113                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11114                if (filter.countDataSchemes() == 1) {
11115                    Uri.Builder builder = new Uri.Builder();
11116                    builder.scheme(filter.getDataScheme(0));
11117                    intent.setData(builder.build());
11118                }
11119                List<PreferredActivity> matches = pir.queryIntent(
11120                        intent, null, true, callingUserId);
11121                if (DEBUG_PREFERRED) {
11122                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11123                }
11124                for (int i = 0; i < matches.size(); i++) {
11125                    PreferredActivity pa = matches.get(i);
11126                    if (DEBUG_PREFERRED) {
11127                        Slog.i(TAG, "Removing preferred activity "
11128                                + pa.mPref.mComponent + ":");
11129                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11130                    }
11131                    pir.removeFilter(pa);
11132                }
11133            }
11134            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11135        }
11136    }
11137
11138    public void clearPackagePreferredActivities(String packageName) {
11139        final int uid = Binder.getCallingUid();
11140        // writer
11141        synchronized (mPackages) {
11142            PackageParser.Package pkg = mPackages.get(packageName);
11143            if (pkg == null || pkg.applicationInfo.uid != uid) {
11144                if (mContext.checkCallingOrSelfPermission(
11145                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11146                        != PackageManager.PERMISSION_GRANTED) {
11147                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11148                            < Build.VERSION_CODES.FROYO) {
11149                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11150                                + Binder.getCallingUid());
11151                        return;
11152                    }
11153                    mContext.enforceCallingOrSelfPermission(
11154                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11155                }
11156            }
11157
11158            int user = UserHandle.getCallingUserId();
11159            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11160                mSettings.writePackageRestrictionsLPr(user);
11161                scheduleWriteSettingsLocked();
11162            }
11163        }
11164    }
11165
11166    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11167    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11168        ArrayList<PreferredActivity> removed = null;
11169        boolean changed = false;
11170        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11171            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11172            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11173            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11174                continue;
11175            }
11176            Iterator<PreferredActivity> it = pir.filterIterator();
11177            while (it.hasNext()) {
11178                PreferredActivity pa = it.next();
11179                // Mark entry for removal only if it matches the package name
11180                // and the entry is of type "always".
11181                if (packageName == null ||
11182                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11183                                && pa.mPref.mAlways)) {
11184                    if (removed == null) {
11185                        removed = new ArrayList<PreferredActivity>();
11186                    }
11187                    removed.add(pa);
11188                }
11189            }
11190            if (removed != null) {
11191                for (int j=0; j<removed.size(); j++) {
11192                    PreferredActivity pa = removed.get(j);
11193                    pir.removeFilter(pa);
11194                }
11195                changed = true;
11196            }
11197        }
11198        return changed;
11199    }
11200
11201    public void resetPreferredActivities(int userId) {
11202        mContext.enforceCallingOrSelfPermission(
11203                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11204        // writer
11205        synchronized (mPackages) {
11206            int user = UserHandle.getCallingUserId();
11207            clearPackagePreferredActivitiesLPw(null, user);
11208            mSettings.readDefaultPreferredAppsLPw(this, user);
11209            mSettings.writePackageRestrictionsLPr(user);
11210            scheduleWriteSettingsLocked();
11211        }
11212    }
11213
11214    public int getPreferredActivities(List<IntentFilter> outFilters,
11215            List<ComponentName> outActivities, String packageName) {
11216
11217        int num = 0;
11218        final int userId = UserHandle.getCallingUserId();
11219        // reader
11220        synchronized (mPackages) {
11221            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11222            if (pir != null) {
11223                final Iterator<PreferredActivity> it = pir.filterIterator();
11224                while (it.hasNext()) {
11225                    final PreferredActivity pa = it.next();
11226                    if (packageName == null
11227                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11228                                    && pa.mPref.mAlways)) {
11229                        if (outFilters != null) {
11230                            outFilters.add(new IntentFilter(pa));
11231                        }
11232                        if (outActivities != null) {
11233                            outActivities.add(pa.mPref.mComponent);
11234                        }
11235                    }
11236                }
11237            }
11238        }
11239
11240        return num;
11241    }
11242
11243    @Override
11244    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11245            int userId) {
11246        int callingUid = Binder.getCallingUid();
11247        if (callingUid != Process.SYSTEM_UID) {
11248            throw new SecurityException(
11249                    "addPersistentPreferredActivity can only be run by the system");
11250        }
11251        if (filter.countActions() == 0) {
11252            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11253            return;
11254        }
11255        synchronized (mPackages) {
11256            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11257                    " :");
11258            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11259            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11260                    new PersistentPreferredActivity(filter, activity));
11261            mSettings.writePackageRestrictionsLPr(userId);
11262        }
11263    }
11264
11265    @Override
11266    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11267        int callingUid = Binder.getCallingUid();
11268        if (callingUid != Process.SYSTEM_UID) {
11269            throw new SecurityException(
11270                    "clearPackagePersistentPreferredActivities can only be run by the system");
11271        }
11272        ArrayList<PersistentPreferredActivity> removed = null;
11273        boolean changed = false;
11274        synchronized (mPackages) {
11275            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11276                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11277                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11278                        .valueAt(i);
11279                if (userId != thisUserId) {
11280                    continue;
11281                }
11282                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11283                while (it.hasNext()) {
11284                    PersistentPreferredActivity ppa = it.next();
11285                    // Mark entry for removal only if it matches the package name.
11286                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11287                        if (removed == null) {
11288                            removed = new ArrayList<PersistentPreferredActivity>();
11289                        }
11290                        removed.add(ppa);
11291                    }
11292                }
11293                if (removed != null) {
11294                    for (int j=0; j<removed.size(); j++) {
11295                        PersistentPreferredActivity ppa = removed.get(j);
11296                        ppir.removeFilter(ppa);
11297                    }
11298                    changed = true;
11299                }
11300            }
11301
11302            if (changed) {
11303                mSettings.writePackageRestrictionsLPr(userId);
11304            }
11305        }
11306    }
11307
11308    @Override
11309    public void addForwardingIntentFilter(IntentFilter filter, boolean removable, int userIdOrig,
11310            int userIdDest) {
11311        mContext.enforceCallingOrSelfPermission(
11312                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11313        if (filter.countActions() == 0) {
11314            Slog.w(TAG, "Cannot set a forwarding intent filter with no filter actions");
11315            return;
11316        }
11317        synchronized (mPackages) {
11318            mSettings.editForwardingIntentResolverLPw(userIdOrig).addFilter(
11319                    new ForwardingIntentFilter(filter, removable, userIdDest));
11320            mSettings.writePackageRestrictionsLPr(userIdOrig);
11321        }
11322    }
11323
11324    @Override
11325    public void clearForwardingIntentFilters(int userIdOrig) {
11326        mContext.enforceCallingOrSelfPermission(
11327                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11328        synchronized (mPackages) {
11329            ForwardingIntentResolver fir = mSettings.editForwardingIntentResolverLPw(userIdOrig);
11330            HashSet<ForwardingIntentFilter> set =
11331                    new HashSet<ForwardingIntentFilter>(fir.filterSet());
11332            for (ForwardingIntentFilter fif : set) {
11333                if (fif.isRemovable()) fir.removeFilter(fif);
11334            }
11335            mSettings.writePackageRestrictionsLPr(userIdOrig);
11336        }
11337    }
11338
11339    @Override
11340    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11341        Intent intent = new Intent(Intent.ACTION_MAIN);
11342        intent.addCategory(Intent.CATEGORY_HOME);
11343
11344        final int callingUserId = UserHandle.getCallingUserId();
11345        List<ResolveInfo> list = queryIntentActivities(intent, null,
11346                PackageManager.GET_META_DATA, callingUserId);
11347        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11348                true, false, false, callingUserId);
11349
11350        allHomeCandidates.clear();
11351        if (list != null) {
11352            for (ResolveInfo ri : list) {
11353                allHomeCandidates.add(ri);
11354            }
11355        }
11356        return (preferred == null || preferred.activityInfo == null)
11357                ? null
11358                : new ComponentName(preferred.activityInfo.packageName,
11359                        preferred.activityInfo.name);
11360    }
11361
11362    @Override
11363    public void setApplicationEnabledSetting(String appPackageName,
11364            int newState, int flags, int userId, String callingPackage) {
11365        if (!sUserManager.exists(userId)) return;
11366        if (callingPackage == null) {
11367            callingPackage = Integer.toString(Binder.getCallingUid());
11368        }
11369        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11370    }
11371
11372    @Override
11373    public void setComponentEnabledSetting(ComponentName componentName,
11374            int newState, int flags, int userId) {
11375        if (!sUserManager.exists(userId)) return;
11376        setEnabledSetting(componentName.getPackageName(),
11377                componentName.getClassName(), newState, flags, userId, null);
11378    }
11379
11380    private void setEnabledSetting(final String packageName, String className, int newState,
11381            final int flags, int userId, String callingPackage) {
11382        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11383              || newState == COMPONENT_ENABLED_STATE_ENABLED
11384              || newState == COMPONENT_ENABLED_STATE_DISABLED
11385              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11386              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11387            throw new IllegalArgumentException("Invalid new component state: "
11388                    + newState);
11389        }
11390        PackageSetting pkgSetting;
11391        final int uid = Binder.getCallingUid();
11392        final int permission = mContext.checkCallingOrSelfPermission(
11393                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11394        enforceCrossUserPermission(uid, userId, false, "set enabled");
11395        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11396        boolean sendNow = false;
11397        boolean isApp = (className == null);
11398        String componentName = isApp ? packageName : className;
11399        int packageUid = -1;
11400        ArrayList<String> components;
11401
11402        // writer
11403        synchronized (mPackages) {
11404            pkgSetting = mSettings.mPackages.get(packageName);
11405            if (pkgSetting == null) {
11406                if (className == null) {
11407                    throw new IllegalArgumentException(
11408                            "Unknown package: " + packageName);
11409                }
11410                throw new IllegalArgumentException(
11411                        "Unknown component: " + packageName
11412                        + "/" + className);
11413            }
11414            // Allow root and verify that userId is not being specified by a different user
11415            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11416                throw new SecurityException(
11417                        "Permission Denial: attempt to change component state from pid="
11418                        + Binder.getCallingPid()
11419                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11420            }
11421            if (className == null) {
11422                // We're dealing with an application/package level state change
11423                if (pkgSetting.getEnabled(userId) == newState) {
11424                    // Nothing to do
11425                    return;
11426                }
11427                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11428                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11429                    // Don't care about who enables an app.
11430                    callingPackage = null;
11431                }
11432                pkgSetting.setEnabled(newState, userId, callingPackage);
11433                // pkgSetting.pkg.mSetEnabled = newState;
11434            } else {
11435                // We're dealing with a component level state change
11436                // First, verify that this is a valid class name.
11437                PackageParser.Package pkg = pkgSetting.pkg;
11438                if (pkg == null || !pkg.hasComponentClassName(className)) {
11439                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11440                        throw new IllegalArgumentException("Component class " + className
11441                                + " does not exist in " + packageName);
11442                    } else {
11443                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11444                                + className + " does not exist in " + packageName);
11445                    }
11446                }
11447                switch (newState) {
11448                case COMPONENT_ENABLED_STATE_ENABLED:
11449                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11450                        return;
11451                    }
11452                    break;
11453                case COMPONENT_ENABLED_STATE_DISABLED:
11454                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11455                        return;
11456                    }
11457                    break;
11458                case COMPONENT_ENABLED_STATE_DEFAULT:
11459                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11460                        return;
11461                    }
11462                    break;
11463                default:
11464                    Slog.e(TAG, "Invalid new component state: " + newState);
11465                    return;
11466                }
11467            }
11468            mSettings.writePackageRestrictionsLPr(userId);
11469            components = mPendingBroadcasts.get(userId, packageName);
11470            final boolean newPackage = components == null;
11471            if (newPackage) {
11472                components = new ArrayList<String>();
11473            }
11474            if (!components.contains(componentName)) {
11475                components.add(componentName);
11476            }
11477            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11478                sendNow = true;
11479                // Purge entry from pending broadcast list if another one exists already
11480                // since we are sending one right away.
11481                mPendingBroadcasts.remove(userId, packageName);
11482            } else {
11483                if (newPackage) {
11484                    mPendingBroadcasts.put(userId, packageName, components);
11485                }
11486                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11487                    // Schedule a message
11488                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11489                }
11490            }
11491        }
11492
11493        long callingId = Binder.clearCallingIdentity();
11494        try {
11495            if (sendNow) {
11496                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11497                sendPackageChangedBroadcast(packageName,
11498                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11499            }
11500        } finally {
11501            Binder.restoreCallingIdentity(callingId);
11502        }
11503    }
11504
11505    private void sendPackageChangedBroadcast(String packageName,
11506            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11507        if (DEBUG_INSTALL)
11508            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11509                    + componentNames);
11510        Bundle extras = new Bundle(4);
11511        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11512        String nameList[] = new String[componentNames.size()];
11513        componentNames.toArray(nameList);
11514        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11515        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11516        extras.putInt(Intent.EXTRA_UID, packageUid);
11517        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11518                new int[] {UserHandle.getUserId(packageUid)});
11519    }
11520
11521    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11522        if (!sUserManager.exists(userId)) return;
11523        final int uid = Binder.getCallingUid();
11524        final int permission = mContext.checkCallingOrSelfPermission(
11525                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11526        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11527        enforceCrossUserPermission(uid, userId, true, "stop package");
11528        // writer
11529        synchronized (mPackages) {
11530            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11531                    uid, userId)) {
11532                scheduleWritePackageRestrictionsLocked(userId);
11533            }
11534        }
11535    }
11536
11537    public String getInstallerPackageName(String packageName) {
11538        // reader
11539        synchronized (mPackages) {
11540            return mSettings.getInstallerPackageNameLPr(packageName);
11541        }
11542    }
11543
11544    @Override
11545    public int getApplicationEnabledSetting(String packageName, int userId) {
11546        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11547        int uid = Binder.getCallingUid();
11548        enforceCrossUserPermission(uid, userId, false, "get enabled");
11549        // reader
11550        synchronized (mPackages) {
11551            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11552        }
11553    }
11554
11555    @Override
11556    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11557        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11558        int uid = Binder.getCallingUid();
11559        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11560        // reader
11561        synchronized (mPackages) {
11562            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11563        }
11564    }
11565
11566    public void enterSafeMode() {
11567        enforceSystemOrRoot("Only the system can request entering safe mode");
11568
11569        if (!mSystemReady) {
11570            mSafeMode = true;
11571        }
11572    }
11573
11574    public void systemReady() {
11575        mSystemReady = true;
11576
11577        // Read the compatibilty setting when the system is ready.
11578        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11579                mContext.getContentResolver(),
11580                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11581        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11582        if (DEBUG_SETTINGS) {
11583            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11584        }
11585
11586        synchronized (mPackages) {
11587            // Verify that all of the preferred activity components actually
11588            // exist.  It is possible for applications to be updated and at
11589            // that point remove a previously declared activity component that
11590            // had been set as a preferred activity.  We try to clean this up
11591            // the next time we encounter that preferred activity, but it is
11592            // possible for the user flow to never be able to return to that
11593            // situation so here we do a sanity check to make sure we haven't
11594            // left any junk around.
11595            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11596            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11597                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11598                removed.clear();
11599                for (PreferredActivity pa : pir.filterSet()) {
11600                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11601                        removed.add(pa);
11602                    }
11603                }
11604                if (removed.size() > 0) {
11605                    for (int j=0; j<removed.size(); j++) {
11606                        PreferredActivity pa = removed.get(i);
11607                        Slog.w(TAG, "Removing dangling preferred activity: "
11608                                + pa.mPref.mComponent);
11609                        pir.removeFilter(pa);
11610                    }
11611                    mSettings.writePackageRestrictionsLPr(
11612                            mSettings.mPreferredActivities.keyAt(i));
11613                }
11614            }
11615        }
11616        sUserManager.systemReady();
11617    }
11618
11619    public boolean isSafeMode() {
11620        return mSafeMode;
11621    }
11622
11623    public boolean hasSystemUidErrors() {
11624        return mHasSystemUidErrors;
11625    }
11626
11627    static String arrayToString(int[] array) {
11628        StringBuffer buf = new StringBuffer(128);
11629        buf.append('[');
11630        if (array != null) {
11631            for (int i=0; i<array.length; i++) {
11632                if (i > 0) buf.append(", ");
11633                buf.append(array[i]);
11634            }
11635        }
11636        buf.append(']');
11637        return buf.toString();
11638    }
11639
11640    static class DumpState {
11641        public static final int DUMP_LIBS = 1 << 0;
11642
11643        public static final int DUMP_FEATURES = 1 << 1;
11644
11645        public static final int DUMP_RESOLVERS = 1 << 2;
11646
11647        public static final int DUMP_PERMISSIONS = 1 << 3;
11648
11649        public static final int DUMP_PACKAGES = 1 << 4;
11650
11651        public static final int DUMP_SHARED_USERS = 1 << 5;
11652
11653        public static final int DUMP_MESSAGES = 1 << 6;
11654
11655        public static final int DUMP_PROVIDERS = 1 << 7;
11656
11657        public static final int DUMP_VERIFIERS = 1 << 8;
11658
11659        public static final int DUMP_PREFERRED = 1 << 9;
11660
11661        public static final int DUMP_PREFERRED_XML = 1 << 10;
11662
11663        public static final int DUMP_KEYSETS = 1 << 11;
11664
11665        public static final int DUMP_VERSION = 1 << 12;
11666
11667        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11668
11669        private int mTypes;
11670
11671        private int mOptions;
11672
11673        private boolean mTitlePrinted;
11674
11675        private SharedUserSetting mSharedUser;
11676
11677        public boolean isDumping(int type) {
11678            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11679                return true;
11680            }
11681
11682            return (mTypes & type) != 0;
11683        }
11684
11685        public void setDump(int type) {
11686            mTypes |= type;
11687        }
11688
11689        public boolean isOptionEnabled(int option) {
11690            return (mOptions & option) != 0;
11691        }
11692
11693        public void setOptionEnabled(int option) {
11694            mOptions |= option;
11695        }
11696
11697        public boolean onTitlePrinted() {
11698            final boolean printed = mTitlePrinted;
11699            mTitlePrinted = true;
11700            return printed;
11701        }
11702
11703        public boolean getTitlePrinted() {
11704            return mTitlePrinted;
11705        }
11706
11707        public void setTitlePrinted(boolean enabled) {
11708            mTitlePrinted = enabled;
11709        }
11710
11711        public SharedUserSetting getSharedUser() {
11712            return mSharedUser;
11713        }
11714
11715        public void setSharedUser(SharedUserSetting user) {
11716            mSharedUser = user;
11717        }
11718    }
11719
11720    @Override
11721    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11722        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
11723                != PackageManager.PERMISSION_GRANTED) {
11724            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11725                    + Binder.getCallingPid()
11726                    + ", uid=" + Binder.getCallingUid()
11727                    + " without permission "
11728                    + android.Manifest.permission.DUMP);
11729            return;
11730        }
11731
11732        DumpState dumpState = new DumpState();
11733        boolean fullPreferred = false;
11734        boolean checkin = false;
11735
11736        String packageName = null;
11737
11738        int opti = 0;
11739        while (opti < args.length) {
11740            String opt = args[opti];
11741            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11742                break;
11743            }
11744            opti++;
11745            if ("-a".equals(opt)) {
11746                // Right now we only know how to print all.
11747            } else if ("-h".equals(opt)) {
11748                pw.println("Package manager dump options:");
11749                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
11750                pw.println("    --checkin: dump for a checkin");
11751                pw.println("    -f: print details of intent filters");
11752                pw.println("    -h: print this help");
11753                pw.println("  cmd may be one of:");
11754                pw.println("    l[ibraries]: list known shared libraries");
11755                pw.println("    f[ibraries]: list device features");
11756                pw.println("    r[esolvers]: dump intent resolvers");
11757                pw.println("    perm[issions]: dump permissions");
11758                pw.println("    pref[erred]: print preferred package settings");
11759                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
11760                pw.println("    prov[iders]: dump content providers");
11761                pw.println("    p[ackages]: dump installed packages");
11762                pw.println("    s[hared-users]: dump shared user IDs");
11763                pw.println("    m[essages]: print collected runtime messages");
11764                pw.println("    v[erifiers]: print package verifier info");
11765                pw.println("    version: print database version info");
11766                pw.println("    <package.name>: info about given package");
11767                pw.println("    k[eysets]: print known keysets");
11768                return;
11769            } else if ("--checkin".equals(opt)) {
11770                checkin = true;
11771            } else if ("-f".equals(opt)) {
11772                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11773            } else {
11774                pw.println("Unknown argument: " + opt + "; use -h for help");
11775            }
11776        }
11777
11778        // Is the caller requesting to dump a particular piece of data?
11779        if (opti < args.length) {
11780            String cmd = args[opti];
11781            opti++;
11782            // Is this a package name?
11783            if ("android".equals(cmd) || cmd.contains(".")) {
11784                packageName = cmd;
11785                // When dumping a single package, we always dump all of its
11786                // filter information since the amount of data will be reasonable.
11787                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
11788            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
11789                dumpState.setDump(DumpState.DUMP_LIBS);
11790            } else if ("f".equals(cmd) || "features".equals(cmd)) {
11791                dumpState.setDump(DumpState.DUMP_FEATURES);
11792            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
11793                dumpState.setDump(DumpState.DUMP_RESOLVERS);
11794            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
11795                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
11796            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
11797                dumpState.setDump(DumpState.DUMP_PREFERRED);
11798            } else if ("preferred-xml".equals(cmd)) {
11799                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
11800                if (opti < args.length && "--full".equals(args[opti])) {
11801                    fullPreferred = true;
11802                    opti++;
11803                }
11804            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
11805                dumpState.setDump(DumpState.DUMP_PACKAGES);
11806            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
11807                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
11808            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
11809                dumpState.setDump(DumpState.DUMP_PROVIDERS);
11810            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
11811                dumpState.setDump(DumpState.DUMP_MESSAGES);
11812            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
11813                dumpState.setDump(DumpState.DUMP_VERIFIERS);
11814            } else if ("version".equals(cmd)) {
11815                dumpState.setDump(DumpState.DUMP_VERSION);
11816            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
11817                dumpState.setDump(DumpState.DUMP_KEYSETS);
11818            }
11819        }
11820
11821        if (checkin) {
11822            pw.println("vers,1");
11823        }
11824
11825        // reader
11826        synchronized (mPackages) {
11827            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
11828                if (!checkin) {
11829                    if (dumpState.onTitlePrinted())
11830                        pw.println();
11831                    pw.println("Database versions:");
11832                    pw.print("  SDK Version:");
11833                    pw.print(" internal=");
11834                    pw.print(mSettings.mInternalSdkPlatform);
11835                    pw.print(" external=");
11836                    pw.println(mSettings.mExternalSdkPlatform);
11837                    pw.print("  DB Version:");
11838                    pw.print(" internal=");
11839                    pw.print(mSettings.mInternalDatabaseVersion);
11840                    pw.print(" external=");
11841                    pw.println(mSettings.mExternalDatabaseVersion);
11842                }
11843            }
11844
11845            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
11846                if (!checkin) {
11847                    if (dumpState.onTitlePrinted())
11848                        pw.println();
11849                    pw.println("Verifiers:");
11850                    pw.print("  Required: ");
11851                    pw.print(mRequiredVerifierPackage);
11852                    pw.print(" (uid=");
11853                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
11854                    pw.println(")");
11855                } else if (mRequiredVerifierPackage != null) {
11856                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
11857                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
11858                }
11859            }
11860
11861            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
11862                boolean printedHeader = false;
11863                final Iterator<String> it = mSharedLibraries.keySet().iterator();
11864                while (it.hasNext()) {
11865                    String name = it.next();
11866                    SharedLibraryEntry ent = mSharedLibraries.get(name);
11867                    if (!checkin) {
11868                        if (!printedHeader) {
11869                            if (dumpState.onTitlePrinted())
11870                                pw.println();
11871                            pw.println("Libraries:");
11872                            printedHeader = true;
11873                        }
11874                        pw.print("  ");
11875                    } else {
11876                        pw.print("lib,");
11877                    }
11878                    pw.print(name);
11879                    if (!checkin) {
11880                        pw.print(" -> ");
11881                    }
11882                    if (ent.path != null) {
11883                        if (!checkin) {
11884                            pw.print("(jar) ");
11885                            pw.print(ent.path);
11886                        } else {
11887                            pw.print(",jar,");
11888                            pw.print(ent.path);
11889                        }
11890                    } else {
11891                        if (!checkin) {
11892                            pw.print("(apk) ");
11893                            pw.print(ent.apk);
11894                        } else {
11895                            pw.print(",apk,");
11896                            pw.print(ent.apk);
11897                        }
11898                    }
11899                    pw.println();
11900                }
11901            }
11902
11903            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
11904                if (dumpState.onTitlePrinted())
11905                    pw.println();
11906                if (!checkin) {
11907                    pw.println("Features:");
11908                }
11909                Iterator<String> it = mAvailableFeatures.keySet().iterator();
11910                while (it.hasNext()) {
11911                    String name = it.next();
11912                    if (!checkin) {
11913                        pw.print("  ");
11914                    } else {
11915                        pw.print("feat,");
11916                    }
11917                    pw.println(name);
11918                }
11919            }
11920
11921            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
11922                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
11923                        : "Activity Resolver Table:", "  ", packageName,
11924                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11925                    dumpState.setTitlePrinted(true);
11926                }
11927                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
11928                        : "Receiver Resolver Table:", "  ", packageName,
11929                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11930                    dumpState.setTitlePrinted(true);
11931                }
11932                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
11933                        : "Service Resolver Table:", "  ", packageName,
11934                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11935                    dumpState.setTitlePrinted(true);
11936                }
11937                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
11938                        : "Provider Resolver Table:", "  ", packageName,
11939                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
11940                    dumpState.setTitlePrinted(true);
11941                }
11942            }
11943
11944            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
11945                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11946                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11947                    int user = mSettings.mPreferredActivities.keyAt(i);
11948                    if (pir.dump(pw,
11949                            dumpState.getTitlePrinted()
11950                                ? "\nPreferred Activities User " + user + ":"
11951                                : "Preferred Activities User " + user + ":", "  ",
11952                            packageName, true)) {
11953                        dumpState.setTitlePrinted(true);
11954                    }
11955                }
11956            }
11957
11958            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
11959                pw.flush();
11960                FileOutputStream fout = new FileOutputStream(fd);
11961                BufferedOutputStream str = new BufferedOutputStream(fout);
11962                XmlSerializer serializer = new FastXmlSerializer();
11963                try {
11964                    serializer.setOutput(str, "utf-8");
11965                    serializer.startDocument(null, true);
11966                    serializer.setFeature(
11967                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
11968                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
11969                    serializer.endDocument();
11970                    serializer.flush();
11971                } catch (IllegalArgumentException e) {
11972                    pw.println("Failed writing: " + e);
11973                } catch (IllegalStateException e) {
11974                    pw.println("Failed writing: " + e);
11975                } catch (IOException e) {
11976                    pw.println("Failed writing: " + e);
11977                }
11978            }
11979
11980            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
11981                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
11982            }
11983
11984            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
11985                boolean printedSomething = false;
11986                for (PackageParser.Provider p : mProviders.mProviders.values()) {
11987                    if (packageName != null && !packageName.equals(p.info.packageName)) {
11988                        continue;
11989                    }
11990                    if (!printedSomething) {
11991                        if (dumpState.onTitlePrinted())
11992                            pw.println();
11993                        pw.println("Registered ContentProviders:");
11994                        printedSomething = true;
11995                    }
11996                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
11997                    pw.print("    "); pw.println(p.toString());
11998                }
11999                printedSomething = false;
12000                for (Map.Entry<String, PackageParser.Provider> entry :
12001                        mProvidersByAuthority.entrySet()) {
12002                    PackageParser.Provider p = entry.getValue();
12003                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12004                        continue;
12005                    }
12006                    if (!printedSomething) {
12007                        if (dumpState.onTitlePrinted())
12008                            pw.println();
12009                        pw.println("ContentProvider Authorities:");
12010                        printedSomething = true;
12011                    }
12012                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12013                    pw.print("    "); pw.println(p.toString());
12014                    if (p.info != null && p.info.applicationInfo != null) {
12015                        final String appInfo = p.info.applicationInfo.toString();
12016                        pw.print("      applicationInfo="); pw.println(appInfo);
12017                    }
12018                }
12019            }
12020
12021            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12022                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
12023            }
12024
12025            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12026                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12027            }
12028
12029            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12030                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12031            }
12032
12033            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12034                if (dumpState.onTitlePrinted())
12035                    pw.println();
12036                mSettings.dumpReadMessagesLPr(pw, dumpState);
12037
12038                pw.println();
12039                pw.println("Package warning messages:");
12040                final File fname = getSettingsProblemFile();
12041                FileInputStream in = null;
12042                try {
12043                    in = new FileInputStream(fname);
12044                    final int avail = in.available();
12045                    final byte[] data = new byte[avail];
12046                    in.read(data);
12047                    pw.print(new String(data));
12048                } catch (FileNotFoundException e) {
12049                } catch (IOException e) {
12050                } finally {
12051                    if (in != null) {
12052                        try {
12053                            in.close();
12054                        } catch (IOException e) {
12055                        }
12056                    }
12057                }
12058            }
12059        }
12060    }
12061
12062    // ------- apps on sdcard specific code -------
12063    static final boolean DEBUG_SD_INSTALL = false;
12064
12065    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12066
12067    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12068
12069    private boolean mMediaMounted = false;
12070
12071    private String getEncryptKey() {
12072        try {
12073            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12074                    SD_ENCRYPTION_KEYSTORE_NAME);
12075            if (sdEncKey == null) {
12076                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12077                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12078                if (sdEncKey == null) {
12079                    Slog.e(TAG, "Failed to create encryption keys");
12080                    return null;
12081                }
12082            }
12083            return sdEncKey;
12084        } catch (NoSuchAlgorithmException nsae) {
12085            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12086            return null;
12087        } catch (IOException ioe) {
12088            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12089            return null;
12090        }
12091
12092    }
12093
12094    /* package */static String getTempContainerId() {
12095        int tmpIdx = 1;
12096        String list[] = PackageHelper.getSecureContainerList();
12097        if (list != null) {
12098            for (final String name : list) {
12099                // Ignore null and non-temporary container entries
12100                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12101                    continue;
12102                }
12103
12104                String subStr = name.substring(mTempContainerPrefix.length());
12105                try {
12106                    int cid = Integer.parseInt(subStr);
12107                    if (cid >= tmpIdx) {
12108                        tmpIdx = cid + 1;
12109                    }
12110                } catch (NumberFormatException e) {
12111                }
12112            }
12113        }
12114        return mTempContainerPrefix + tmpIdx;
12115    }
12116
12117    /*
12118     * Update media status on PackageManager.
12119     */
12120    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12121        int callingUid = Binder.getCallingUid();
12122        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12123            throw new SecurityException("Media status can only be updated by the system");
12124        }
12125        // reader; this apparently protects mMediaMounted, but should probably
12126        // be a different lock in that case.
12127        synchronized (mPackages) {
12128            Log.i(TAG, "Updating external media status from "
12129                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12130                    + (mediaStatus ? "mounted" : "unmounted"));
12131            if (DEBUG_SD_INSTALL)
12132                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12133                        + ", mMediaMounted=" + mMediaMounted);
12134            if (mediaStatus == mMediaMounted) {
12135                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12136                        : 0, -1);
12137                mHandler.sendMessage(msg);
12138                return;
12139            }
12140            mMediaMounted = mediaStatus;
12141        }
12142        // Queue up an async operation since the package installation may take a
12143        // little while.
12144        mHandler.post(new Runnable() {
12145            public void run() {
12146                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12147            }
12148        });
12149    }
12150
12151    /**
12152     * Called by MountService when the initial ASECs to scan are available.
12153     * Should block until all the ASEC containers are finished being scanned.
12154     */
12155    public void scanAvailableAsecs() {
12156        updateExternalMediaStatusInner(true, false, false);
12157        if (mShouldRestoreconData) {
12158            SELinuxMMAC.setRestoreconDone();
12159            mShouldRestoreconData = false;
12160        }
12161    }
12162
12163    /*
12164     * Collect information of applications on external media, map them against
12165     * existing containers and update information based on current mount status.
12166     * Please note that we always have to report status if reportStatus has been
12167     * set to true especially when unloading packages.
12168     */
12169    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12170            boolean externalStorage) {
12171        // Collection of uids
12172        int uidArr[] = null;
12173        // Collection of stale containers
12174        HashSet<String> removeCids = new HashSet<String>();
12175        // Collection of packages on external media with valid containers.
12176        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12177        // Get list of secure containers.
12178        final String list[] = PackageHelper.getSecureContainerList();
12179        if (list == null || list.length == 0) {
12180            Log.i(TAG, "No secure containers on sdcard");
12181        } else {
12182            // Process list of secure containers and categorize them
12183            // as active or stale based on their package internal state.
12184            int uidList[] = new int[list.length];
12185            int num = 0;
12186            // reader
12187            synchronized (mPackages) {
12188                for (String cid : list) {
12189                    if (DEBUG_SD_INSTALL)
12190                        Log.i(TAG, "Processing container " + cid);
12191                    String pkgName = getAsecPackageName(cid);
12192                    if (pkgName == null) {
12193                        if (DEBUG_SD_INSTALL)
12194                            Log.i(TAG, "Container : " + cid + " stale");
12195                        removeCids.add(cid);
12196                        continue;
12197                    }
12198                    if (DEBUG_SD_INSTALL)
12199                        Log.i(TAG, "Looking for pkg : " + pkgName);
12200
12201                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12202                    if (ps == null) {
12203                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12204                        removeCids.add(cid);
12205                        continue;
12206                    }
12207
12208                    /*
12209                     * Skip packages that are not external if we're unmounting
12210                     * external storage.
12211                     */
12212                    if (externalStorage && !isMounted && !isExternal(ps)) {
12213                        continue;
12214                    }
12215
12216                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12217                            getAppInstructionSetFromSettings(ps),
12218                            isForwardLocked(ps));
12219                    // The package status is changed only if the code path
12220                    // matches between settings and the container id.
12221                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12222                        if (DEBUG_SD_INSTALL) {
12223                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12224                                    + " at code path: " + ps.codePathString);
12225                        }
12226
12227                        // We do have a valid package installed on sdcard
12228                        processCids.put(args, ps.codePathString);
12229                        final int uid = ps.appId;
12230                        if (uid != -1) {
12231                            uidList[num++] = uid;
12232                        }
12233                    } else {
12234                        Log.i(TAG, "Deleting stale container for " + cid);
12235                        removeCids.add(cid);
12236                    }
12237                }
12238            }
12239
12240            if (num > 0) {
12241                // Sort uid list
12242                Arrays.sort(uidList, 0, num);
12243                // Throw away duplicates
12244                uidArr = new int[num];
12245                uidArr[0] = uidList[0];
12246                int di = 0;
12247                for (int i = 1; i < num; i++) {
12248                    if (uidList[i - 1] != uidList[i]) {
12249                        uidArr[di++] = uidList[i];
12250                    }
12251                }
12252            }
12253        }
12254        // Process packages with valid entries.
12255        if (isMounted) {
12256            if (DEBUG_SD_INSTALL)
12257                Log.i(TAG, "Loading packages");
12258            loadMediaPackages(processCids, uidArr, removeCids);
12259            startCleaningPackages();
12260        } else {
12261            if (DEBUG_SD_INSTALL)
12262                Log.i(TAG, "Unloading packages");
12263            unloadMediaPackages(processCids, uidArr, reportStatus);
12264        }
12265    }
12266
12267   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12268           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12269        int size = pkgList.size();
12270        if (size > 0) {
12271            // Send broadcasts here
12272            Bundle extras = new Bundle();
12273            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12274                    .toArray(new String[size]));
12275            if (uidArr != null) {
12276                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12277            }
12278            if (replacing) {
12279                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12280            }
12281            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12282                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12283            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12284        }
12285    }
12286
12287   /*
12288     * Look at potentially valid container ids from processCids If package
12289     * information doesn't match the one on record or package scanning fails,
12290     * the cid is added to list of removeCids. We currently don't delete stale
12291     * containers.
12292     */
12293   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12294            HashSet<String> removeCids) {
12295        ArrayList<String> pkgList = new ArrayList<String>();
12296        Set<AsecInstallArgs> keys = processCids.keySet();
12297        boolean doGc = false;
12298        for (AsecInstallArgs args : keys) {
12299            String codePath = processCids.get(args);
12300            if (DEBUG_SD_INSTALL)
12301                Log.i(TAG, "Loading container : " + args.cid);
12302            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12303            try {
12304                // Make sure there are no container errors first.
12305                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12306                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12307                            + " when installing from sdcard");
12308                    continue;
12309                }
12310                // Check code path here.
12311                if (codePath == null || !codePath.equals(args.getCodePath())) {
12312                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12313                            + " does not match one in settings " + codePath);
12314                    continue;
12315                }
12316                // Parse package
12317                int parseFlags = mDefParseFlags;
12318                if (args.isExternal()) {
12319                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12320                }
12321                if (args.isFwdLocked()) {
12322                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12323                }
12324
12325                doGc = true;
12326                synchronized (mInstallLock) {
12327                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
12328                            0, 0, null);
12329                    // Scan the package
12330                    if (pkg != null) {
12331                        /*
12332                         * TODO why is the lock being held? doPostInstall is
12333                         * called in other places without the lock. This needs
12334                         * to be straightened out.
12335                         */
12336                        // writer
12337                        synchronized (mPackages) {
12338                            retCode = PackageManager.INSTALL_SUCCEEDED;
12339                            pkgList.add(pkg.packageName);
12340                            // Post process args
12341                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12342                                    pkg.applicationInfo.uid);
12343                        }
12344                    } else {
12345                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12346                    }
12347                }
12348
12349            } finally {
12350                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12351                    // Don't destroy container here. Wait till gc clears things
12352                    // up.
12353                    removeCids.add(args.cid);
12354                }
12355            }
12356        }
12357        // writer
12358        synchronized (mPackages) {
12359            // If the platform SDK has changed since the last time we booted,
12360            // we need to re-grant app permission to catch any new ones that
12361            // appear. This is really a hack, and means that apps can in some
12362            // cases get permissions that the user didn't initially explicitly
12363            // allow... it would be nice to have some better way to handle
12364            // this situation.
12365            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12366            if (regrantPermissions)
12367                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12368                        + mSdkVersion + "; regranting permissions for external storage");
12369            mSettings.mExternalSdkPlatform = mSdkVersion;
12370
12371            // Make sure group IDs have been assigned, and any permission
12372            // changes in other apps are accounted for
12373            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12374                    | (regrantPermissions
12375                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12376                            : 0));
12377
12378            mSettings.updateExternalDatabaseVersion();
12379
12380            // can downgrade to reader
12381            // Persist settings
12382            mSettings.writeLPr();
12383        }
12384        // Send a broadcast to let everyone know we are done processing
12385        if (pkgList.size() > 0) {
12386            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12387        }
12388        // Force gc to avoid any stale parser references that we might have.
12389        if (doGc) {
12390            Runtime.getRuntime().gc();
12391        }
12392        // List stale containers and destroy stale temporary containers.
12393        if (removeCids != null) {
12394            for (String cid : removeCids) {
12395                if (cid.startsWith(mTempContainerPrefix)) {
12396                    Log.i(TAG, "Destroying stale temporary container " + cid);
12397                    PackageHelper.destroySdDir(cid);
12398                } else {
12399                    Log.w(TAG, "Container " + cid + " is stale");
12400               }
12401           }
12402        }
12403    }
12404
12405   /*
12406     * Utility method to unload a list of specified containers
12407     */
12408    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12409        // Just unmount all valid containers.
12410        for (AsecInstallArgs arg : cidArgs) {
12411            synchronized (mInstallLock) {
12412                arg.doPostDeleteLI(false);
12413           }
12414       }
12415   }
12416
12417    /*
12418     * Unload packages mounted on external media. This involves deleting package
12419     * data from internal structures, sending broadcasts about diabled packages,
12420     * gc'ing to free up references, unmounting all secure containers
12421     * corresponding to packages on external media, and posting a
12422     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12423     * that we always have to post this message if status has been requested no
12424     * matter what.
12425     */
12426    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12427            final boolean reportStatus) {
12428        if (DEBUG_SD_INSTALL)
12429            Log.i(TAG, "unloading media packages");
12430        ArrayList<String> pkgList = new ArrayList<String>();
12431        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12432        final Set<AsecInstallArgs> keys = processCids.keySet();
12433        for (AsecInstallArgs args : keys) {
12434            String pkgName = args.getPackageName();
12435            if (DEBUG_SD_INSTALL)
12436                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12437            // Delete package internally
12438            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12439            synchronized (mInstallLock) {
12440                boolean res = deletePackageLI(pkgName, null, false, null, null,
12441                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12442                if (res) {
12443                    pkgList.add(pkgName);
12444                } else {
12445                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12446                    failedList.add(args);
12447                }
12448            }
12449        }
12450
12451        // reader
12452        synchronized (mPackages) {
12453            // We didn't update the settings after removing each package;
12454            // write them now for all packages.
12455            mSettings.writeLPr();
12456        }
12457
12458        // We have to absolutely send UPDATED_MEDIA_STATUS only
12459        // after confirming that all the receivers processed the ordered
12460        // broadcast when packages get disabled, force a gc to clean things up.
12461        // and unload all the containers.
12462        if (pkgList.size() > 0) {
12463            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12464                    new IIntentReceiver.Stub() {
12465                public void performReceive(Intent intent, int resultCode, String data,
12466                        Bundle extras, boolean ordered, boolean sticky,
12467                        int sendingUser) throws RemoteException {
12468                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12469                            reportStatus ? 1 : 0, 1, keys);
12470                    mHandler.sendMessage(msg);
12471                }
12472            });
12473        } else {
12474            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12475                    keys);
12476            mHandler.sendMessage(msg);
12477        }
12478    }
12479
12480    /** Binder call */
12481    @Override
12482    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12483            final int flags) {
12484        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12485        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12486        int returnCode = PackageManager.MOVE_SUCCEEDED;
12487        int currFlags = 0;
12488        int newFlags = 0;
12489        // reader
12490        synchronized (mPackages) {
12491            PackageParser.Package pkg = mPackages.get(packageName);
12492            if (pkg == null) {
12493                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12494            } else {
12495                // Disable moving fwd locked apps and system packages
12496                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12497                    Slog.w(TAG, "Cannot move system application");
12498                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12499                } else if (pkg.mOperationPending) {
12500                    Slog.w(TAG, "Attempt to move package which has pending operations");
12501                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12502                } else {
12503                    // Find install location first
12504                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12505                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12506                        Slog.w(TAG, "Ambigous flags specified for move location.");
12507                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12508                    } else {
12509                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12510                                : PackageManager.INSTALL_INTERNAL;
12511                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12512                                : PackageManager.INSTALL_INTERNAL;
12513
12514                        if (newFlags == currFlags) {
12515                            Slog.w(TAG, "No move required. Trying to move to same location");
12516                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12517                        } else {
12518                            if (isForwardLocked(pkg)) {
12519                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12520                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12521                            }
12522                        }
12523                    }
12524                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12525                        pkg.mOperationPending = true;
12526                    }
12527                }
12528            }
12529
12530            /*
12531             * TODO this next block probably shouldn't be inside the lock. We
12532             * can't guarantee these won't change after this is fired off
12533             * anyway.
12534             */
12535            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12536                processPendingMove(new MoveParams(null, observer, 0, packageName, null,
12537                        null, -1, user),
12538                        returnCode);
12539            } else {
12540                Message msg = mHandler.obtainMessage(INIT_COPY);
12541                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
12542                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
12543                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir,
12544                        instructionSet);
12545                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12546                        pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user);
12547                msg.obj = mp;
12548                mHandler.sendMessage(msg);
12549            }
12550        }
12551    }
12552
12553    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12554        // Queue up an async operation since the package deletion may take a
12555        // little while.
12556        mHandler.post(new Runnable() {
12557            public void run() {
12558                // TODO fix this; this does nothing.
12559                mHandler.removeCallbacks(this);
12560                int returnCode = currentStatus;
12561                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12562                    int uidArr[] = null;
12563                    ArrayList<String> pkgList = null;
12564                    synchronized (mPackages) {
12565                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12566                        if (pkg == null) {
12567                            Slog.w(TAG, " Package " + mp.packageName
12568                                    + " doesn't exist. Aborting move");
12569                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12570                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
12571                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12572                                    + mp.srcArgs.getCodePath() + " to "
12573                                    + pkg.applicationInfo.sourceDir
12574                                    + " Aborting move and returning error");
12575                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12576                        } else {
12577                            uidArr = new int[] {
12578                                pkg.applicationInfo.uid
12579                            };
12580                            pkgList = new ArrayList<String>();
12581                            pkgList.add(mp.packageName);
12582                        }
12583                    }
12584                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12585                        // Send resources unavailable broadcast
12586                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12587                        // Update package code and resource paths
12588                        synchronized (mInstallLock) {
12589                            synchronized (mPackages) {
12590                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12591                                // Recheck for package again.
12592                                if (pkg == null) {
12593                                    Slog.w(TAG, " Package " + mp.packageName
12594                                            + " doesn't exist. Aborting move");
12595                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12596                                } else if (!mp.srcArgs.getCodePath().equals(
12597                                        pkg.applicationInfo.sourceDir)) {
12598                                    Slog.w(TAG, "Package " + mp.packageName
12599                                            + " code path changed from " + mp.srcArgs.getCodePath()
12600                                            + " to " + pkg.applicationInfo.sourceDir
12601                                            + " Aborting move and returning error");
12602                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12603                                } else {
12604                                    final String oldCodePath = pkg.mPath;
12605                                    final String newCodePath = mp.targetArgs.getCodePath();
12606                                    final String newResPath = mp.targetArgs.getResourcePath();
12607                                    final String newNativePath = mp.targetArgs
12608                                            .getNativeLibraryPath();
12609
12610                                    final File newNativeDir = new File(newNativePath);
12611
12612                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12613                                        // NOTE: We do not report any errors from the APK scan and library
12614                                        // copy at this point.
12615                                        NativeLibraryHelper.ApkHandle handle =
12616                                                new NativeLibraryHelper.ApkHandle(newCodePath);
12617                                        final int abi = NativeLibraryHelper.findSupportedAbi(
12618                                                handle, Build.SUPPORTED_ABIS);
12619                                        if (abi >= 0) {
12620                                            NativeLibraryHelper.copyNativeBinariesIfNeededLI(
12621                                                    handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
12622                                        }
12623                                        handle.close();
12624                                    }
12625                                    final int[] users = sUserManager.getUserIds();
12626                                    for (int user : users) {
12627                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
12628                                                newNativePath, user) < 0) {
12629                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12630                                        }
12631                                    }
12632
12633                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12634                                        pkg.mPath = newCodePath;
12635                                        // Move dex files around
12636                                        if (moveDexFilesLI(pkg) != PackageManager.INSTALL_SUCCEEDED) {
12637                                            // Moving of dex files failed. Set
12638                                            // error code and abort move.
12639                                            pkg.mPath = pkg.mScanPath;
12640                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12641                                        }
12642                                    }
12643
12644                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12645                                        pkg.mScanPath = newCodePath;
12646                                        pkg.applicationInfo.sourceDir = newCodePath;
12647                                        pkg.applicationInfo.publicSourceDir = newResPath;
12648                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
12649                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
12650                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
12651                                        ps.codePathString = ps.codePath.getPath();
12652                                        ps.resourcePath = new File(
12653                                                pkg.applicationInfo.publicSourceDir);
12654                                        ps.resourcePathString = ps.resourcePath.getPath();
12655                                        ps.nativeLibraryPathString = newNativePath;
12656                                        // Set the application info flag
12657                                        // correctly.
12658                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
12659                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12660                                        } else {
12661                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12662                                        }
12663                                        ps.setFlags(pkg.applicationInfo.flags);
12664                                        mAppDirs.remove(oldCodePath);
12665                                        mAppDirs.put(newCodePath, pkg);
12666                                        // Persist settings
12667                                        mSettings.writeLPr();
12668                                    }
12669                                }
12670                            }
12671                        }
12672                        // Send resources available broadcast
12673                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12674                    }
12675                }
12676                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12677                    // Clean up failed installation
12678                    if (mp.targetArgs != null) {
12679                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
12680                                -1);
12681                    }
12682                } else {
12683                    // Force a gc to clear things up.
12684                    Runtime.getRuntime().gc();
12685                    // Delete older code
12686                    synchronized (mInstallLock) {
12687                        mp.srcArgs.doPostDeleteLI(true);
12688                    }
12689                }
12690
12691                // Allow more operations on this file if we didn't fail because
12692                // an operation was already pending for this package.
12693                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
12694                    synchronized (mPackages) {
12695                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12696                        if (pkg != null) {
12697                            pkg.mOperationPending = false;
12698                       }
12699                   }
12700                }
12701
12702                IPackageMoveObserver observer = mp.observer;
12703                if (observer != null) {
12704                    try {
12705                        observer.packageMoved(mp.packageName, returnCode);
12706                    } catch (RemoteException e) {
12707                        Log.i(TAG, "Observer no longer exists.");
12708                    }
12709                }
12710            }
12711        });
12712    }
12713
12714    public boolean setInstallLocation(int loc) {
12715        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12716                null);
12717        if (getInstallLocation() == loc) {
12718            return true;
12719        }
12720        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12721                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12722            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12723                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12724            return true;
12725        }
12726        return false;
12727   }
12728
12729    public int getInstallLocation() {
12730        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12731                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12732                PackageHelper.APP_INSTALL_AUTO);
12733    }
12734
12735    /** Called by UserManagerService */
12736    void cleanUpUserLILPw(int userHandle) {
12737        mDirtyUsers.remove(userHandle);
12738        mSettings.removeUserLPr(userHandle);
12739        mPendingBroadcasts.remove(userHandle);
12740        if (mInstaller != null) {
12741            // Technically, we shouldn't be doing this with the package lock
12742            // held.  However, this is very rare, and there is already so much
12743            // other disk I/O going on, that we'll let it slide for now.
12744            mInstaller.removeUserDataDirs(userHandle);
12745        }
12746    }
12747
12748    /** Called by UserManagerService */
12749    void createNewUserLILPw(int userHandle, File path) {
12750        if (mInstaller != null) {
12751            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
12752        }
12753    }
12754
12755    @Override
12756    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
12757        mContext.enforceCallingOrSelfPermission(
12758                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
12759                "Only package verification agents can read the verifier device identity");
12760
12761        synchronized (mPackages) {
12762            return mSettings.getVerifierDeviceIdentityLPw();
12763        }
12764    }
12765
12766    @Override
12767    public void setPermissionEnforced(String permission, boolean enforced) {
12768        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
12769        if (READ_EXTERNAL_STORAGE.equals(permission)) {
12770            synchronized (mPackages) {
12771                if (mSettings.mReadExternalStorageEnforced == null
12772                        || mSettings.mReadExternalStorageEnforced != enforced) {
12773                    mSettings.mReadExternalStorageEnforced = enforced;
12774                    mSettings.writeLPr();
12775                }
12776            }
12777            // kill any non-foreground processes so we restart them and
12778            // grant/revoke the GID.
12779            final IActivityManager am = ActivityManagerNative.getDefault();
12780            if (am != null) {
12781                final long token = Binder.clearCallingIdentity();
12782                try {
12783                    am.killProcessesBelowForeground("setPermissionEnforcement");
12784                } catch (RemoteException e) {
12785                } finally {
12786                    Binder.restoreCallingIdentity(token);
12787                }
12788            }
12789        } else {
12790            throw new IllegalArgumentException("No selective enforcement for " + permission);
12791        }
12792    }
12793
12794    @Override
12795    @Deprecated
12796    public boolean isPermissionEnforced(String permission) {
12797        return true;
12798    }
12799
12800    @Override
12801    public boolean isStorageLow() {
12802        final long token = Binder.clearCallingIdentity();
12803        try {
12804            final DeviceStorageMonitorInternal
12805                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
12806            if (dsm != null) {
12807                return dsm.isMemoryLow();
12808            } else {
12809                return false;
12810            }
12811        } finally {
12812            Binder.restoreCallingIdentity(token);
12813        }
12814    }
12815}
12816