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