PackageManagerService.java revision 032f2b246bd01653c592f2b148d6a0debfe164b2
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.Manifest.permission.INSTALL_PACKAGES;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
27import static android.os.Process.PACKAGE_INFO_GID;
28import static android.os.Process.SYSTEM_UID;
29import static android.system.OsConstants.S_IRGRP;
30import static android.system.OsConstants.S_IROTH;
31import static android.system.OsConstants.S_IRWXU;
32import static android.system.OsConstants.S_IXGRP;
33import static android.system.OsConstants.S_IXOTH;
34import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
35import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
36import static com.android.internal.util.ArrayUtils.appendInt;
37import static com.android.internal.util.ArrayUtils.removeInt;
38
39import com.android.internal.R;
40import com.android.internal.app.IMediaContainerService;
41import com.android.internal.app.ResolverActivity;
42import com.android.internal.content.NativeLibraryHelper;
43import com.android.internal.content.NativeLibraryHelper.ApkHandle;
44import com.android.internal.content.PackageHelper;
45import com.android.internal.util.ArrayUtils;
46import com.android.internal.util.FastPrintWriter;
47import com.android.internal.util.FastXmlSerializer;
48import com.android.internal.util.XmlUtils;
49import com.android.server.EventLogTags;
50import com.android.server.IntentResolver;
51import com.android.server.LocalServices;
52import com.android.server.ServiceThread;
53import com.android.server.Watchdog;
54import com.android.server.pm.Settings.DatabaseVersion;
55import com.android.server.storage.DeviceStorageMonitorInternal;
56import com.android.server.storage.DeviceStorageMonitorInternal;
57
58import org.xmlpull.v1.XmlPullParser;
59import org.xmlpull.v1.XmlPullParserException;
60import org.xmlpull.v1.XmlSerializer;
61
62import android.app.ActivityManager;
63import android.app.ActivityManagerNative;
64import android.app.IActivityManager;
65import android.app.PackageInstallObserver;
66import android.app.admin.IDevicePolicyManager;
67import android.app.backup.IBackupManager;
68import android.content.BroadcastReceiver;
69import android.content.ComponentName;
70import android.content.Context;
71import android.content.IIntentReceiver;
72import android.content.Intent;
73import android.content.IntentFilter;
74import android.content.IntentSender;
75import android.content.IntentSender.SendIntentException;
76import android.content.ServiceConnection;
77import android.content.pm.ActivityInfo;
78import android.content.pm.ApplicationInfo;
79import android.content.pm.ContainerEncryptionParams;
80import android.content.pm.FeatureInfo;
81import android.content.pm.IPackageDataObserver;
82import android.content.pm.IPackageDeleteObserver;
83import android.content.pm.IPackageInstallObserver;
84import android.content.pm.IPackageInstallObserver2;
85import android.content.pm.IPackageInstaller;
86import android.content.pm.IPackageManager;
87import android.content.pm.IPackageMoveObserver;
88import android.content.pm.IPackageStatsObserver;
89import android.content.pm.InstrumentationInfo;
90import android.content.pm.ManifestDigest;
91import android.content.pm.PackageCleanItem;
92import android.content.pm.PackageInfo;
93import android.content.pm.PackageInfoLite;
94import android.content.pm.PackageInstallerParams;
95import android.content.pm.PackageManager;
96import android.content.pm.PackageParser.ActivityIntentInfo;
97import android.content.pm.PackageParser.PackageParserException;
98import android.content.pm.PackageParser;
99import android.content.pm.PackageStats;
100import android.content.pm.PackageUserState;
101import android.content.pm.ParceledListSlice;
102import android.content.pm.PermissionGroupInfo;
103import android.content.pm.PermissionInfo;
104import android.content.pm.ProviderInfo;
105import android.content.pm.ResolveInfo;
106import android.content.pm.ServiceInfo;
107import android.content.pm.Signature;
108import android.content.pm.VerificationParams;
109import android.content.pm.VerifierDeviceIdentity;
110import android.content.pm.VerifierInfo;
111import android.content.res.Resources;
112import android.hardware.display.DisplayManager;
113import android.net.Uri;
114import android.os.Binder;
115import android.os.Build;
116import android.os.Bundle;
117import android.os.Environment;
118import android.os.Environment.UserEnvironment;
119import android.os.FileObserver;
120import android.os.FileUtils;
121import android.os.Handler;
122import android.os.IBinder;
123import android.os.Looper;
124import android.os.Message;
125import android.os.Parcel;
126import android.os.ParcelFileDescriptor;
127import android.os.Process;
128import android.os.RemoteException;
129import android.os.SELinux;
130import android.os.ServiceManager;
131import android.os.SystemClock;
132import android.os.SystemProperties;
133import android.os.UserHandle;
134import android.os.UserManager;
135import android.security.KeyStore;
136import android.security.SystemKeyStore;
137import android.system.ErrnoException;
138import android.system.Os;
139import android.system.StructStat;
140import android.text.TextUtils;
141import android.util.ArraySet;
142import android.util.AtomicFile;
143import android.util.DisplayMetrics;
144import android.util.EventLog;
145import android.util.Log;
146import android.util.LogPrinter;
147import android.util.PrintStreamPrinter;
148import android.util.Slog;
149import android.util.SparseArray;
150import android.util.Xml;
151import android.view.Display;
152
153import java.io.BufferedInputStream;
154import java.io.BufferedOutputStream;
155import java.io.File;
156import java.io.FileDescriptor;
157import java.io.FileInputStream;
158import java.io.FileNotFoundException;
159import java.io.FileOutputStream;
160import java.io.FileReader;
161import java.io.FilenameFilter;
162import java.io.IOException;
163import java.io.InputStream;
164import java.io.PrintWriter;
165import java.nio.charset.StandardCharsets;
166import java.security.NoSuchAlgorithmException;
167import java.security.PublicKey;
168import java.security.cert.CertificateEncodingException;
169import java.security.cert.CertificateException;
170import java.text.SimpleDateFormat;
171import java.util.ArrayList;
172import java.util.Arrays;
173import java.util.Collection;
174import java.util.Collections;
175import java.util.Comparator;
176import java.util.Date;
177import java.util.HashMap;
178import java.util.HashSet;
179import java.util.Iterator;
180import java.util.List;
181import java.util.Map;
182import java.util.Set;
183import java.util.concurrent.atomic.AtomicBoolean;
184import java.util.concurrent.atomic.AtomicLong;
185
186import dalvik.system.DexFile;
187import dalvik.system.StaleDexCacheError;
188import dalvik.system.VMRuntime;
189
190import libcore.io.IoUtils;
191
192/**
193 * Keep track of all those .apks everywhere.
194 *
195 * This is very central to the platform's security; please run the unit
196 * tests whenever making modifications here:
197 *
198mmm frameworks/base/tests/AndroidTests
199adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
200adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
201 *
202 * {@hide}
203 */
204public class PackageManagerService extends IPackageManager.Stub {
205    static final String TAG = "PackageManager";
206    static final boolean DEBUG_SETTINGS = false;
207    static final boolean DEBUG_PREFERRED = false;
208    static final boolean DEBUG_UPGRADE = false;
209    private static final boolean DEBUG_INSTALL = false;
210    private static final boolean DEBUG_REMOVE = false;
211    private static final boolean DEBUG_BROADCASTS = false;
212    private static final boolean DEBUG_SHOW_INFO = false;
213    private static final boolean DEBUG_PACKAGE_INFO = false;
214    private static final boolean DEBUG_INTENT_MATCHING = false;
215    private static final boolean DEBUG_PACKAGE_SCANNING = false;
216    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
217    private static final boolean DEBUG_VERIFY = false;
218    private static final boolean DEBUG_DEXOPT = false;
219
220    private static final int RADIO_UID = Process.PHONE_UID;
221    private static final int LOG_UID = Process.LOG_UID;
222    private static final int NFC_UID = Process.NFC_UID;
223    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
224    private static final int SHELL_UID = Process.SHELL_UID;
225
226    // Cap the size of permission trees that 3rd party apps can define
227    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
228
229    private static final int REMOVE_EVENTS =
230        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
231    private static final int ADD_EVENTS =
232        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
233
234    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
235    // Suffix used during package installation when copying/moving
236    // package apks to install directory.
237    private static final String INSTALL_PACKAGE_SUFFIX = "-";
238
239    static final int SCAN_MONITOR = 1<<0;
240    static final int SCAN_NO_DEX = 1<<1;
241    static final int SCAN_FORCE_DEX = 1<<2;
242    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
243    static final int SCAN_NEW_INSTALL = 1<<4;
244    static final int SCAN_NO_PATHS = 1<<5;
245    static final int SCAN_UPDATE_TIME = 1<<6;
246    static final int SCAN_DEFER_DEX = 1<<7;
247    static final int SCAN_BOOTING = 1<<8;
248    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
249    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
250
251    static final int REMOVE_CHATTY = 1<<16;
252
253    /**
254     * Timeout (in milliseconds) after which the watchdog should declare that
255     * our handler thread is wedged.  The usual default for such things is one
256     * minute but we sometimes do very lengthy I/O operations on this thread,
257     * such as installing multi-gigabyte applications, so ours needs to be longer.
258     */
259    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
260
261    /**
262     * Whether verification is enabled by default.
263     */
264    private static final boolean DEFAULT_VERIFY_ENABLE = true;
265
266    /**
267     * The default maximum time to wait for the verification agent to return in
268     * milliseconds.
269     */
270    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
271
272    /**
273     * The default response for package verification timeout.
274     *
275     * This can be either PackageManager.VERIFICATION_ALLOW or
276     * PackageManager.VERIFICATION_REJECT.
277     */
278    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
279
280    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
281
282    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
283            DEFAULT_CONTAINER_PACKAGE,
284            "com.android.defcontainer.DefaultContainerService");
285
286    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
287
288    private static final String LIB_DIR_NAME = "lib";
289    private static final String LIB64_DIR_NAME = "lib64";
290
291    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
292
293    static final String mTempContainerPrefix = "smdl2tmp";
294
295    private static String sPreferredInstructionSet;
296
297    final ServiceThread mHandlerThread;
298
299    private static final String IDMAP_PREFIX = "/data/resource-cache/";
300    private static final String IDMAP_SUFFIX = "@idmap";
301
302    final PackageHandler mHandler;
303
304    final int mSdkVersion = Build.VERSION.SDK_INT;
305
306    final Context mContext;
307    final boolean mFactoryTest;
308    final boolean mOnlyCore;
309    final DisplayMetrics mMetrics;
310    final int mDefParseFlags;
311    final String[] mSeparateProcesses;
312
313    // This is where all application persistent data goes.
314    final File mAppDataDir;
315
316    // This is where all application persistent data goes for secondary users.
317    final File mUserAppDataDir;
318
319    /** The location for ASEC container files on internal storage. */
320    final String mAsecInternalPath;
321
322    // This is the object monitoring the framework dir.
323    final FileObserver mFrameworkInstallObserver;
324
325    // This is the object monitoring the system app dir.
326    final FileObserver mSystemInstallObserver;
327
328    // This is the object monitoring the privileged system app dir.
329    final FileObserver mPrivilegedInstallObserver;
330
331    // This is the object monitoring the vendor app dir.
332    final FileObserver mVendorInstallObserver;
333
334    // This is the object monitoring the vendor overlay package dir.
335    final FileObserver mVendorOverlayInstallObserver;
336
337    // This is the object monitoring the OEM app dir.
338    final FileObserver mOemInstallObserver;
339
340    // This is the object monitoring mAppInstallDir.
341    final FileObserver mAppInstallObserver;
342
343    // This is the object monitoring mDrmAppPrivateInstallDir.
344    final FileObserver mDrmAppInstallObserver;
345
346    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
347    // LOCK HELD.  Can be called with mInstallLock held.
348    final Installer mInstaller;
349
350    final File mAppInstallDir;
351
352    /**
353     * Directory to which applications installed internally have native
354     * libraries copied.
355     */
356    private File mAppLibInstallDir;
357
358    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
359    // apps.
360    final File mDrmAppPrivateInstallDir;
361
362    final File mAppStagingDir;
363
364    // ----------------------------------------------------------------
365
366    // Lock for state used when installing and doing other long running
367    // operations.  Methods that must be called with this lock held have
368    // the suffix "LI".
369    final Object mInstallLock = new Object();
370
371    // These are the directories in the 3rd party applications installed dir
372    // that we have currently loaded packages from.  Keys are the application's
373    // installed zip file (absolute codePath), and values are Package.
374    final HashMap<String, PackageParser.Package> mAppDirs =
375            new HashMap<String, PackageParser.Package>();
376
377    // Information for the parser to write more useful error messages.
378    int mLastScanError;
379
380    // ----------------------------------------------------------------
381
382    // Keys are String (package name), values are Package.  This also serves
383    // as the lock for the global state.  Methods that must be called with
384    // this lock held have the prefix "LP".
385    final HashMap<String, PackageParser.Package> mPackages =
386            new HashMap<String, PackageParser.Package>();
387
388    // Tracks available target package names -> overlay package paths.
389    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
390        new HashMap<String, HashMap<String, PackageParser.Package>>();
391
392    final Settings mSettings;
393    boolean mRestoredSettings;
394
395    // Group-ids that are given to all packages as read from etc/permissions/*.xml.
396    int[] mGlobalGids;
397
398    // These are the built-in uid -> permission mappings that were read from the
399    // etc/permissions.xml file.
400    final SparseArray<HashSet<String>> mSystemPermissions =
401            new SparseArray<HashSet<String>>();
402
403    static final class SharedLibraryEntry {
404        final String path;
405        final String apk;
406
407        SharedLibraryEntry(String _path, String _apk) {
408            path = _path;
409            apk = _apk;
410        }
411    }
412
413    // These are the built-in shared libraries that were read from the
414    // etc/permissions.xml file.
415    final HashMap<String, SharedLibraryEntry> mSharedLibraries
416            = new HashMap<String, SharedLibraryEntry>();
417
418    // These are the features this devices supports that were read from the
419    // etc/permissions.xml file.
420    final HashMap<String, FeatureInfo> mAvailableFeatures =
421            new HashMap<String, FeatureInfo>();
422
423    // If mac_permissions.xml was found for seinfo labeling.
424    boolean mFoundPolicyFile;
425
426    // If a recursive restorecon of /data/data/<pkg> is needed.
427    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
428
429    // All available activities, for your resolving pleasure.
430    final ActivityIntentResolver mActivities =
431            new ActivityIntentResolver();
432
433    // All available receivers, for your resolving pleasure.
434    final ActivityIntentResolver mReceivers =
435            new ActivityIntentResolver();
436
437    // All available services, for your resolving pleasure.
438    final ServiceIntentResolver mServices = new ServiceIntentResolver();
439
440    // All available providers, for your resolving pleasure.
441    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
442
443    // Mapping from provider base names (first directory in content URI codePath)
444    // to the provider information.
445    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
446            new HashMap<String, PackageParser.Provider>();
447
448    // Mapping from instrumentation class names to info about them.
449    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
450            new HashMap<ComponentName, PackageParser.Instrumentation>();
451
452    // Mapping from permission names to info about them.
453    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
454            new HashMap<String, PackageParser.PermissionGroup>();
455
456    // Packages whose data we have transfered into another package, thus
457    // should no longer exist.
458    final HashSet<String> mTransferedPackages = new HashSet<String>();
459
460    // Broadcast actions that are only available to the system.
461    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
462
463    /** List of packages waiting for verification. */
464    final SparseArray<PackageVerificationState> mPendingVerification
465            = new SparseArray<PackageVerificationState>();
466
467    final PackageInstallerService mInstallerService;
468
469    HashSet<PackageParser.Package> mDeferredDexOpt = null;
470
471    /** Token for keys in mPendingVerification. */
472    private int mPendingVerificationToken = 0;
473
474    boolean mSystemReady;
475    boolean mSafeMode;
476    boolean mHasSystemUidErrors;
477
478    ApplicationInfo mAndroidApplication;
479    final ActivityInfo mResolveActivity = new ActivityInfo();
480    final ResolveInfo mResolveInfo = new ResolveInfo();
481    ComponentName mResolveComponentName;
482    PackageParser.Package mPlatformPackage;
483    ComponentName mCustomResolverComponentName;
484
485    boolean mResolverReplaced = false;
486
487    // Set of pending broadcasts for aggregating enable/disable of components.
488    static class PendingPackageBroadcasts {
489        // for each user id, a map of <package name -> components within that package>
490        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
491
492        public PendingPackageBroadcasts() {
493            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
494        }
495
496        public ArrayList<String> get(int userId, String packageName) {
497            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
498            return packages.get(packageName);
499        }
500
501        public void put(int userId, String packageName, ArrayList<String> components) {
502            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
503            packages.put(packageName, components);
504        }
505
506        public void remove(int userId, String packageName) {
507            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
508            if (packages != null) {
509                packages.remove(packageName);
510            }
511        }
512
513        public void remove(int userId) {
514            mUidMap.remove(userId);
515        }
516
517        public int userIdCount() {
518            return mUidMap.size();
519        }
520
521        public int userIdAt(int n) {
522            return mUidMap.keyAt(n);
523        }
524
525        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
526            return mUidMap.get(userId);
527        }
528
529        public int size() {
530            // total number of pending broadcast entries across all userIds
531            int num = 0;
532            for (int i = 0; i< mUidMap.size(); i++) {
533                num += mUidMap.valueAt(i).size();
534            }
535            return num;
536        }
537
538        public void clear() {
539            mUidMap.clear();
540        }
541
542        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
543            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
544            if (map == null) {
545                map = new HashMap<String, ArrayList<String>>();
546                mUidMap.put(userId, map);
547            }
548            return map;
549        }
550    }
551    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
552
553    // Service Connection to remote media container service to copy
554    // package uri's from external media onto secure containers
555    // or internal storage.
556    private IMediaContainerService mContainerService = null;
557
558    static final int SEND_PENDING_BROADCAST = 1;
559    static final int MCS_BOUND = 3;
560    static final int END_COPY = 4;
561    static final int INIT_COPY = 5;
562    static final int MCS_UNBIND = 6;
563    static final int START_CLEANING_PACKAGE = 7;
564    static final int FIND_INSTALL_LOC = 8;
565    static final int POST_INSTALL = 9;
566    static final int MCS_RECONNECT = 10;
567    static final int MCS_GIVE_UP = 11;
568    static final int UPDATED_MEDIA_STATUS = 12;
569    static final int WRITE_SETTINGS = 13;
570    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
571    static final int PACKAGE_VERIFIED = 15;
572    static final int CHECK_PENDING_VERIFICATION = 16;
573
574    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
575
576    // Delay time in millisecs
577    static final int BROADCAST_DELAY = 10 * 1000;
578
579    static UserManagerService sUserManager;
580
581    // Stores a list of users whose package restrictions file needs to be updated
582    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
583
584    final private DefaultContainerConnection mDefContainerConn =
585            new DefaultContainerConnection();
586    class DefaultContainerConnection implements ServiceConnection {
587        public void onServiceConnected(ComponentName name, IBinder service) {
588            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
589            IMediaContainerService imcs =
590                IMediaContainerService.Stub.asInterface(service);
591            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
592        }
593
594        public void onServiceDisconnected(ComponentName name) {
595            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
596        }
597    };
598
599    // Recordkeeping of restore-after-install operations that are currently in flight
600    // between the Package Manager and the Backup Manager
601    class PostInstallData {
602        public InstallArgs args;
603        public PackageInstalledInfo res;
604
605        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
606            args = _a;
607            res = _r;
608        }
609    };
610    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
611    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
612
613    private final String mRequiredVerifierPackage;
614
615    private final PackageUsage mPackageUsage = new PackageUsage();
616
617    private class PackageUsage {
618        private static final int WRITE_INTERVAL
619            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
620
621        private final Object mFileLock = new Object();
622        private final AtomicLong mLastWritten = new AtomicLong(0);
623        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
624
625        private boolean mIsFirstBoot = false;
626
627        boolean isFirstBoot() {
628            return mIsFirstBoot;
629        }
630
631        void write(boolean force) {
632            if (force) {
633                writeInternal();
634                return;
635            }
636            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
637                && !DEBUG_DEXOPT) {
638                return;
639            }
640            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
641                new Thread("PackageUsage_DiskWriter") {
642                    @Override
643                    public void run() {
644                        try {
645                            writeInternal();
646                        } finally {
647                            mBackgroundWriteRunning.set(false);
648                        }
649                    }
650                }.start();
651            }
652        }
653
654        private void writeInternal() {
655            synchronized (mPackages) {
656                synchronized (mFileLock) {
657                    AtomicFile file = getFile();
658                    FileOutputStream f = null;
659                    try {
660                        f = file.startWrite();
661                        BufferedOutputStream out = new BufferedOutputStream(f);
662                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
663                        StringBuilder sb = new StringBuilder();
664                        for (PackageParser.Package pkg : mPackages.values()) {
665                            if (pkg.mLastPackageUsageTimeInMills == 0) {
666                                continue;
667                            }
668                            sb.setLength(0);
669                            sb.append(pkg.packageName);
670                            sb.append(' ');
671                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
672                            sb.append('\n');
673                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
674                        }
675                        out.flush();
676                        file.finishWrite(f);
677                    } catch (IOException e) {
678                        if (f != null) {
679                            file.failWrite(f);
680                        }
681                        Log.e(TAG, "Failed to write package usage times", e);
682                    }
683                }
684            }
685            mLastWritten.set(SystemClock.elapsedRealtime());
686        }
687
688        void readLP() {
689            synchronized (mFileLock) {
690                AtomicFile file = getFile();
691                BufferedInputStream in = null;
692                try {
693                    in = new BufferedInputStream(file.openRead());
694                    StringBuffer sb = new StringBuffer();
695                    while (true) {
696                        String packageName = readToken(in, sb, ' ');
697                        if (packageName == null) {
698                            break;
699                        }
700                        String timeInMillisString = readToken(in, sb, '\n');
701                        if (timeInMillisString == null) {
702                            throw new IOException("Failed to find last usage time for package "
703                                                  + packageName);
704                        }
705                        PackageParser.Package pkg = mPackages.get(packageName);
706                        if (pkg == null) {
707                            continue;
708                        }
709                        long timeInMillis;
710                        try {
711                            timeInMillis = Long.parseLong(timeInMillisString.toString());
712                        } catch (NumberFormatException e) {
713                            throw new IOException("Failed to parse " + timeInMillisString
714                                                  + " as a long.", e);
715                        }
716                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
717                    }
718                } catch (FileNotFoundException expected) {
719                    mIsFirstBoot = true;
720                } catch (IOException e) {
721                    Log.w(TAG, "Failed to read package usage times", e);
722                } finally {
723                    IoUtils.closeQuietly(in);
724                }
725            }
726            mLastWritten.set(SystemClock.elapsedRealtime());
727        }
728
729        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
730                throws IOException {
731            sb.setLength(0);
732            while (true) {
733                int ch = in.read();
734                if (ch == -1) {
735                    if (sb.length() == 0) {
736                        return null;
737                    }
738                    throw new IOException("Unexpected EOF");
739                }
740                if (ch == endOfToken) {
741                    return sb.toString();
742                }
743                sb.append((char)ch);
744            }
745        }
746
747        private AtomicFile getFile() {
748            File dataDir = Environment.getDataDirectory();
749            File systemDir = new File(dataDir, "system");
750            File fname = new File(systemDir, "package-usage.list");
751            return new AtomicFile(fname);
752        }
753    }
754
755    class PackageHandler extends Handler {
756        private boolean mBound = false;
757        final ArrayList<HandlerParams> mPendingInstalls =
758            new ArrayList<HandlerParams>();
759
760        private boolean connectToService() {
761            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
762                    " DefaultContainerService");
763            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
764            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
765            if (mContext.bindServiceAsUser(service, mDefContainerConn,
766                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
767                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
768                mBound = true;
769                return true;
770            }
771            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
772            return false;
773        }
774
775        private void disconnectService() {
776            mContainerService = null;
777            mBound = false;
778            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
779            mContext.unbindService(mDefContainerConn);
780            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
781        }
782
783        PackageHandler(Looper looper) {
784            super(looper);
785        }
786
787        public void handleMessage(Message msg) {
788            try {
789                doHandleMessage(msg);
790            } finally {
791                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
792            }
793        }
794
795        void doHandleMessage(Message msg) {
796            switch (msg.what) {
797                case INIT_COPY: {
798                    HandlerParams params = (HandlerParams) msg.obj;
799                    int idx = mPendingInstalls.size();
800                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
801                    // If a bind was already initiated we dont really
802                    // need to do anything. The pending install
803                    // will be processed later on.
804                    if (!mBound) {
805                        // If this is the only one pending we might
806                        // have to bind to the service again.
807                        if (!connectToService()) {
808                            Slog.e(TAG, "Failed to bind to media container service");
809                            params.serviceError();
810                            return;
811                        } else {
812                            // Once we bind to the service, the first
813                            // pending request will be processed.
814                            mPendingInstalls.add(idx, params);
815                        }
816                    } else {
817                        mPendingInstalls.add(idx, params);
818                        // Already bound to the service. Just make
819                        // sure we trigger off processing the first request.
820                        if (idx == 0) {
821                            mHandler.sendEmptyMessage(MCS_BOUND);
822                        }
823                    }
824                    break;
825                }
826                case MCS_BOUND: {
827                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
828                    if (msg.obj != null) {
829                        mContainerService = (IMediaContainerService) msg.obj;
830                    }
831                    if (mContainerService == null) {
832                        // Something seriously wrong. Bail out
833                        Slog.e(TAG, "Cannot bind to media container service");
834                        for (HandlerParams params : mPendingInstalls) {
835                            // Indicate service bind error
836                            params.serviceError();
837                        }
838                        mPendingInstalls.clear();
839                    } else if (mPendingInstalls.size() > 0) {
840                        HandlerParams params = mPendingInstalls.get(0);
841                        if (params != null) {
842                            if (params.startCopy()) {
843                                // We are done...  look for more work or to
844                                // go idle.
845                                if (DEBUG_SD_INSTALL) Log.i(TAG,
846                                        "Checking for more work or unbind...");
847                                // Delete pending install
848                                if (mPendingInstalls.size() > 0) {
849                                    mPendingInstalls.remove(0);
850                                }
851                                if (mPendingInstalls.size() == 0) {
852                                    if (mBound) {
853                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
854                                                "Posting delayed MCS_UNBIND");
855                                        removeMessages(MCS_UNBIND);
856                                        Message ubmsg = obtainMessage(MCS_UNBIND);
857                                        // Unbind after a little delay, to avoid
858                                        // continual thrashing.
859                                        sendMessageDelayed(ubmsg, 10000);
860                                    }
861                                } else {
862                                    // There are more pending requests in queue.
863                                    // Just post MCS_BOUND message to trigger processing
864                                    // of next pending install.
865                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
866                                            "Posting MCS_BOUND for next work");
867                                    mHandler.sendEmptyMessage(MCS_BOUND);
868                                }
869                            }
870                        }
871                    } else {
872                        // Should never happen ideally.
873                        Slog.w(TAG, "Empty queue");
874                    }
875                    break;
876                }
877                case MCS_RECONNECT: {
878                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
879                    if (mPendingInstalls.size() > 0) {
880                        if (mBound) {
881                            disconnectService();
882                        }
883                        if (!connectToService()) {
884                            Slog.e(TAG, "Failed to bind to media container service");
885                            for (HandlerParams params : mPendingInstalls) {
886                                // Indicate service bind error
887                                params.serviceError();
888                            }
889                            mPendingInstalls.clear();
890                        }
891                    }
892                    break;
893                }
894                case MCS_UNBIND: {
895                    // If there is no actual work left, then time to unbind.
896                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
897
898                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
899                        if (mBound) {
900                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
901
902                            disconnectService();
903                        }
904                    } else if (mPendingInstalls.size() > 0) {
905                        // There are more pending requests in queue.
906                        // Just post MCS_BOUND message to trigger processing
907                        // of next pending install.
908                        mHandler.sendEmptyMessage(MCS_BOUND);
909                    }
910
911                    break;
912                }
913                case MCS_GIVE_UP: {
914                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
915                    mPendingInstalls.remove(0);
916                    break;
917                }
918                case SEND_PENDING_BROADCAST: {
919                    String packages[];
920                    ArrayList<String> components[];
921                    int size = 0;
922                    int uids[];
923                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
924                    synchronized (mPackages) {
925                        if (mPendingBroadcasts == null) {
926                            return;
927                        }
928                        size = mPendingBroadcasts.size();
929                        if (size <= 0) {
930                            // Nothing to be done. Just return
931                            return;
932                        }
933                        packages = new String[size];
934                        components = new ArrayList[size];
935                        uids = new int[size];
936                        int i = 0;  // filling out the above arrays
937
938                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
939                            int packageUserId = mPendingBroadcasts.userIdAt(n);
940                            Iterator<Map.Entry<String, ArrayList<String>>> it
941                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
942                                            .entrySet().iterator();
943                            while (it.hasNext() && i < size) {
944                                Map.Entry<String, ArrayList<String>> ent = it.next();
945                                packages[i] = ent.getKey();
946                                components[i] = ent.getValue();
947                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
948                                uids[i] = (ps != null)
949                                        ? UserHandle.getUid(packageUserId, ps.appId)
950                                        : -1;
951                                i++;
952                            }
953                        }
954                        size = i;
955                        mPendingBroadcasts.clear();
956                    }
957                    // Send broadcasts
958                    for (int i = 0; i < size; i++) {
959                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
960                    }
961                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
962                    break;
963                }
964                case START_CLEANING_PACKAGE: {
965                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
966                    final String packageName = (String)msg.obj;
967                    final int userId = msg.arg1;
968                    final boolean andCode = msg.arg2 != 0;
969                    synchronized (mPackages) {
970                        if (userId == UserHandle.USER_ALL) {
971                            int[] users = sUserManager.getUserIds();
972                            for (int user : users) {
973                                mSettings.addPackageToCleanLPw(
974                                        new PackageCleanItem(user, packageName, andCode));
975                            }
976                        } else {
977                            mSettings.addPackageToCleanLPw(
978                                    new PackageCleanItem(userId, packageName, andCode));
979                        }
980                    }
981                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
982                    startCleaningPackages();
983                } break;
984                case POST_INSTALL: {
985                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
986                    PostInstallData data = mRunningInstalls.get(msg.arg1);
987                    mRunningInstalls.delete(msg.arg1);
988                    boolean deleteOld = false;
989
990                    if (data != null) {
991                        InstallArgs args = data.args;
992                        PackageInstalledInfo res = data.res;
993
994                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
995                            res.removedInfo.sendBroadcast(false, true, false);
996                            Bundle extras = new Bundle(1);
997                            extras.putInt(Intent.EXTRA_UID, res.uid);
998                            // Determine the set of users who are adding this
999                            // package for the first time vs. those who are seeing
1000                            // an update.
1001                            int[] firstUsers;
1002                            int[] updateUsers = new int[0];
1003                            if (res.origUsers == null || res.origUsers.length == 0) {
1004                                firstUsers = res.newUsers;
1005                            } else {
1006                                firstUsers = new int[0];
1007                                for (int i=0; i<res.newUsers.length; i++) {
1008                                    int user = res.newUsers[i];
1009                                    boolean isNew = true;
1010                                    for (int j=0; j<res.origUsers.length; j++) {
1011                                        if (res.origUsers[j] == user) {
1012                                            isNew = false;
1013                                            break;
1014                                        }
1015                                    }
1016                                    if (isNew) {
1017                                        int[] newFirst = new int[firstUsers.length+1];
1018                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1019                                                firstUsers.length);
1020                                        newFirst[firstUsers.length] = user;
1021                                        firstUsers = newFirst;
1022                                    } else {
1023                                        int[] newUpdate = new int[updateUsers.length+1];
1024                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1025                                                updateUsers.length);
1026                                        newUpdate[updateUsers.length] = user;
1027                                        updateUsers = newUpdate;
1028                                    }
1029                                }
1030                            }
1031                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1032                                    res.pkg.applicationInfo.packageName,
1033                                    extras, null, null, firstUsers);
1034                            final boolean update = res.removedInfo.removedPackage != null;
1035                            if (update) {
1036                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1037                            }
1038                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1039                                    res.pkg.applicationInfo.packageName,
1040                                    extras, null, null, updateUsers);
1041                            if (update) {
1042                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1043                                        res.pkg.applicationInfo.packageName,
1044                                        extras, null, null, updateUsers);
1045                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1046                                        null, null,
1047                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1048
1049                                // treat asec-hosted packages like removable media on upgrade
1050                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1051                                    if (DEBUG_INSTALL) {
1052                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1053                                                + " is ASEC-hosted -> AVAILABLE");
1054                                    }
1055                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1056                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1057                                    pkgList.add(res.pkg.applicationInfo.packageName);
1058                                    sendResourcesChangedBroadcast(true, true,
1059                                            pkgList,uidArray, null);
1060                                }
1061                            }
1062                            if (res.removedInfo.args != null) {
1063                                // Remove the replaced package's older resources safely now
1064                                deleteOld = true;
1065                            }
1066
1067                            // Log current value of "unknown sources" setting
1068                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1069                                getUnknownSourcesSettings());
1070                        }
1071                        // Force a gc to clear up things
1072                        Runtime.getRuntime().gc();
1073                        // We delete after a gc for applications  on sdcard.
1074                        if (deleteOld) {
1075                            synchronized (mInstallLock) {
1076                                res.removedInfo.args.doPostDeleteLI(true);
1077                            }
1078                        }
1079                        if (args.observer != null) {
1080                            try {
1081                                args.observer.packageInstalled(res.name, res.returnCode);
1082                            } catch (RemoteException e) {
1083                                Slog.i(TAG, "Observer no longer exists.");
1084                            }
1085                        }
1086                        if (args.observer2 != null) {
1087                            try {
1088                                Bundle extras = extrasForInstallResult(res);
1089                                args.observer2.packageInstalled(res.name, extras, res.returnCode);
1090                            } catch (RemoteException e) {
1091                                Slog.i(TAG, "Observer no longer exists.");
1092                            }
1093                        }
1094                    } else {
1095                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1096                    }
1097                } break;
1098                case UPDATED_MEDIA_STATUS: {
1099                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1100                    boolean reportStatus = msg.arg1 == 1;
1101                    boolean doGc = msg.arg2 == 1;
1102                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1103                    if (doGc) {
1104                        // Force a gc to clear up stale containers.
1105                        Runtime.getRuntime().gc();
1106                    }
1107                    if (msg.obj != null) {
1108                        @SuppressWarnings("unchecked")
1109                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1110                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1111                        // Unload containers
1112                        unloadAllContainers(args);
1113                    }
1114                    if (reportStatus) {
1115                        try {
1116                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1117                            PackageHelper.getMountService().finishMediaUpdate();
1118                        } catch (RemoteException e) {
1119                            Log.e(TAG, "MountService not running?");
1120                        }
1121                    }
1122                } break;
1123                case WRITE_SETTINGS: {
1124                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1125                    synchronized (mPackages) {
1126                        removeMessages(WRITE_SETTINGS);
1127                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1128                        mSettings.writeLPr();
1129                        mDirtyUsers.clear();
1130                    }
1131                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1132                } break;
1133                case WRITE_PACKAGE_RESTRICTIONS: {
1134                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1135                    synchronized (mPackages) {
1136                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1137                        for (int userId : mDirtyUsers) {
1138                            mSettings.writePackageRestrictionsLPr(userId);
1139                        }
1140                        mDirtyUsers.clear();
1141                    }
1142                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1143                } break;
1144                case CHECK_PENDING_VERIFICATION: {
1145                    final int verificationId = msg.arg1;
1146                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1147
1148                    if ((state != null) && !state.timeoutExtended()) {
1149                        final InstallArgs args = state.getInstallArgs();
1150                        Slog.i(TAG, "Verification timed out for " + args.packageURI.toString());
1151                        mPendingVerification.remove(verificationId);
1152
1153                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1154
1155                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1156                            Slog.i(TAG, "Continuing with installation of "
1157                                    + args.packageURI.toString());
1158                            state.setVerifierResponse(Binder.getCallingUid(),
1159                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1160                            broadcastPackageVerified(verificationId, args.packageURI,
1161                                    PackageManager.VERIFICATION_ALLOW,
1162                                    state.getInstallArgs().getUser());
1163                            try {
1164                                ret = args.copyApk(mContainerService, true);
1165                            } catch (RemoteException e) {
1166                                Slog.e(TAG, "Could not contact the ContainerService");
1167                            }
1168                        } else {
1169                            broadcastPackageVerified(verificationId, args.packageURI,
1170                                    PackageManager.VERIFICATION_REJECT,
1171                                    state.getInstallArgs().getUser());
1172                        }
1173
1174                        processPendingInstall(args, ret);
1175                        mHandler.sendEmptyMessage(MCS_UNBIND);
1176                    }
1177                    break;
1178                }
1179                case PACKAGE_VERIFIED: {
1180                    final int verificationId = msg.arg1;
1181
1182                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1183                    if (state == null) {
1184                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1185                        break;
1186                    }
1187
1188                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1189
1190                    state.setVerifierResponse(response.callerUid, response.code);
1191
1192                    if (state.isVerificationComplete()) {
1193                        mPendingVerification.remove(verificationId);
1194
1195                        final InstallArgs args = state.getInstallArgs();
1196
1197                        int ret;
1198                        if (state.isInstallAllowed()) {
1199                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1200                            broadcastPackageVerified(verificationId, args.packageURI,
1201                                    response.code, state.getInstallArgs().getUser());
1202                            try {
1203                                ret = args.copyApk(mContainerService, true);
1204                            } catch (RemoteException e) {
1205                                Slog.e(TAG, "Could not contact the ContainerService");
1206                            }
1207                        } else {
1208                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1209                        }
1210
1211                        processPendingInstall(args, ret);
1212
1213                        mHandler.sendEmptyMessage(MCS_UNBIND);
1214                    }
1215
1216                    break;
1217                }
1218            }
1219        }
1220    }
1221
1222    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1223        Bundle extras = null;
1224        switch (res.returnCode) {
1225            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1226                extras = new Bundle();
1227                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1228                        res.origPermission);
1229                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1230                        res.origPackage);
1231                break;
1232            }
1233        }
1234        return extras;
1235    }
1236
1237    void scheduleWriteSettingsLocked() {
1238        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1239            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1240        }
1241    }
1242
1243    void scheduleWritePackageRestrictionsLocked(int userId) {
1244        if (!sUserManager.exists(userId)) return;
1245        mDirtyUsers.add(userId);
1246        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1247            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1248        }
1249    }
1250
1251    public static final PackageManagerService main(Context context, Installer installer,
1252            boolean factoryTest, boolean onlyCore) {
1253        PackageManagerService m = new PackageManagerService(context, installer,
1254                factoryTest, onlyCore);
1255        ServiceManager.addService("package", m);
1256        return m;
1257    }
1258
1259    static String[] splitString(String str, char sep) {
1260        int count = 1;
1261        int i = 0;
1262        while ((i=str.indexOf(sep, i)) >= 0) {
1263            count++;
1264            i++;
1265        }
1266
1267        String[] res = new String[count];
1268        i=0;
1269        count = 0;
1270        int lastI=0;
1271        while ((i=str.indexOf(sep, i)) >= 0) {
1272            res[count] = str.substring(lastI, i);
1273            count++;
1274            i++;
1275            lastI = i;
1276        }
1277        res[count] = str.substring(lastI, str.length());
1278        return res;
1279    }
1280
1281    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1282        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1283                Context.DISPLAY_SERVICE);
1284        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1285    }
1286
1287    public PackageManagerService(Context context, Installer installer,
1288            boolean factoryTest, boolean onlyCore) {
1289        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1290                SystemClock.uptimeMillis());
1291
1292        if (mSdkVersion <= 0) {
1293            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1294        }
1295
1296        mContext = context;
1297        mFactoryTest = factoryTest;
1298        mOnlyCore = onlyCore;
1299        mMetrics = new DisplayMetrics();
1300        mSettings = new Settings(context);
1301        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1302                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1303        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1304                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1305        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1306                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1307        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1308                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1309        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1310                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1311        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1312                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1313
1314        String separateProcesses = SystemProperties.get("debug.separate_processes");
1315        if (separateProcesses != null && separateProcesses.length() > 0) {
1316            if ("*".equals(separateProcesses)) {
1317                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1318                mSeparateProcesses = null;
1319                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1320            } else {
1321                mDefParseFlags = 0;
1322                mSeparateProcesses = separateProcesses.split(",");
1323                Slog.w(TAG, "Running with debug.separate_processes: "
1324                        + separateProcesses);
1325            }
1326        } else {
1327            mDefParseFlags = 0;
1328            mSeparateProcesses = null;
1329        }
1330
1331        mInstaller = installer;
1332
1333        getDefaultDisplayMetrics(context, mMetrics);
1334
1335        synchronized (mInstallLock) {
1336        // writer
1337        synchronized (mPackages) {
1338            mHandlerThread = new ServiceThread(TAG,
1339                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1340            mHandlerThread.start();
1341            mHandler = new PackageHandler(mHandlerThread.getLooper());
1342            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1343
1344            File dataDir = Environment.getDataDirectory();
1345            mAppDataDir = new File(dataDir, "data");
1346            mAppInstallDir = new File(dataDir, "app");
1347            mAppLibInstallDir = new File(dataDir, "app-lib");
1348            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1349            mUserAppDataDir = new File(dataDir, "user");
1350            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1351            mAppStagingDir = new File(dataDir, "app-staging");
1352
1353            sUserManager = new UserManagerService(context, this,
1354                    mInstallLock, mPackages);
1355
1356            // Read permissions and features from system
1357            readPermissions(Environment.buildPath(
1358                    Environment.getRootDirectory(), "etc", "permissions"), false);
1359            // Only read features from OEM
1360            readPermissions(Environment.buildPath(
1361                    Environment.getOemDirectory(), "etc", "permissions"), true);
1362
1363            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1364
1365            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1366                    mSdkVersion, mOnlyCore);
1367
1368            String customResolverActivity = Resources.getSystem().getString(
1369                    R.string.config_customResolverActivity);
1370            if (TextUtils.isEmpty(customResolverActivity)) {
1371                customResolverActivity = null;
1372            } else {
1373                mCustomResolverComponentName = ComponentName.unflattenFromString(
1374                        customResolverActivity);
1375            }
1376
1377            long startTime = SystemClock.uptimeMillis();
1378
1379            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1380                    startTime);
1381
1382            // Set flag to monitor and not change apk file paths when
1383            // scanning install directories.
1384            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1385
1386            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1387
1388            /**
1389             * Add everything in the in the boot class path to the
1390             * list of process files because dexopt will have been run
1391             * if necessary during zygote startup.
1392             */
1393            String bootClassPath = System.getProperty("java.boot.class.path");
1394            if (bootClassPath != null) {
1395                String[] paths = splitString(bootClassPath, ':');
1396                for (int i=0; i<paths.length; i++) {
1397                    alreadyDexOpted.add(paths[i]);
1398                }
1399            } else {
1400                Slog.w(TAG, "No BOOTCLASSPATH found!");
1401            }
1402
1403            boolean didDexOptLibraryOrTool = false;
1404
1405            final List<String> instructionSets = getAllInstructionSets();
1406
1407            /**
1408             * Ensure all external libraries have had dexopt run on them.
1409             */
1410            if (mSharedLibraries.size() > 0) {
1411                // NOTE: For now, we're compiling these system "shared libraries"
1412                // (and framework jars) into all available architectures. It's possible
1413                // to compile them only when we come across an app that uses them (there's
1414                // already logic for that in scanPackageLI) but that adds some complexity.
1415                for (String instructionSet : instructionSets) {
1416                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1417                        final String lib = libEntry.path;
1418                        if (lib == null) {
1419                            continue;
1420                        }
1421
1422                        try {
1423                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1424                                alreadyDexOpted.add(lib);
1425
1426                                // The list of "shared libraries" we have at this point is
1427                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1428                                didDexOptLibraryOrTool = true;
1429                            }
1430                        } catch (FileNotFoundException e) {
1431                            Slog.w(TAG, "Library not found: " + lib);
1432                        } catch (IOException e) {
1433                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1434                                    + e.getMessage());
1435                        }
1436                    }
1437                }
1438            }
1439
1440            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1441
1442            // Gross hack for now: we know this file doesn't contain any
1443            // code, so don't dexopt it to avoid the resulting log spew.
1444            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1445
1446            // Gross hack for now: we know this file is only part of
1447            // the boot class path for art, so don't dexopt it to
1448            // avoid the resulting log spew.
1449            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1450
1451            /**
1452             * And there are a number of commands implemented in Java, which
1453             * we currently need to do the dexopt on so that they can be
1454             * run from a non-root shell.
1455             */
1456            String[] frameworkFiles = frameworkDir.list();
1457            if (frameworkFiles != null) {
1458                // TODO: We could compile these only for the most preferred ABI. We should
1459                // first double check that the dex files for these commands are not referenced
1460                // by other system apps.
1461                for (String instructionSet : instructionSets) {
1462                    for (int i=0; i<frameworkFiles.length; i++) {
1463                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1464                        String path = libPath.getPath();
1465                        // Skip the file if we already did it.
1466                        if (alreadyDexOpted.contains(path)) {
1467                            continue;
1468                        }
1469                        // Skip the file if it is not a type we want to dexopt.
1470                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1471                            continue;
1472                        }
1473                        try {
1474                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1475                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1476                                didDexOptLibraryOrTool = true;
1477                            }
1478                        } catch (FileNotFoundException e) {
1479                            Slog.w(TAG, "Jar not found: " + path);
1480                        } catch (IOException e) {
1481                            Slog.w(TAG, "Exception reading jar: " + path, e);
1482                        }
1483                    }
1484                }
1485            }
1486
1487            if (didDexOptLibraryOrTool) {
1488                // If we dexopted a library or tool, then something on the system has
1489                // changed. Consider this significant, and wipe away all other
1490                // existing dexopt files to ensure we don't leave any dangling around.
1491                //
1492                // Additionally, delete all dex files from the root directory
1493                // since there shouldn't be any there anyway.
1494                //
1495                // TODO: This should be revisited because it isn't as good an indicator
1496                // as it used to be. It used to include the boot classpath but at some point
1497                // DexFile.isDexOptNeeded started returning false for the boot
1498                // class path files in all cases. It is very possible in a
1499                // small maintenance release update that the library and tool
1500                // jars may be unchanged but APK could be removed resulting in
1501                // unused dalvik-cache files.
1502                mInstaller.pruneDexCache();
1503            }
1504
1505            // Collect vendor overlay packages.
1506            // (Do this before scanning any apps.)
1507            // For security and version matching reason, only consider
1508            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1509            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1510            mVendorOverlayInstallObserver = new AppDirObserver(
1511                vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1512            mVendorOverlayInstallObserver.startWatching();
1513            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1514                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1515
1516            // Find base frameworks (resource packages without code).
1517            mFrameworkInstallObserver = new AppDirObserver(
1518                frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1519            mFrameworkInstallObserver.startWatching();
1520            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1521                    | PackageParser.PARSE_IS_SYSTEM_DIR
1522                    | PackageParser.PARSE_IS_PRIVILEGED,
1523                    scanMode | SCAN_NO_DEX, 0);
1524
1525            // Collected privileged system packages.
1526            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1527            mPrivilegedInstallObserver = new AppDirObserver(
1528                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1529            mPrivilegedInstallObserver.startWatching();
1530                scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1531                        | PackageParser.PARSE_IS_SYSTEM_DIR
1532                        | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1533
1534            // Collect ordinary system packages.
1535            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1536            mSystemInstallObserver = new AppDirObserver(
1537                systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1538            mSystemInstallObserver.startWatching();
1539            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1540                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1541
1542            // Collect all vendor packages.
1543            File vendorAppDir = new File("/vendor/app");
1544            try {
1545                vendorAppDir = vendorAppDir.getCanonicalFile();
1546            } catch (IOException e) {
1547                // failed to look up canonical path, continue with original one
1548            }
1549            mVendorInstallObserver = new AppDirObserver(
1550                vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1551            mVendorInstallObserver.startWatching();
1552            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1553                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1554
1555            // Collect all OEM packages.
1556            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1557            mOemInstallObserver = new AppDirObserver(
1558                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1559            mOemInstallObserver.startWatching();
1560            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1561                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1562
1563            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1564            mInstaller.moveFiles();
1565
1566            // Prune any system packages that no longer exist.
1567            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1568            if (!mOnlyCore) {
1569                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1570                while (psit.hasNext()) {
1571                    PackageSetting ps = psit.next();
1572
1573                    /*
1574                     * If this is not a system app, it can't be a
1575                     * disable system app.
1576                     */
1577                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1578                        continue;
1579                    }
1580
1581                    /*
1582                     * If the package is scanned, it's not erased.
1583                     */
1584                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1585                    if (scannedPkg != null) {
1586                        /*
1587                         * If the system app is both scanned and in the
1588                         * disabled packages list, then it must have been
1589                         * added via OTA. Remove it from the currently
1590                         * scanned package so the previously user-installed
1591                         * application can be scanned.
1592                         */
1593                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1594                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1595                                    + "; removing system app");
1596                            removePackageLI(ps, true);
1597                        }
1598
1599                        continue;
1600                    }
1601
1602                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1603                        psit.remove();
1604                        String msg = "System package " + ps.name
1605                                + " no longer exists; wiping its data";
1606                        reportSettingsProblem(Log.WARN, msg);
1607                        removeDataDirsLI(ps.name);
1608                    } else {
1609                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1610                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1611                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1612                        }
1613                    }
1614                }
1615            }
1616
1617            //look for any incomplete package installations
1618            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1619            //clean up list
1620            for(int i = 0; i < deletePkgsList.size(); i++) {
1621                //clean up here
1622                cleanupInstallFailedPackage(deletePkgsList.get(i));
1623            }
1624            //delete tmp files
1625            deleteTempPackageFiles();
1626
1627            // Remove any shared userIDs that have no associated packages
1628            mSettings.pruneSharedUsersLPw();
1629
1630            if (!mOnlyCore) {
1631                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1632                        SystemClock.uptimeMillis());
1633                mAppInstallObserver = new AppDirObserver(
1634                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1635                mAppInstallObserver.startWatching();
1636                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1637
1638                mDrmAppInstallObserver = new AppDirObserver(
1639                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1640                mDrmAppInstallObserver.startWatching();
1641                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1642                        scanMode, 0);
1643
1644                /**
1645                 * Remove disable package settings for any updated system
1646                 * apps that were removed via an OTA. If they're not a
1647                 * previously-updated app, remove them completely.
1648                 * Otherwise, just revoke their system-level permissions.
1649                 */
1650                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1651                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1652                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1653
1654                    String msg;
1655                    if (deletedPkg == null) {
1656                        msg = "Updated system package " + deletedAppName
1657                                + " no longer exists; wiping its data";
1658                        removeDataDirsLI(deletedAppName);
1659                    } else {
1660                        msg = "Updated system app + " + deletedAppName
1661                                + " no longer present; removing system privileges for "
1662                                + deletedAppName;
1663
1664                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1665
1666                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1667                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1668                    }
1669                    reportSettingsProblem(Log.WARN, msg);
1670                }
1671            } else {
1672                mAppInstallObserver = null;
1673                mDrmAppInstallObserver = null;
1674            }
1675
1676            // Now that we know all of the shared libraries, update all clients to have
1677            // the correct library paths.
1678            updateAllSharedLibrariesLPw();
1679
1680            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1681                // NOTE: We ignore potential failures here during a system scan (like
1682                // the rest of the commands above) because there's precious little we
1683                // can do about it. A settings error is reported, though.
1684                adjustCpuAbisForSharedUserLPw(setting.packages, null,
1685                        false /* force dexopt */, false /* defer dexopt */);
1686            }
1687
1688            // Now that we know all the packages we are keeping,
1689            // read and update their last usage times.
1690            mPackageUsage.readLP();
1691
1692            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1693                    SystemClock.uptimeMillis());
1694            Slog.i(TAG, "Time to scan packages: "
1695                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1696                    + " seconds");
1697
1698            // If the platform SDK has changed since the last time we booted,
1699            // we need to re-grant app permission to catch any new ones that
1700            // appear.  This is really a hack, and means that apps can in some
1701            // cases get permissions that the user didn't initially explicitly
1702            // allow...  it would be nice to have some better way to handle
1703            // this situation.
1704            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1705                    != mSdkVersion;
1706            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1707                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1708                    + "; regranting permissions for internal storage");
1709            mSettings.mInternalSdkPlatform = mSdkVersion;
1710
1711            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1712                    | (regrantPermissions
1713                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1714                            : 0));
1715
1716            // If this is the first boot, and it is a normal boot, then
1717            // we need to initialize the default preferred apps.
1718            if (!mRestoredSettings && !onlyCore) {
1719                mSettings.readDefaultPreferredAppsLPw(this, 0);
1720            }
1721
1722            // All the changes are done during package scanning.
1723            mSettings.updateInternalDatabaseVersion();
1724
1725            // can downgrade to reader
1726            mSettings.writeLPr();
1727
1728            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1729                    SystemClock.uptimeMillis());
1730
1731
1732            mRequiredVerifierPackage = getRequiredVerifierLPr();
1733        } // synchronized (mPackages)
1734        } // synchronized (mInstallLock)
1735
1736        mInstallerService = new PackageInstallerService(context, this, mAppStagingDir);
1737
1738        // Now after opening every single application zip, make sure they
1739        // are all flushed.  Not really needed, but keeps things nice and
1740        // tidy.
1741        Runtime.getRuntime().gc();
1742    }
1743
1744    @Override
1745    public boolean isFirstBoot() {
1746        return !mRestoredSettings || mPackageUsage.isFirstBoot();
1747    }
1748
1749    @Override
1750    public boolean isOnlyCoreApps() {
1751        return mOnlyCore;
1752    }
1753
1754    private String getRequiredVerifierLPr() {
1755        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1756        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1757                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1758
1759        String requiredVerifier = null;
1760
1761        final int N = receivers.size();
1762        for (int i = 0; i < N; i++) {
1763            final ResolveInfo info = receivers.get(i);
1764
1765            if (info.activityInfo == null) {
1766                continue;
1767            }
1768
1769            final String packageName = info.activityInfo.packageName;
1770
1771            final PackageSetting ps = mSettings.mPackages.get(packageName);
1772            if (ps == null) {
1773                continue;
1774            }
1775
1776            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1777            if (!gp.grantedPermissions
1778                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1779                continue;
1780            }
1781
1782            if (requiredVerifier != null) {
1783                throw new RuntimeException("There can be only one required verifier");
1784            }
1785
1786            requiredVerifier = packageName;
1787        }
1788
1789        return requiredVerifier;
1790    }
1791
1792    @Override
1793    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1794            throws RemoteException {
1795        try {
1796            return super.onTransact(code, data, reply, flags);
1797        } catch (RuntimeException e) {
1798            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1799                Slog.wtf(TAG, "Package Manager Crash", e);
1800            }
1801            throw e;
1802        }
1803    }
1804
1805    void cleanupInstallFailedPackage(PackageSetting ps) {
1806        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1807        removeDataDirsLI(ps.name);
1808        if (ps.codePath != null) {
1809            if (!ps.codePath.delete()) {
1810                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1811            }
1812        }
1813        if (ps.resourcePath != null) {
1814            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1815                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1816            }
1817        }
1818        mSettings.removePackageLPw(ps.name);
1819    }
1820
1821    void readPermissions(File libraryDir, boolean onlyFeatures) {
1822        // Read permissions from .../etc/permission directory.
1823        if (!libraryDir.exists() || !libraryDir.isDirectory()) {
1824            Slog.w(TAG, "No directory " + libraryDir + ", skipping");
1825            return;
1826        }
1827        if (!libraryDir.canRead()) {
1828            Slog.w(TAG, "Directory " + libraryDir + " cannot be read");
1829            return;
1830        }
1831
1832        // Iterate over the files in the directory and scan .xml files
1833        for (File f : libraryDir.listFiles()) {
1834            // We'll read platform.xml last
1835            if (f.getPath().endsWith("etc/permissions/platform.xml")) {
1836                continue;
1837            }
1838
1839            if (!f.getPath().endsWith(".xml")) {
1840                Slog.i(TAG, "Non-xml file " + f + " in " + libraryDir + " directory, ignoring");
1841                continue;
1842            }
1843            if (!f.canRead()) {
1844                Slog.w(TAG, "Permissions library file " + f + " cannot be read");
1845                continue;
1846            }
1847
1848            readPermissionsFromXml(f, onlyFeatures);
1849        }
1850
1851        // Read permissions from .../etc/permissions/platform.xml last so it will take precedence
1852        final File permFile = new File(Environment.getRootDirectory(),
1853                "etc/permissions/platform.xml");
1854        readPermissionsFromXml(permFile, onlyFeatures);
1855    }
1856
1857    private void readPermissionsFromXml(File permFile, boolean onlyFeatures) {
1858        FileReader permReader = null;
1859        try {
1860            permReader = new FileReader(permFile);
1861        } catch (FileNotFoundException e) {
1862            Slog.w(TAG, "Couldn't find or open permissions file " + permFile);
1863            return;
1864        }
1865
1866        try {
1867            XmlPullParser parser = Xml.newPullParser();
1868            parser.setInput(permReader);
1869
1870            XmlUtils.beginDocument(parser, "permissions");
1871
1872            while (true) {
1873                XmlUtils.nextElement(parser);
1874                if (parser.getEventType() == XmlPullParser.END_DOCUMENT) {
1875                    break;
1876                }
1877
1878                String name = parser.getName();
1879                if ("group".equals(name) && !onlyFeatures) {
1880                    String gidStr = parser.getAttributeValue(null, "gid");
1881                    if (gidStr != null) {
1882                        int gid = Process.getGidForName(gidStr);
1883                        mGlobalGids = appendInt(mGlobalGids, gid);
1884                    } else {
1885                        Slog.w(TAG, "<group> without gid at "
1886                                + parser.getPositionDescription());
1887                    }
1888
1889                    XmlUtils.skipCurrentTag(parser);
1890                    continue;
1891                } else if ("permission".equals(name) && !onlyFeatures) {
1892                    String perm = parser.getAttributeValue(null, "name");
1893                    if (perm == null) {
1894                        Slog.w(TAG, "<permission> without name at "
1895                                + parser.getPositionDescription());
1896                        XmlUtils.skipCurrentTag(parser);
1897                        continue;
1898                    }
1899                    perm = perm.intern();
1900                    readPermission(parser, perm);
1901
1902                } else if ("assign-permission".equals(name) && !onlyFeatures) {
1903                    String perm = parser.getAttributeValue(null, "name");
1904                    if (perm == null) {
1905                        Slog.w(TAG, "<assign-permission> without name at "
1906                                + parser.getPositionDescription());
1907                        XmlUtils.skipCurrentTag(parser);
1908                        continue;
1909                    }
1910                    String uidStr = parser.getAttributeValue(null, "uid");
1911                    if (uidStr == null) {
1912                        Slog.w(TAG, "<assign-permission> without uid at "
1913                                + parser.getPositionDescription());
1914                        XmlUtils.skipCurrentTag(parser);
1915                        continue;
1916                    }
1917                    int uid = Process.getUidForName(uidStr);
1918                    if (uid < 0) {
1919                        Slog.w(TAG, "<assign-permission> with unknown uid \""
1920                                + uidStr + "\" at "
1921                                + parser.getPositionDescription());
1922                        XmlUtils.skipCurrentTag(parser);
1923                        continue;
1924                    }
1925                    perm = perm.intern();
1926                    HashSet<String> perms = mSystemPermissions.get(uid);
1927                    if (perms == null) {
1928                        perms = new HashSet<String>();
1929                        mSystemPermissions.put(uid, perms);
1930                    }
1931                    perms.add(perm);
1932                    XmlUtils.skipCurrentTag(parser);
1933
1934                } else if ("library".equals(name) && !onlyFeatures) {
1935                    String lname = parser.getAttributeValue(null, "name");
1936                    String lfile = parser.getAttributeValue(null, "file");
1937                    if (lname == null) {
1938                        Slog.w(TAG, "<library> without name at "
1939                                + parser.getPositionDescription());
1940                    } else if (lfile == null) {
1941                        Slog.w(TAG, "<library> without file at "
1942                                + parser.getPositionDescription());
1943                    } else {
1944                        //Log.i(TAG, "Got library " + lname + " in " + lfile);
1945                        mSharedLibraries.put(lname, new SharedLibraryEntry(lfile, null));
1946                    }
1947                    XmlUtils.skipCurrentTag(parser);
1948                    continue;
1949
1950                } else if ("feature".equals(name)) {
1951                    String fname = parser.getAttributeValue(null, "name");
1952                    if (fname == null) {
1953                        Slog.w(TAG, "<feature> without name at "
1954                                + parser.getPositionDescription());
1955                    } else {
1956                        //Log.i(TAG, "Got feature " + fname);
1957                        FeatureInfo fi = new FeatureInfo();
1958                        fi.name = fname;
1959                        mAvailableFeatures.put(fname, fi);
1960                    }
1961                    XmlUtils.skipCurrentTag(parser);
1962                    continue;
1963
1964                } else {
1965                    XmlUtils.skipCurrentTag(parser);
1966                    continue;
1967                }
1968
1969            }
1970            permReader.close();
1971        } catch (XmlPullParserException e) {
1972            Slog.w(TAG, "Got execption parsing permissions.", e);
1973        } catch (IOException e) {
1974            Slog.w(TAG, "Got execption parsing permissions.", e);
1975        }
1976    }
1977
1978    void readPermission(XmlPullParser parser, String name)
1979            throws IOException, XmlPullParserException {
1980
1981        name = name.intern();
1982
1983        BasePermission bp = mSettings.mPermissions.get(name);
1984        if (bp == null) {
1985            bp = new BasePermission(name, null, BasePermission.TYPE_BUILTIN);
1986            mSettings.mPermissions.put(name, bp);
1987        }
1988        int outerDepth = parser.getDepth();
1989        int type;
1990        while ((type=parser.next()) != XmlPullParser.END_DOCUMENT
1991               && (type != XmlPullParser.END_TAG
1992                       || parser.getDepth() > outerDepth)) {
1993            if (type == XmlPullParser.END_TAG
1994                    || type == XmlPullParser.TEXT) {
1995                continue;
1996            }
1997
1998            String tagName = parser.getName();
1999            if ("group".equals(tagName)) {
2000                String gidStr = parser.getAttributeValue(null, "gid");
2001                if (gidStr != null) {
2002                    int gid = Process.getGidForName(gidStr);
2003                    bp.gids = appendInt(bp.gids, gid);
2004                } else {
2005                    Slog.w(TAG, "<group> without gid at "
2006                            + parser.getPositionDescription());
2007                }
2008            }
2009            XmlUtils.skipCurrentTag(parser);
2010        }
2011    }
2012
2013    static int[] appendInts(int[] cur, int[] add) {
2014        if (add == null) return cur;
2015        if (cur == null) return add;
2016        final int N = add.length;
2017        for (int i=0; i<N; i++) {
2018            cur = appendInt(cur, add[i]);
2019        }
2020        return cur;
2021    }
2022
2023    static int[] removeInts(int[] cur, int[] rem) {
2024        if (rem == null) return cur;
2025        if (cur == null) return cur;
2026        final int N = rem.length;
2027        for (int i=0; i<N; i++) {
2028            cur = removeInt(cur, rem[i]);
2029        }
2030        return cur;
2031    }
2032
2033    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
2034        if (!sUserManager.exists(userId)) return null;
2035        final PackageSetting ps = (PackageSetting) p.mExtras;
2036        if (ps == null) {
2037            return null;
2038        }
2039        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
2040        final PackageUserState state = ps.readUserState(userId);
2041        return PackageParser.generatePackageInfo(p, gp.gids, flags,
2042                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
2043                state, userId);
2044    }
2045
2046    @Override
2047    public boolean isPackageAvailable(String packageName, int userId) {
2048        if (!sUserManager.exists(userId)) return false;
2049        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
2050        synchronized (mPackages) {
2051            PackageParser.Package p = mPackages.get(packageName);
2052            if (p != null) {
2053                final PackageSetting ps = (PackageSetting) p.mExtras;
2054                if (ps != null) {
2055                    final PackageUserState state = ps.readUserState(userId);
2056                    if (state != null) {
2057                        return PackageParser.isAvailable(state);
2058                    }
2059                }
2060            }
2061        }
2062        return false;
2063    }
2064
2065    @Override
2066    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
2067        if (!sUserManager.exists(userId)) return null;
2068        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
2069        // reader
2070        synchronized (mPackages) {
2071            PackageParser.Package p = mPackages.get(packageName);
2072            if (DEBUG_PACKAGE_INFO)
2073                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
2074            if (p != null) {
2075                return generatePackageInfo(p, flags, userId);
2076            }
2077            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2078                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
2079            }
2080        }
2081        return null;
2082    }
2083
2084    @Override
2085    public String[] currentToCanonicalPackageNames(String[] names) {
2086        String[] out = new String[names.length];
2087        // reader
2088        synchronized (mPackages) {
2089            for (int i=names.length-1; i>=0; i--) {
2090                PackageSetting ps = mSettings.mPackages.get(names[i]);
2091                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
2092            }
2093        }
2094        return out;
2095    }
2096
2097    @Override
2098    public String[] canonicalToCurrentPackageNames(String[] names) {
2099        String[] out = new String[names.length];
2100        // reader
2101        synchronized (mPackages) {
2102            for (int i=names.length-1; i>=0; i--) {
2103                String cur = mSettings.mRenamedPackages.get(names[i]);
2104                out[i] = cur != null ? cur : names[i];
2105            }
2106        }
2107        return out;
2108    }
2109
2110    @Override
2111    public int getPackageUid(String packageName, int userId) {
2112        if (!sUserManager.exists(userId)) return -1;
2113        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
2114        // reader
2115        synchronized (mPackages) {
2116            PackageParser.Package p = mPackages.get(packageName);
2117            if(p != null) {
2118                return UserHandle.getUid(userId, p.applicationInfo.uid);
2119            }
2120            PackageSetting ps = mSettings.mPackages.get(packageName);
2121            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
2122                return -1;
2123            }
2124            p = ps.pkg;
2125            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
2126        }
2127    }
2128
2129    @Override
2130    public int[] getPackageGids(String packageName) {
2131        // reader
2132        synchronized (mPackages) {
2133            PackageParser.Package p = mPackages.get(packageName);
2134            if (DEBUG_PACKAGE_INFO)
2135                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
2136            if (p != null) {
2137                final PackageSetting ps = (PackageSetting)p.mExtras;
2138                return ps.getGids();
2139            }
2140        }
2141        // stupid thing to indicate an error.
2142        return new int[0];
2143    }
2144
2145    static final PermissionInfo generatePermissionInfo(
2146            BasePermission bp, int flags) {
2147        if (bp.perm != null) {
2148            return PackageParser.generatePermissionInfo(bp.perm, flags);
2149        }
2150        PermissionInfo pi = new PermissionInfo();
2151        pi.name = bp.name;
2152        pi.packageName = bp.sourcePackage;
2153        pi.nonLocalizedLabel = bp.name;
2154        pi.protectionLevel = bp.protectionLevel;
2155        return pi;
2156    }
2157
2158    @Override
2159    public PermissionInfo getPermissionInfo(String name, int flags) {
2160        // reader
2161        synchronized (mPackages) {
2162            final BasePermission p = mSettings.mPermissions.get(name);
2163            if (p != null) {
2164                return generatePermissionInfo(p, flags);
2165            }
2166            return null;
2167        }
2168    }
2169
2170    @Override
2171    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2172        // reader
2173        synchronized (mPackages) {
2174            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2175            for (BasePermission p : mSettings.mPermissions.values()) {
2176                if (group == null) {
2177                    if (p.perm == null || p.perm.info.group == null) {
2178                        out.add(generatePermissionInfo(p, flags));
2179                    }
2180                } else {
2181                    if (p.perm != null && group.equals(p.perm.info.group)) {
2182                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2183                    }
2184                }
2185            }
2186
2187            if (out.size() > 0) {
2188                return out;
2189            }
2190            return mPermissionGroups.containsKey(group) ? out : null;
2191        }
2192    }
2193
2194    @Override
2195    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2196        // reader
2197        synchronized (mPackages) {
2198            return PackageParser.generatePermissionGroupInfo(
2199                    mPermissionGroups.get(name), flags);
2200        }
2201    }
2202
2203    @Override
2204    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2205        // reader
2206        synchronized (mPackages) {
2207            final int N = mPermissionGroups.size();
2208            ArrayList<PermissionGroupInfo> out
2209                    = new ArrayList<PermissionGroupInfo>(N);
2210            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2211                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2212            }
2213            return out;
2214        }
2215    }
2216
2217    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2218            int userId) {
2219        if (!sUserManager.exists(userId)) return null;
2220        PackageSetting ps = mSettings.mPackages.get(packageName);
2221        if (ps != null) {
2222            if (ps.pkg == null) {
2223                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2224                        flags, userId);
2225                if (pInfo != null) {
2226                    return pInfo.applicationInfo;
2227                }
2228                return null;
2229            }
2230            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2231                    ps.readUserState(userId), userId);
2232        }
2233        return null;
2234    }
2235
2236    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2237            int userId) {
2238        if (!sUserManager.exists(userId)) return null;
2239        PackageSetting ps = mSettings.mPackages.get(packageName);
2240        if (ps != null) {
2241            PackageParser.Package pkg = ps.pkg;
2242            if (pkg == null) {
2243                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2244                    return null;
2245                }
2246                // App code is gone, so we aren't worried about split paths
2247                pkg = new PackageParser.Package(packageName);
2248                pkg.applicationInfo.packageName = packageName;
2249                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2250                pkg.applicationInfo.sourceDir = ps.codePathString;
2251                pkg.applicationInfo.publicSourceDir = ps.resourcePathString;
2252                pkg.applicationInfo.dataDir =
2253                        getDataPathForPackage(packageName, 0).getPath();
2254                pkg.applicationInfo.nativeLibraryDir = ps.nativeLibraryPathString;
2255                pkg.applicationInfo.cpuAbi = ps.cpuAbiString;
2256            }
2257            return generatePackageInfo(pkg, flags, userId);
2258        }
2259        return null;
2260    }
2261
2262    @Override
2263    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2264        if (!sUserManager.exists(userId)) return null;
2265        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2266        // writer
2267        synchronized (mPackages) {
2268            PackageParser.Package p = mPackages.get(packageName);
2269            if (DEBUG_PACKAGE_INFO) Log.v(
2270                    TAG, "getApplicationInfo " + packageName
2271                    + ": " + p);
2272            if (p != null) {
2273                PackageSetting ps = mSettings.mPackages.get(packageName);
2274                if (ps == null) return null;
2275                // Note: isEnabledLP() does not apply here - always return info
2276                return PackageParser.generateApplicationInfo(
2277                        p, flags, ps.readUserState(userId), userId);
2278            }
2279            if ("android".equals(packageName)||"system".equals(packageName)) {
2280                return mAndroidApplication;
2281            }
2282            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2283                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2284            }
2285        }
2286        return null;
2287    }
2288
2289
2290    @Override
2291    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2292        mContext.enforceCallingOrSelfPermission(
2293                android.Manifest.permission.CLEAR_APP_CACHE, null);
2294        // Queue up an async operation since clearing cache may take a little while.
2295        mHandler.post(new Runnable() {
2296            public void run() {
2297                mHandler.removeCallbacks(this);
2298                int retCode = -1;
2299                synchronized (mInstallLock) {
2300                    retCode = mInstaller.freeCache(freeStorageSize);
2301                    if (retCode < 0) {
2302                        Slog.w(TAG, "Couldn't clear application caches");
2303                    }
2304                }
2305                if (observer != null) {
2306                    try {
2307                        observer.onRemoveCompleted(null, (retCode >= 0));
2308                    } catch (RemoteException e) {
2309                        Slog.w(TAG, "RemoveException when invoking call back");
2310                    }
2311                }
2312            }
2313        });
2314    }
2315
2316    @Override
2317    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2318        mContext.enforceCallingOrSelfPermission(
2319                android.Manifest.permission.CLEAR_APP_CACHE, null);
2320        // Queue up an async operation since clearing cache may take a little while.
2321        mHandler.post(new Runnable() {
2322            public void run() {
2323                mHandler.removeCallbacks(this);
2324                int retCode = -1;
2325                synchronized (mInstallLock) {
2326                    retCode = mInstaller.freeCache(freeStorageSize);
2327                    if (retCode < 0) {
2328                        Slog.w(TAG, "Couldn't clear application caches");
2329                    }
2330                }
2331                if(pi != null) {
2332                    try {
2333                        // Callback via pending intent
2334                        int code = (retCode >= 0) ? 1 : 0;
2335                        pi.sendIntent(null, code, null,
2336                                null, null);
2337                    } catch (SendIntentException e1) {
2338                        Slog.i(TAG, "Failed to send pending intent");
2339                    }
2340                }
2341            }
2342        });
2343    }
2344
2345    void freeStorage(long freeStorageSize) throws IOException {
2346        synchronized (mInstallLock) {
2347            if (mInstaller.freeCache(freeStorageSize) < 0) {
2348                throw new IOException("Failed to free enough space");
2349            }
2350        }
2351    }
2352
2353    @Override
2354    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2355        if (!sUserManager.exists(userId)) return null;
2356        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2357        synchronized (mPackages) {
2358            PackageParser.Activity a = mActivities.mActivities.get(component);
2359
2360            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2361            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2362                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2363                if (ps == null) return null;
2364                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2365                        userId);
2366            }
2367            if (mResolveComponentName.equals(component)) {
2368                return mResolveActivity;
2369            }
2370        }
2371        return null;
2372    }
2373
2374    @Override
2375    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2376            String resolvedType) {
2377        synchronized (mPackages) {
2378            PackageParser.Activity a = mActivities.mActivities.get(component);
2379            if (a == null) {
2380                return false;
2381            }
2382            for (int i=0; i<a.intents.size(); i++) {
2383                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2384                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2385                    return true;
2386                }
2387            }
2388            return false;
2389        }
2390    }
2391
2392    @Override
2393    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2394        if (!sUserManager.exists(userId)) return null;
2395        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2396        synchronized (mPackages) {
2397            PackageParser.Activity a = mReceivers.mActivities.get(component);
2398            if (DEBUG_PACKAGE_INFO) Log.v(
2399                TAG, "getReceiverInfo " + component + ": " + a);
2400            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2401                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2402                if (ps == null) return null;
2403                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2404                        userId);
2405            }
2406        }
2407        return null;
2408    }
2409
2410    @Override
2411    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2412        if (!sUserManager.exists(userId)) return null;
2413        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2414        synchronized (mPackages) {
2415            PackageParser.Service s = mServices.mServices.get(component);
2416            if (DEBUG_PACKAGE_INFO) Log.v(
2417                TAG, "getServiceInfo " + component + ": " + s);
2418            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2419                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2420                if (ps == null) return null;
2421                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2422                        userId);
2423            }
2424        }
2425        return null;
2426    }
2427
2428    @Override
2429    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2430        if (!sUserManager.exists(userId)) return null;
2431        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2432        synchronized (mPackages) {
2433            PackageParser.Provider p = mProviders.mProviders.get(component);
2434            if (DEBUG_PACKAGE_INFO) Log.v(
2435                TAG, "getProviderInfo " + component + ": " + p);
2436            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2437                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2438                if (ps == null) return null;
2439                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2440                        userId);
2441            }
2442        }
2443        return null;
2444    }
2445
2446    @Override
2447    public String[] getSystemSharedLibraryNames() {
2448        Set<String> libSet;
2449        synchronized (mPackages) {
2450            libSet = mSharedLibraries.keySet();
2451            int size = libSet.size();
2452            if (size > 0) {
2453                String[] libs = new String[size];
2454                libSet.toArray(libs);
2455                return libs;
2456            }
2457        }
2458        return null;
2459    }
2460
2461    @Override
2462    public FeatureInfo[] getSystemAvailableFeatures() {
2463        Collection<FeatureInfo> featSet;
2464        synchronized (mPackages) {
2465            featSet = mAvailableFeatures.values();
2466            int size = featSet.size();
2467            if (size > 0) {
2468                FeatureInfo[] features = new FeatureInfo[size+1];
2469                featSet.toArray(features);
2470                FeatureInfo fi = new FeatureInfo();
2471                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2472                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2473                features[size] = fi;
2474                return features;
2475            }
2476        }
2477        return null;
2478    }
2479
2480    @Override
2481    public boolean hasSystemFeature(String name) {
2482        synchronized (mPackages) {
2483            return mAvailableFeatures.containsKey(name);
2484        }
2485    }
2486
2487    private void checkValidCaller(int uid, int userId) {
2488        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2489            return;
2490
2491        throw new SecurityException("Caller uid=" + uid
2492                + " is not privileged to communicate with user=" + userId);
2493    }
2494
2495    @Override
2496    public int checkPermission(String permName, String pkgName) {
2497        synchronized (mPackages) {
2498            PackageParser.Package p = mPackages.get(pkgName);
2499            if (p != null && p.mExtras != null) {
2500                PackageSetting ps = (PackageSetting)p.mExtras;
2501                if (ps.sharedUser != null) {
2502                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2503                        return PackageManager.PERMISSION_GRANTED;
2504                    }
2505                } else if (ps.grantedPermissions.contains(permName)) {
2506                    return PackageManager.PERMISSION_GRANTED;
2507                }
2508            }
2509        }
2510        return PackageManager.PERMISSION_DENIED;
2511    }
2512
2513    @Override
2514    public int checkUidPermission(String permName, int uid) {
2515        synchronized (mPackages) {
2516            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2517            if (obj != null) {
2518                GrantedPermissions gp = (GrantedPermissions)obj;
2519                if (gp.grantedPermissions.contains(permName)) {
2520                    return PackageManager.PERMISSION_GRANTED;
2521                }
2522            } else {
2523                HashSet<String> perms = mSystemPermissions.get(uid);
2524                if (perms != null && perms.contains(permName)) {
2525                    return PackageManager.PERMISSION_GRANTED;
2526                }
2527            }
2528        }
2529        return PackageManager.PERMISSION_DENIED;
2530    }
2531
2532    /**
2533     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2534     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2535     * @param message the message to log on security exception
2536     */
2537    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2538            String message) {
2539        if (userId < 0) {
2540            throw new IllegalArgumentException("Invalid userId " + userId);
2541        }
2542        if (userId == UserHandle.getUserId(callingUid)) return;
2543        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2544            if (requireFullPermission) {
2545                mContext.enforceCallingOrSelfPermission(
2546                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2547            } else {
2548                try {
2549                    mContext.enforceCallingOrSelfPermission(
2550                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2551                } catch (SecurityException se) {
2552                    mContext.enforceCallingOrSelfPermission(
2553                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2554                }
2555            }
2556        }
2557    }
2558
2559    private BasePermission findPermissionTreeLP(String permName) {
2560        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2561            if (permName.startsWith(bp.name) &&
2562                    permName.length() > bp.name.length() &&
2563                    permName.charAt(bp.name.length()) == '.') {
2564                return bp;
2565            }
2566        }
2567        return null;
2568    }
2569
2570    private BasePermission checkPermissionTreeLP(String permName) {
2571        if (permName != null) {
2572            BasePermission bp = findPermissionTreeLP(permName);
2573            if (bp != null) {
2574                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2575                    return bp;
2576                }
2577                throw new SecurityException("Calling uid "
2578                        + Binder.getCallingUid()
2579                        + " is not allowed to add to permission tree "
2580                        + bp.name + " owned by uid " + bp.uid);
2581            }
2582        }
2583        throw new SecurityException("No permission tree found for " + permName);
2584    }
2585
2586    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2587        if (s1 == null) {
2588            return s2 == null;
2589        }
2590        if (s2 == null) {
2591            return false;
2592        }
2593        if (s1.getClass() != s2.getClass()) {
2594            return false;
2595        }
2596        return s1.equals(s2);
2597    }
2598
2599    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2600        if (pi1.icon != pi2.icon) return false;
2601        if (pi1.logo != pi2.logo) return false;
2602        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2603        if (!compareStrings(pi1.name, pi2.name)) return false;
2604        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2605        // We'll take care of setting this one.
2606        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2607        // These are not currently stored in settings.
2608        //if (!compareStrings(pi1.group, pi2.group)) return false;
2609        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2610        //if (pi1.labelRes != pi2.labelRes) return false;
2611        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2612        return true;
2613    }
2614
2615    int permissionInfoFootprint(PermissionInfo info) {
2616        int size = info.name.length();
2617        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2618        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2619        return size;
2620    }
2621
2622    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2623        int size = 0;
2624        for (BasePermission perm : mSettings.mPermissions.values()) {
2625            if (perm.uid == tree.uid) {
2626                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2627            }
2628        }
2629        return size;
2630    }
2631
2632    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2633        // We calculate the max size of permissions defined by this uid and throw
2634        // if that plus the size of 'info' would exceed our stated maximum.
2635        if (tree.uid != Process.SYSTEM_UID) {
2636            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2637            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2638                throw new SecurityException("Permission tree size cap exceeded");
2639            }
2640        }
2641    }
2642
2643    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2644        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2645            throw new SecurityException("Label must be specified in permission");
2646        }
2647        BasePermission tree = checkPermissionTreeLP(info.name);
2648        BasePermission bp = mSettings.mPermissions.get(info.name);
2649        boolean added = bp == null;
2650        boolean changed = true;
2651        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2652        if (added) {
2653            enforcePermissionCapLocked(info, tree);
2654            bp = new BasePermission(info.name, tree.sourcePackage,
2655                    BasePermission.TYPE_DYNAMIC);
2656        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2657            throw new SecurityException(
2658                    "Not allowed to modify non-dynamic permission "
2659                    + info.name);
2660        } else {
2661            if (bp.protectionLevel == fixedLevel
2662                    && bp.perm.owner.equals(tree.perm.owner)
2663                    && bp.uid == tree.uid
2664                    && comparePermissionInfos(bp.perm.info, info)) {
2665                changed = false;
2666            }
2667        }
2668        bp.protectionLevel = fixedLevel;
2669        info = new PermissionInfo(info);
2670        info.protectionLevel = fixedLevel;
2671        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2672        bp.perm.info.packageName = tree.perm.info.packageName;
2673        bp.uid = tree.uid;
2674        if (added) {
2675            mSettings.mPermissions.put(info.name, bp);
2676        }
2677        if (changed) {
2678            if (!async) {
2679                mSettings.writeLPr();
2680            } else {
2681                scheduleWriteSettingsLocked();
2682            }
2683        }
2684        return added;
2685    }
2686
2687    @Override
2688    public boolean addPermission(PermissionInfo info) {
2689        synchronized (mPackages) {
2690            return addPermissionLocked(info, false);
2691        }
2692    }
2693
2694    @Override
2695    public boolean addPermissionAsync(PermissionInfo info) {
2696        synchronized (mPackages) {
2697            return addPermissionLocked(info, true);
2698        }
2699    }
2700
2701    @Override
2702    public void removePermission(String name) {
2703        synchronized (mPackages) {
2704            checkPermissionTreeLP(name);
2705            BasePermission bp = mSettings.mPermissions.get(name);
2706            if (bp != null) {
2707                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2708                    throw new SecurityException(
2709                            "Not allowed to modify non-dynamic permission "
2710                            + name);
2711                }
2712                mSettings.mPermissions.remove(name);
2713                mSettings.writeLPr();
2714            }
2715        }
2716    }
2717
2718    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2719        int index = pkg.requestedPermissions.indexOf(bp.name);
2720        if (index == -1) {
2721            throw new SecurityException("Package " + pkg.packageName
2722                    + " has not requested permission " + bp.name);
2723        }
2724        boolean isNormal =
2725                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2726                        == PermissionInfo.PROTECTION_NORMAL);
2727        boolean isDangerous =
2728                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2729                        == PermissionInfo.PROTECTION_DANGEROUS);
2730        boolean isDevelopment =
2731                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2732
2733        if (!isNormal && !isDangerous && !isDevelopment) {
2734            throw new SecurityException("Permission " + bp.name
2735                    + " is not a changeable permission type");
2736        }
2737
2738        if (isNormal || isDangerous) {
2739            if (pkg.requestedPermissionsRequired.get(index)) {
2740                throw new SecurityException("Can't change " + bp.name
2741                        + ". It is required by the application");
2742            }
2743        }
2744    }
2745
2746    @Override
2747    public void grantPermission(String packageName, String permissionName) {
2748        mContext.enforceCallingOrSelfPermission(
2749                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2750        synchronized (mPackages) {
2751            final PackageParser.Package pkg = mPackages.get(packageName);
2752            if (pkg == null) {
2753                throw new IllegalArgumentException("Unknown package: " + packageName);
2754            }
2755            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2756            if (bp == null) {
2757                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2758            }
2759
2760            checkGrantRevokePermissions(pkg, bp);
2761
2762            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2763            if (ps == null) {
2764                return;
2765            }
2766            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2767            if (gp.grantedPermissions.add(permissionName)) {
2768                if (ps.haveGids) {
2769                    gp.gids = appendInts(gp.gids, bp.gids);
2770                }
2771                mSettings.writeLPr();
2772            }
2773        }
2774    }
2775
2776    @Override
2777    public void revokePermission(String packageName, String permissionName) {
2778        int changedAppId = -1;
2779
2780        synchronized (mPackages) {
2781            final PackageParser.Package pkg = mPackages.get(packageName);
2782            if (pkg == null) {
2783                throw new IllegalArgumentException("Unknown package: " + packageName);
2784            }
2785            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2786                mContext.enforceCallingOrSelfPermission(
2787                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2788            }
2789            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2790            if (bp == null) {
2791                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2792            }
2793
2794            checkGrantRevokePermissions(pkg, bp);
2795
2796            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2797            if (ps == null) {
2798                return;
2799            }
2800            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2801            if (gp.grantedPermissions.remove(permissionName)) {
2802                gp.grantedPermissions.remove(permissionName);
2803                if (ps.haveGids) {
2804                    gp.gids = removeInts(gp.gids, bp.gids);
2805                }
2806                mSettings.writeLPr();
2807                changedAppId = ps.appId;
2808            }
2809        }
2810
2811        if (changedAppId >= 0) {
2812            // We changed the perm on someone, kill its processes.
2813            IActivityManager am = ActivityManagerNative.getDefault();
2814            if (am != null) {
2815                final int callingUserId = UserHandle.getCallingUserId();
2816                final long ident = Binder.clearCallingIdentity();
2817                try {
2818                    //XXX we should only revoke for the calling user's app permissions,
2819                    // but for now we impact all users.
2820                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2821                    //        "revoke " + permissionName);
2822                    int[] users = sUserManager.getUserIds();
2823                    for (int user : users) {
2824                        am.killUid(UserHandle.getUid(user, changedAppId),
2825                                "revoke " + permissionName);
2826                    }
2827                } catch (RemoteException e) {
2828                } finally {
2829                    Binder.restoreCallingIdentity(ident);
2830                }
2831            }
2832        }
2833    }
2834
2835    @Override
2836    public boolean isProtectedBroadcast(String actionName) {
2837        synchronized (mPackages) {
2838            return mProtectedBroadcasts.contains(actionName);
2839        }
2840    }
2841
2842    @Override
2843    public int checkSignatures(String pkg1, String pkg2) {
2844        synchronized (mPackages) {
2845            final PackageParser.Package p1 = mPackages.get(pkg1);
2846            final PackageParser.Package p2 = mPackages.get(pkg2);
2847            if (p1 == null || p1.mExtras == null
2848                    || p2 == null || p2.mExtras == null) {
2849                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2850            }
2851            return compareSignatures(p1.mSignatures, p2.mSignatures);
2852        }
2853    }
2854
2855    @Override
2856    public int checkUidSignatures(int uid1, int uid2) {
2857        // Map to base uids.
2858        uid1 = UserHandle.getAppId(uid1);
2859        uid2 = UserHandle.getAppId(uid2);
2860        // reader
2861        synchronized (mPackages) {
2862            Signature[] s1;
2863            Signature[] s2;
2864            Object obj = mSettings.getUserIdLPr(uid1);
2865            if (obj != null) {
2866                if (obj instanceof SharedUserSetting) {
2867                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2868                } else if (obj instanceof PackageSetting) {
2869                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2870                } else {
2871                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2872                }
2873            } else {
2874                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2875            }
2876            obj = mSettings.getUserIdLPr(uid2);
2877            if (obj != null) {
2878                if (obj instanceof SharedUserSetting) {
2879                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2880                } else if (obj instanceof PackageSetting) {
2881                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2882                } else {
2883                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2884                }
2885            } else {
2886                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2887            }
2888            return compareSignatures(s1, s2);
2889        }
2890    }
2891
2892    /**
2893     * Compares two sets of signatures. Returns:
2894     * <br />
2895     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2896     * <br />
2897     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2898     * <br />
2899     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2900     * <br />
2901     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2902     * <br />
2903     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2904     */
2905    static int compareSignatures(Signature[] s1, Signature[] s2) {
2906        if (s1 == null) {
2907            return s2 == null
2908                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2909                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2910        }
2911
2912        if (s2 == null) {
2913            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2914        }
2915
2916        if (s1.length != s2.length) {
2917            return PackageManager.SIGNATURE_NO_MATCH;
2918        }
2919
2920        // Since both signature sets are of size 1, we can compare without HashSets.
2921        if (s1.length == 1) {
2922            return s1[0].equals(s2[0]) ?
2923                    PackageManager.SIGNATURE_MATCH :
2924                    PackageManager.SIGNATURE_NO_MATCH;
2925        }
2926
2927        HashSet<Signature> set1 = new HashSet<Signature>();
2928        for (Signature sig : s1) {
2929            set1.add(sig);
2930        }
2931        HashSet<Signature> set2 = new HashSet<Signature>();
2932        for (Signature sig : s2) {
2933            set2.add(sig);
2934        }
2935        // Make sure s2 contains all signatures in s1.
2936        if (set1.equals(set2)) {
2937            return PackageManager.SIGNATURE_MATCH;
2938        }
2939        return PackageManager.SIGNATURE_NO_MATCH;
2940    }
2941
2942    /**
2943     * If the database version for this type of package (internal storage or
2944     * external storage) is less than the version where package signatures
2945     * were updated, return true.
2946     */
2947    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2948        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2949                DatabaseVersion.SIGNATURE_END_ENTITY))
2950                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2951                        DatabaseVersion.SIGNATURE_END_ENTITY));
2952    }
2953
2954    /**
2955     * Used for backward compatibility to make sure any packages with
2956     * certificate chains get upgraded to the new style. {@code existingSigs}
2957     * will be in the old format (since they were stored on disk from before the
2958     * system upgrade) and {@code scannedSigs} will be in the newer format.
2959     */
2960    private int compareSignaturesCompat(PackageSignatures existingSigs,
2961            PackageParser.Package scannedPkg) {
2962        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2963            return PackageManager.SIGNATURE_NO_MATCH;
2964        }
2965
2966        HashSet<Signature> existingSet = new HashSet<Signature>();
2967        for (Signature sig : existingSigs.mSignatures) {
2968            existingSet.add(sig);
2969        }
2970        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2971        for (Signature sig : scannedPkg.mSignatures) {
2972            try {
2973                Signature[] chainSignatures = sig.getChainSignatures();
2974                for (Signature chainSig : chainSignatures) {
2975                    scannedCompatSet.add(chainSig);
2976                }
2977            } catch (CertificateEncodingException e) {
2978                scannedCompatSet.add(sig);
2979            }
2980        }
2981        /*
2982         * Make sure the expanded scanned set contains all signatures in the
2983         * existing one.
2984         */
2985        if (scannedCompatSet.equals(existingSet)) {
2986            // Migrate the old signatures to the new scheme.
2987            existingSigs.assignSignatures(scannedPkg.mSignatures);
2988            // The new KeySets will be re-added later in the scanning process.
2989            mSettings.mKeySetManager.removeAppKeySetData(scannedPkg.packageName);
2990            return PackageManager.SIGNATURE_MATCH;
2991        }
2992        return PackageManager.SIGNATURE_NO_MATCH;
2993    }
2994
2995    @Override
2996    public String[] getPackagesForUid(int uid) {
2997        uid = UserHandle.getAppId(uid);
2998        // reader
2999        synchronized (mPackages) {
3000            Object obj = mSettings.getUserIdLPr(uid);
3001            if (obj instanceof SharedUserSetting) {
3002                final SharedUserSetting sus = (SharedUserSetting) obj;
3003                final int N = sus.packages.size();
3004                final String[] res = new String[N];
3005                final Iterator<PackageSetting> it = sus.packages.iterator();
3006                int i = 0;
3007                while (it.hasNext()) {
3008                    res[i++] = it.next().name;
3009                }
3010                return res;
3011            } else if (obj instanceof PackageSetting) {
3012                final PackageSetting ps = (PackageSetting) obj;
3013                return new String[] { ps.name };
3014            }
3015        }
3016        return null;
3017    }
3018
3019    @Override
3020    public String getNameForUid(int uid) {
3021        // reader
3022        synchronized (mPackages) {
3023            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3024            if (obj instanceof SharedUserSetting) {
3025                final SharedUserSetting sus = (SharedUserSetting) obj;
3026                return sus.name + ":" + sus.userId;
3027            } else if (obj instanceof PackageSetting) {
3028                final PackageSetting ps = (PackageSetting) obj;
3029                return ps.name;
3030            }
3031        }
3032        return null;
3033    }
3034
3035    @Override
3036    public int getUidForSharedUser(String sharedUserName) {
3037        if(sharedUserName == null) {
3038            return -1;
3039        }
3040        // reader
3041        synchronized (mPackages) {
3042            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
3043            if (suid == null) {
3044                return -1;
3045            }
3046            return suid.userId;
3047        }
3048    }
3049
3050    @Override
3051    public int getFlagsForUid(int uid) {
3052        synchronized (mPackages) {
3053            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
3054            if (obj instanceof SharedUserSetting) {
3055                final SharedUserSetting sus = (SharedUserSetting) obj;
3056                return sus.pkgFlags;
3057            } else if (obj instanceof PackageSetting) {
3058                final PackageSetting ps = (PackageSetting) obj;
3059                return ps.pkgFlags;
3060            }
3061        }
3062        return 0;
3063    }
3064
3065    @Override
3066    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3067            int flags, int userId) {
3068        if (!sUserManager.exists(userId)) return null;
3069        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
3070        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3071        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3072    }
3073
3074    @Override
3075    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3076            IntentFilter filter, int match, ComponentName activity) {
3077        final int userId = UserHandle.getCallingUserId();
3078        if (DEBUG_PREFERRED) {
3079            Log.v(TAG, "setLastChosenActivity intent=" + intent
3080                + " resolvedType=" + resolvedType
3081                + " flags=" + flags
3082                + " filter=" + filter
3083                + " match=" + match
3084                + " activity=" + activity);
3085            filter.dump(new PrintStreamPrinter(System.out), "    ");
3086        }
3087        intent.setComponent(null);
3088        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3089        // Find any earlier preferred or last chosen entries and nuke them
3090        findPreferredActivity(intent, resolvedType,
3091                flags, query, 0, false, true, false, userId);
3092        // Add the new activity as the last chosen for this filter
3093        addPreferredActivityInternal(filter, match, null, activity, false, userId);
3094    }
3095
3096    @Override
3097    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3098        final int userId = UserHandle.getCallingUserId();
3099        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3100        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3101        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3102                false, false, false, userId);
3103    }
3104
3105    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3106            int flags, List<ResolveInfo> query, int userId) {
3107        if (query != null) {
3108            final int N = query.size();
3109            if (N == 1) {
3110                return query.get(0);
3111            } else if (N > 1) {
3112                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3113                // If there is more than one activity with the same priority,
3114                // then let the user decide between them.
3115                ResolveInfo r0 = query.get(0);
3116                ResolveInfo r1 = query.get(1);
3117                if (DEBUG_INTENT_MATCHING || debug) {
3118                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3119                            + r1.activityInfo.name + "=" + r1.priority);
3120                }
3121                // If the first activity has a higher priority, or a different
3122                // default, then it is always desireable to pick it.
3123                if (r0.priority != r1.priority
3124                        || r0.preferredOrder != r1.preferredOrder
3125                        || r0.isDefault != r1.isDefault) {
3126                    return query.get(0);
3127                }
3128                // If we have saved a preference for a preferred activity for
3129                // this Intent, use that.
3130                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3131                        flags, query, r0.priority, true, false, debug, userId);
3132                if (ri != null) {
3133                    return ri;
3134                }
3135                if (userId != 0) {
3136                    ri = new ResolveInfo(mResolveInfo);
3137                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3138                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3139                            ri.activityInfo.applicationInfo);
3140                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3141                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3142                    return ri;
3143                }
3144                return mResolveInfo;
3145            }
3146        }
3147        return null;
3148    }
3149
3150    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3151            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3152        final int N = query.size();
3153        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3154                .get(userId);
3155        // Get the list of persistent preferred activities that handle the intent
3156        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3157        List<PersistentPreferredActivity> pprefs = ppir != null
3158                ? ppir.queryIntent(intent, resolvedType,
3159                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3160                : null;
3161        if (pprefs != null && pprefs.size() > 0) {
3162            final int M = pprefs.size();
3163            for (int i=0; i<M; i++) {
3164                final PersistentPreferredActivity ppa = pprefs.get(i);
3165                if (DEBUG_PREFERRED || debug) {
3166                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3167                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3168                            + "\n  component=" + ppa.mComponent);
3169                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3170                }
3171                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3172                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3173                if (DEBUG_PREFERRED || debug) {
3174                    Slog.v(TAG, "Found persistent preferred activity:");
3175                    if (ai != null) {
3176                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3177                    } else {
3178                        Slog.v(TAG, "  null");
3179                    }
3180                }
3181                if (ai == null) {
3182                    // This previously registered persistent preferred activity
3183                    // component is no longer known. Ignore it and do NOT remove it.
3184                    continue;
3185                }
3186                for (int j=0; j<N; j++) {
3187                    final ResolveInfo ri = query.get(j);
3188                    if (!ri.activityInfo.applicationInfo.packageName
3189                            .equals(ai.applicationInfo.packageName)) {
3190                        continue;
3191                    }
3192                    if (!ri.activityInfo.name.equals(ai.name)) {
3193                        continue;
3194                    }
3195                    //  Found a persistent preference that can handle the intent.
3196                    if (DEBUG_PREFERRED || debug) {
3197                        Slog.v(TAG, "Returning persistent preferred activity: " +
3198                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3199                    }
3200                    return ri;
3201                }
3202            }
3203        }
3204        return null;
3205    }
3206
3207    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3208            List<ResolveInfo> query, int priority, boolean always,
3209            boolean removeMatches, boolean debug, int userId) {
3210        if (!sUserManager.exists(userId)) return null;
3211        // writer
3212        synchronized (mPackages) {
3213            if (intent.getSelector() != null) {
3214                intent = intent.getSelector();
3215            }
3216            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3217
3218            // Try to find a matching persistent preferred activity.
3219            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3220                    debug, userId);
3221
3222            // If a persistent preferred activity matched, use it.
3223            if (pri != null) {
3224                return pri;
3225            }
3226
3227            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3228            // Get the list of preferred activities that handle the intent
3229            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3230            List<PreferredActivity> prefs = pir != null
3231                    ? pir.queryIntent(intent, resolvedType,
3232                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3233                    : null;
3234            if (prefs != null && prefs.size() > 0) {
3235                // First figure out how good the original match set is.
3236                // We will only allow preferred activities that came
3237                // from the same match quality.
3238                int match = 0;
3239
3240                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3241
3242                final int N = query.size();
3243                for (int j=0; j<N; j++) {
3244                    final ResolveInfo ri = query.get(j);
3245                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3246                            + ": 0x" + Integer.toHexString(match));
3247                    if (ri.match > match) {
3248                        match = ri.match;
3249                    }
3250                }
3251
3252                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3253                        + Integer.toHexString(match));
3254
3255                match &= IntentFilter.MATCH_CATEGORY_MASK;
3256                final int M = prefs.size();
3257                for (int i=0; i<M; i++) {
3258                    final PreferredActivity pa = prefs.get(i);
3259                    if (DEBUG_PREFERRED || debug) {
3260                        Slog.v(TAG, "Checking PreferredActivity ds="
3261                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3262                                + "\n  component=" + pa.mPref.mComponent);
3263                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3264                    }
3265                    if (pa.mPref.mMatch != match) {
3266                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3267                                + Integer.toHexString(pa.mPref.mMatch));
3268                        continue;
3269                    }
3270                    // If it's not an "always" type preferred activity and that's what we're
3271                    // looking for, skip it.
3272                    if (always && !pa.mPref.mAlways) {
3273                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3274                        continue;
3275                    }
3276                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3277                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3278                    if (DEBUG_PREFERRED || debug) {
3279                        Slog.v(TAG, "Found preferred activity:");
3280                        if (ai != null) {
3281                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3282                        } else {
3283                            Slog.v(TAG, "  null");
3284                        }
3285                    }
3286                    if (ai == null) {
3287                        // This previously registered preferred activity
3288                        // component is no longer known.  Most likely an update
3289                        // to the app was installed and in the new version this
3290                        // component no longer exists.  Clean it up by removing
3291                        // it from the preferred activities list, and skip it.
3292                        Slog.w(TAG, "Removing dangling preferred activity: "
3293                                + pa.mPref.mComponent);
3294                        pir.removeFilter(pa);
3295                        continue;
3296                    }
3297                    for (int j=0; j<N; j++) {
3298                        final ResolveInfo ri = query.get(j);
3299                        if (!ri.activityInfo.applicationInfo.packageName
3300                                .equals(ai.applicationInfo.packageName)) {
3301                            continue;
3302                        }
3303                        if (!ri.activityInfo.name.equals(ai.name)) {
3304                            continue;
3305                        }
3306
3307                        if (removeMatches) {
3308                            pir.removeFilter(pa);
3309                            if (DEBUG_PREFERRED) {
3310                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3311                            }
3312                            break;
3313                        }
3314
3315                        // Okay we found a previously set preferred or last chosen app.
3316                        // If the result set is different from when this
3317                        // was created, we need to clear it and re-ask the
3318                        // user their preference, if we're looking for an "always" type entry.
3319                        if (always && !pa.mPref.sameSet(query, priority)) {
3320                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3321                                    + intent + " type " + resolvedType);
3322                            if (DEBUG_PREFERRED) {
3323                                Slog.v(TAG, "Removing preferred activity since set changed "
3324                                        + pa.mPref.mComponent);
3325                            }
3326                            pir.removeFilter(pa);
3327                            // Re-add the filter as a "last chosen" entry (!always)
3328                            PreferredActivity lastChosen = new PreferredActivity(
3329                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3330                            pir.addFilter(lastChosen);
3331                            mSettings.writePackageRestrictionsLPr(userId);
3332                            return null;
3333                        }
3334
3335                        // Yay! Either the set matched or we're looking for the last chosen
3336                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3337                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3338                        mSettings.writePackageRestrictionsLPr(userId);
3339                        return ri;
3340                    }
3341                }
3342            }
3343            mSettings.writePackageRestrictionsLPr(userId);
3344        }
3345        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3346        return null;
3347    }
3348
3349    /*
3350     * Returns if intent can be forwarded from the userId from to dest
3351     */
3352    @Override
3353    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3354            int targetUserId) {
3355        mContext.enforceCallingOrSelfPermission(
3356                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3357        List<CrossProfileIntentFilter> matches =
3358                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3359        if (matches != null) {
3360            int size = matches.size();
3361            for (int i = 0; i < size; i++) {
3362                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3363            }
3364        }
3365        return false;
3366    }
3367
3368    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3369            String resolvedType, int userId) {
3370        CrossProfileIntentResolver cpir = mSettings.mCrossProfileIntentResolvers.get(userId);
3371        if (cpir != null) {
3372            return cpir.queryIntent(intent, resolvedType, false, userId);
3373        }
3374        return null;
3375    }
3376
3377    @Override
3378    public List<ResolveInfo> queryIntentActivities(Intent intent,
3379            String resolvedType, int flags, int userId) {
3380        if (!sUserManager.exists(userId)) return Collections.emptyList();
3381        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3382        ComponentName comp = intent.getComponent();
3383        if (comp == null) {
3384            if (intent.getSelector() != null) {
3385                intent = intent.getSelector();
3386                comp = intent.getComponent();
3387            }
3388        }
3389
3390        if (comp != null) {
3391            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3392            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3393            if (ai != null) {
3394                final ResolveInfo ri = new ResolveInfo();
3395                ri.activityInfo = ai;
3396                list.add(ri);
3397            }
3398            return list;
3399        }
3400
3401        // reader
3402        synchronized (mPackages) {
3403            final String pkgName = intent.getPackage();
3404            if (pkgName == null) {
3405                List<ResolveInfo> result =
3406                        mActivities.queryIntent(intent, resolvedType, flags, userId);
3407                // Checking if we can forward the intent to another user
3408                List<CrossProfileIntentFilter> cpifs =
3409                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3410                if (cpifs != null) {
3411                    CrossProfileIntentFilter crossProfileIntentFilterWithResult = null;
3412                    HashSet<Integer> alreadyTriedUserIds = new HashSet<Integer>();
3413                    for (CrossProfileIntentFilter cpif : cpifs) {
3414                        int targetUserId = cpif.getTargetUserId();
3415                        // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3416                        // match the same an intent. For performance reasons, it is better not to
3417                        // run queryIntent twice for the same userId
3418                        if (!alreadyTriedUserIds.contains(targetUserId)) {
3419                            List<ResolveInfo> resultUser = mActivities.queryIntent(intent,
3420                                    resolvedType, flags, targetUserId);
3421                            if (resultUser != null) {
3422                                crossProfileIntentFilterWithResult = cpif;
3423                                // As soon as there is a match in another user, we add the
3424                                // intentForwarderActivity to the list of ResolveInfo.
3425                                break;
3426                            }
3427                            alreadyTriedUserIds.add(targetUserId);
3428                        }
3429                    }
3430                    if (crossProfileIntentFilterWithResult != null) {
3431                        ResolveInfo forwardingResolveInfo = createForwardingResolveInfo(
3432                                crossProfileIntentFilterWithResult, userId);
3433                        result.add(forwardingResolveInfo);
3434                    }
3435                }
3436                return result;
3437            }
3438            final PackageParser.Package pkg = mPackages.get(pkgName);
3439            if (pkg != null) {
3440                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3441                        pkg.activities, userId);
3442            }
3443            return new ArrayList<ResolveInfo>();
3444        }
3445    }
3446
3447    private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter cpif,
3448            int sourceUserId) {
3449        String className;
3450        int targetUserId = cpif.getTargetUserId();
3451        if (targetUserId == UserHandle.USER_OWNER) {
3452            className = FORWARD_INTENT_TO_USER_OWNER;
3453        } else {
3454            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3455        }
3456        ComponentName forwardingActivityComponentName = new ComponentName(
3457                mAndroidApplication.packageName, className);
3458        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3459                sourceUserId);
3460        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3461        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3462        forwardingResolveInfo.priority = 0;
3463        forwardingResolveInfo.preferredOrder = 0;
3464        forwardingResolveInfo.match = 0;
3465        forwardingResolveInfo.isDefault = true;
3466        forwardingResolveInfo.filter = cpif;
3467        return forwardingResolveInfo;
3468    }
3469
3470    @Override
3471    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3472            Intent[] specifics, String[] specificTypes, Intent intent,
3473            String resolvedType, int flags, int userId) {
3474        if (!sUserManager.exists(userId)) return Collections.emptyList();
3475        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3476                "query intent activity options");
3477        final String resultsAction = intent.getAction();
3478
3479        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3480                | PackageManager.GET_RESOLVED_FILTER, userId);
3481
3482        if (DEBUG_INTENT_MATCHING) {
3483            Log.v(TAG, "Query " + intent + ": " + results);
3484        }
3485
3486        int specificsPos = 0;
3487        int N;
3488
3489        // todo: note that the algorithm used here is O(N^2).  This
3490        // isn't a problem in our current environment, but if we start running
3491        // into situations where we have more than 5 or 10 matches then this
3492        // should probably be changed to something smarter...
3493
3494        // First we go through and resolve each of the specific items
3495        // that were supplied, taking care of removing any corresponding
3496        // duplicate items in the generic resolve list.
3497        if (specifics != null) {
3498            for (int i=0; i<specifics.length; i++) {
3499                final Intent sintent = specifics[i];
3500                if (sintent == null) {
3501                    continue;
3502                }
3503
3504                if (DEBUG_INTENT_MATCHING) {
3505                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3506                }
3507
3508                String action = sintent.getAction();
3509                if (resultsAction != null && resultsAction.equals(action)) {
3510                    // If this action was explicitly requested, then don't
3511                    // remove things that have it.
3512                    action = null;
3513                }
3514
3515                ResolveInfo ri = null;
3516                ActivityInfo ai = null;
3517
3518                ComponentName comp = sintent.getComponent();
3519                if (comp == null) {
3520                    ri = resolveIntent(
3521                        sintent,
3522                        specificTypes != null ? specificTypes[i] : null,
3523                            flags, userId);
3524                    if (ri == null) {
3525                        continue;
3526                    }
3527                    if (ri == mResolveInfo) {
3528                        // ACK!  Must do something better with this.
3529                    }
3530                    ai = ri.activityInfo;
3531                    comp = new ComponentName(ai.applicationInfo.packageName,
3532                            ai.name);
3533                } else {
3534                    ai = getActivityInfo(comp, flags, userId);
3535                    if (ai == null) {
3536                        continue;
3537                    }
3538                }
3539
3540                // Look for any generic query activities that are duplicates
3541                // of this specific one, and remove them from the results.
3542                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3543                N = results.size();
3544                int j;
3545                for (j=specificsPos; j<N; j++) {
3546                    ResolveInfo sri = results.get(j);
3547                    if ((sri.activityInfo.name.equals(comp.getClassName())
3548                            && sri.activityInfo.applicationInfo.packageName.equals(
3549                                    comp.getPackageName()))
3550                        || (action != null && sri.filter.matchAction(action))) {
3551                        results.remove(j);
3552                        if (DEBUG_INTENT_MATCHING) Log.v(
3553                            TAG, "Removing duplicate item from " + j
3554                            + " due to specific " + specificsPos);
3555                        if (ri == null) {
3556                            ri = sri;
3557                        }
3558                        j--;
3559                        N--;
3560                    }
3561                }
3562
3563                // Add this specific item to its proper place.
3564                if (ri == null) {
3565                    ri = new ResolveInfo();
3566                    ri.activityInfo = ai;
3567                }
3568                results.add(specificsPos, ri);
3569                ri.specificIndex = i;
3570                specificsPos++;
3571            }
3572        }
3573
3574        // Now we go through the remaining generic results and remove any
3575        // duplicate actions that are found here.
3576        N = results.size();
3577        for (int i=specificsPos; i<N-1; i++) {
3578            final ResolveInfo rii = results.get(i);
3579            if (rii.filter == null) {
3580                continue;
3581            }
3582
3583            // Iterate over all of the actions of this result's intent
3584            // filter...  typically this should be just one.
3585            final Iterator<String> it = rii.filter.actionsIterator();
3586            if (it == null) {
3587                continue;
3588            }
3589            while (it.hasNext()) {
3590                final String action = it.next();
3591                if (resultsAction != null && resultsAction.equals(action)) {
3592                    // If this action was explicitly requested, then don't
3593                    // remove things that have it.
3594                    continue;
3595                }
3596                for (int j=i+1; j<N; j++) {
3597                    final ResolveInfo rij = results.get(j);
3598                    if (rij.filter != null && rij.filter.hasAction(action)) {
3599                        results.remove(j);
3600                        if (DEBUG_INTENT_MATCHING) Log.v(
3601                            TAG, "Removing duplicate item from " + j
3602                            + " due to action " + action + " at " + i);
3603                        j--;
3604                        N--;
3605                    }
3606                }
3607            }
3608
3609            // If the caller didn't request filter information, drop it now
3610            // so we don't have to marshall/unmarshall it.
3611            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3612                rii.filter = null;
3613            }
3614        }
3615
3616        // Filter out the caller activity if so requested.
3617        if (caller != null) {
3618            N = results.size();
3619            for (int i=0; i<N; i++) {
3620                ActivityInfo ainfo = results.get(i).activityInfo;
3621                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3622                        && caller.getClassName().equals(ainfo.name)) {
3623                    results.remove(i);
3624                    break;
3625                }
3626            }
3627        }
3628
3629        // If the caller didn't request filter information,
3630        // drop them now so we don't have to
3631        // marshall/unmarshall it.
3632        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3633            N = results.size();
3634            for (int i=0; i<N; i++) {
3635                results.get(i).filter = null;
3636            }
3637        }
3638
3639        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3640        return results;
3641    }
3642
3643    @Override
3644    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3645            int userId) {
3646        if (!sUserManager.exists(userId)) return Collections.emptyList();
3647        ComponentName comp = intent.getComponent();
3648        if (comp == null) {
3649            if (intent.getSelector() != null) {
3650                intent = intent.getSelector();
3651                comp = intent.getComponent();
3652            }
3653        }
3654        if (comp != null) {
3655            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3656            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3657            if (ai != null) {
3658                ResolveInfo ri = new ResolveInfo();
3659                ri.activityInfo = ai;
3660                list.add(ri);
3661            }
3662            return list;
3663        }
3664
3665        // reader
3666        synchronized (mPackages) {
3667            String pkgName = intent.getPackage();
3668            if (pkgName == null) {
3669                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3670            }
3671            final PackageParser.Package pkg = mPackages.get(pkgName);
3672            if (pkg != null) {
3673                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3674                        userId);
3675            }
3676            return null;
3677        }
3678    }
3679
3680    @Override
3681    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3682        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3683        if (!sUserManager.exists(userId)) return null;
3684        if (query != null) {
3685            if (query.size() >= 1) {
3686                // If there is more than one service with the same priority,
3687                // just arbitrarily pick the first one.
3688                return query.get(0);
3689            }
3690        }
3691        return null;
3692    }
3693
3694    @Override
3695    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3696            int userId) {
3697        if (!sUserManager.exists(userId)) return Collections.emptyList();
3698        ComponentName comp = intent.getComponent();
3699        if (comp == null) {
3700            if (intent.getSelector() != null) {
3701                intent = intent.getSelector();
3702                comp = intent.getComponent();
3703            }
3704        }
3705        if (comp != null) {
3706            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3707            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3708            if (si != null) {
3709                final ResolveInfo ri = new ResolveInfo();
3710                ri.serviceInfo = si;
3711                list.add(ri);
3712            }
3713            return list;
3714        }
3715
3716        // reader
3717        synchronized (mPackages) {
3718            String pkgName = intent.getPackage();
3719            if (pkgName == null) {
3720                return mServices.queryIntent(intent, resolvedType, flags, userId);
3721            }
3722            final PackageParser.Package pkg = mPackages.get(pkgName);
3723            if (pkg != null) {
3724                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3725                        userId);
3726            }
3727            return null;
3728        }
3729    }
3730
3731    @Override
3732    public List<ResolveInfo> queryIntentContentProviders(
3733            Intent intent, String resolvedType, int flags, int userId) {
3734        if (!sUserManager.exists(userId)) return Collections.emptyList();
3735        ComponentName comp = intent.getComponent();
3736        if (comp == null) {
3737            if (intent.getSelector() != null) {
3738                intent = intent.getSelector();
3739                comp = intent.getComponent();
3740            }
3741        }
3742        if (comp != null) {
3743            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3744            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3745            if (pi != null) {
3746                final ResolveInfo ri = new ResolveInfo();
3747                ri.providerInfo = pi;
3748                list.add(ri);
3749            }
3750            return list;
3751        }
3752
3753        // reader
3754        synchronized (mPackages) {
3755            String pkgName = intent.getPackage();
3756            if (pkgName == null) {
3757                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3758            }
3759            final PackageParser.Package pkg = mPackages.get(pkgName);
3760            if (pkg != null) {
3761                return mProviders.queryIntentForPackage(
3762                        intent, resolvedType, flags, pkg.providers, userId);
3763            }
3764            return null;
3765        }
3766    }
3767
3768    @Override
3769    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3770        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3771
3772        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3773
3774        // writer
3775        synchronized (mPackages) {
3776            ArrayList<PackageInfo> list;
3777            if (listUninstalled) {
3778                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3779                for (PackageSetting ps : mSettings.mPackages.values()) {
3780                    PackageInfo pi;
3781                    if (ps.pkg != null) {
3782                        pi = generatePackageInfo(ps.pkg, flags, userId);
3783                    } else {
3784                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3785                    }
3786                    if (pi != null) {
3787                        list.add(pi);
3788                    }
3789                }
3790            } else {
3791                list = new ArrayList<PackageInfo>(mPackages.size());
3792                for (PackageParser.Package p : mPackages.values()) {
3793                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3794                    if (pi != null) {
3795                        list.add(pi);
3796                    }
3797                }
3798            }
3799
3800            return new ParceledListSlice<PackageInfo>(list);
3801        }
3802    }
3803
3804    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3805            String[] permissions, boolean[] tmp, int flags, int userId) {
3806        int numMatch = 0;
3807        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3808        for (int i=0; i<permissions.length; i++) {
3809            if (gp.grantedPermissions.contains(permissions[i])) {
3810                tmp[i] = true;
3811                numMatch++;
3812            } else {
3813                tmp[i] = false;
3814            }
3815        }
3816        if (numMatch == 0) {
3817            return;
3818        }
3819        PackageInfo pi;
3820        if (ps.pkg != null) {
3821            pi = generatePackageInfo(ps.pkg, flags, userId);
3822        } else {
3823            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3824        }
3825        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3826            if (numMatch == permissions.length) {
3827                pi.requestedPermissions = permissions;
3828            } else {
3829                pi.requestedPermissions = new String[numMatch];
3830                numMatch = 0;
3831                for (int i=0; i<permissions.length; i++) {
3832                    if (tmp[i]) {
3833                        pi.requestedPermissions[numMatch] = permissions[i];
3834                        numMatch++;
3835                    }
3836                }
3837            }
3838        }
3839        list.add(pi);
3840    }
3841
3842    @Override
3843    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3844            String[] permissions, int flags, int userId) {
3845        if (!sUserManager.exists(userId)) return null;
3846        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3847
3848        // writer
3849        synchronized (mPackages) {
3850            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3851            boolean[] tmpBools = new boolean[permissions.length];
3852            if (listUninstalled) {
3853                for (PackageSetting ps : mSettings.mPackages.values()) {
3854                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3855                }
3856            } else {
3857                for (PackageParser.Package pkg : mPackages.values()) {
3858                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3859                    if (ps != null) {
3860                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3861                                userId);
3862                    }
3863                }
3864            }
3865
3866            return new ParceledListSlice<PackageInfo>(list);
3867        }
3868    }
3869
3870    @Override
3871    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3872        if (!sUserManager.exists(userId)) return null;
3873        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3874
3875        // writer
3876        synchronized (mPackages) {
3877            ArrayList<ApplicationInfo> list;
3878            if (listUninstalled) {
3879                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3880                for (PackageSetting ps : mSettings.mPackages.values()) {
3881                    ApplicationInfo ai;
3882                    if (ps.pkg != null) {
3883                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3884                                ps.readUserState(userId), userId);
3885                    } else {
3886                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3887                    }
3888                    if (ai != null) {
3889                        list.add(ai);
3890                    }
3891                }
3892            } else {
3893                list = new ArrayList<ApplicationInfo>(mPackages.size());
3894                for (PackageParser.Package p : mPackages.values()) {
3895                    if (p.mExtras != null) {
3896                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3897                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3898                        if (ai != null) {
3899                            list.add(ai);
3900                        }
3901                    }
3902                }
3903            }
3904
3905            return new ParceledListSlice<ApplicationInfo>(list);
3906        }
3907    }
3908
3909    public List<ApplicationInfo> getPersistentApplications(int flags) {
3910        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3911
3912        // reader
3913        synchronized (mPackages) {
3914            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3915            final int userId = UserHandle.getCallingUserId();
3916            while (i.hasNext()) {
3917                final PackageParser.Package p = i.next();
3918                if (p.applicationInfo != null
3919                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3920                        && (!mSafeMode || isSystemApp(p))) {
3921                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3922                    if (ps != null) {
3923                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3924                                ps.readUserState(userId), userId);
3925                        if (ai != null) {
3926                            finalList.add(ai);
3927                        }
3928                    }
3929                }
3930            }
3931        }
3932
3933        return finalList;
3934    }
3935
3936    @Override
3937    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3938        if (!sUserManager.exists(userId)) return null;
3939        // reader
3940        synchronized (mPackages) {
3941            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3942            PackageSetting ps = provider != null
3943                    ? mSettings.mPackages.get(provider.owner.packageName)
3944                    : null;
3945            return ps != null
3946                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3947                    && (!mSafeMode || (provider.info.applicationInfo.flags
3948                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3949                    ? PackageParser.generateProviderInfo(provider, flags,
3950                            ps.readUserState(userId), userId)
3951                    : null;
3952        }
3953    }
3954
3955    /**
3956     * @deprecated
3957     */
3958    @Deprecated
3959    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3960        // reader
3961        synchronized (mPackages) {
3962            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3963                    .entrySet().iterator();
3964            final int userId = UserHandle.getCallingUserId();
3965            while (i.hasNext()) {
3966                Map.Entry<String, PackageParser.Provider> entry = i.next();
3967                PackageParser.Provider p = entry.getValue();
3968                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3969
3970                if (ps != null && p.syncable
3971                        && (!mSafeMode || (p.info.applicationInfo.flags
3972                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3973                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3974                            ps.readUserState(userId), userId);
3975                    if (info != null) {
3976                        outNames.add(entry.getKey());
3977                        outInfo.add(info);
3978                    }
3979                }
3980            }
3981        }
3982    }
3983
3984    @Override
3985    public List<ProviderInfo> queryContentProviders(String processName,
3986            int uid, int flags) {
3987        ArrayList<ProviderInfo> finalList = null;
3988        // reader
3989        synchronized (mPackages) {
3990            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3991            final int userId = processName != null ?
3992                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3993            while (i.hasNext()) {
3994                final PackageParser.Provider p = i.next();
3995                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3996                if (ps != null && p.info.authority != null
3997                        && (processName == null
3998                                || (p.info.processName.equals(processName)
3999                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4000                        && mSettings.isEnabledLPr(p.info, flags, userId)
4001                        && (!mSafeMode
4002                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4003                    if (finalList == null) {
4004                        finalList = new ArrayList<ProviderInfo>(3);
4005                    }
4006                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4007                            ps.readUserState(userId), userId);
4008                    if (info != null) {
4009                        finalList.add(info);
4010                    }
4011                }
4012            }
4013        }
4014
4015        if (finalList != null) {
4016            Collections.sort(finalList, mProviderInitOrderSorter);
4017        }
4018
4019        return finalList;
4020    }
4021
4022    @Override
4023    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4024            int flags) {
4025        // reader
4026        synchronized (mPackages) {
4027            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4028            return PackageParser.generateInstrumentationInfo(i, flags);
4029        }
4030    }
4031
4032    @Override
4033    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4034            int flags) {
4035        ArrayList<InstrumentationInfo> finalList =
4036            new ArrayList<InstrumentationInfo>();
4037
4038        // reader
4039        synchronized (mPackages) {
4040            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4041            while (i.hasNext()) {
4042                final PackageParser.Instrumentation p = i.next();
4043                if (targetPackage == null
4044                        || targetPackage.equals(p.info.targetPackage)) {
4045                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4046                            flags);
4047                    if (ii != null) {
4048                        finalList.add(ii);
4049                    }
4050                }
4051            }
4052        }
4053
4054        return finalList;
4055    }
4056
4057    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4058        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4059        if (overlays == null) {
4060            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4061            return;
4062        }
4063        for (PackageParser.Package opkg : overlays.values()) {
4064            // Not much to do if idmap fails: we already logged the error
4065            // and we certainly don't want to abort installation of pkg simply
4066            // because an overlay didn't fit properly. For these reasons,
4067            // ignore the return value of createIdmapForPackagePairLI.
4068            createIdmapForPackagePairLI(pkg, opkg);
4069        }
4070    }
4071
4072    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4073            PackageParser.Package opkg) {
4074        if (!opkg.mTrustedOverlay) {
4075            Slog.w(TAG, "Skipping target and overlay pair " + pkg.codePath + " and " +
4076                    opkg.codePath + ": overlay not trusted");
4077            return false;
4078        }
4079        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4080        if (overlaySet == null) {
4081            Slog.e(TAG, "was about to create idmap for " + pkg.codePath + " and " +
4082                    opkg.codePath + " but target package has no known overlays");
4083            return false;
4084        }
4085        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4086        // TODO: generate idmap for split APKs
4087        if (mInstaller.idmap(pkg.codePath, opkg.codePath, sharedGid) != 0) {
4088            Slog.e(TAG, "Failed to generate idmap for " + pkg.codePath + " and " + opkg.codePath);
4089            return false;
4090        }
4091        PackageParser.Package[] overlayArray =
4092            overlaySet.values().toArray(new PackageParser.Package[0]);
4093        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4094            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4095                return p1.mOverlayPriority - p2.mOverlayPriority;
4096            }
4097        };
4098        Arrays.sort(overlayArray, cmp);
4099
4100        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4101        int i = 0;
4102        for (PackageParser.Package p : overlayArray) {
4103            pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir;
4104        }
4105        return true;
4106    }
4107
4108    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4109        String[] files = dir.list();
4110        if (files == null) {
4111            Log.d(TAG, "No files in app dir " + dir);
4112            return;
4113        }
4114
4115        if (DEBUG_PACKAGE_SCANNING) {
4116            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4117                    + " flags=0x" + Integer.toHexString(flags));
4118        }
4119
4120        int i;
4121        for (i=0; i<files.length; i++) {
4122            File file = new File(dir, files[i]);
4123            if (!isPackageFilename(files[i])) {
4124                // Ignore entries which are not apk's
4125                continue;
4126            }
4127            PackageParser.Package pkg = scanPackageLI(file,
4128                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null);
4129            // Don't mess around with apps in system partition.
4130            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4131                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
4132                // Delete the apk
4133                Slog.w(TAG, "Cleaning up failed install of " + file);
4134                file.delete();
4135            }
4136        }
4137    }
4138
4139    private static File getSettingsProblemFile() {
4140        File dataDir = Environment.getDataDirectory();
4141        File systemDir = new File(dataDir, "system");
4142        File fname = new File(systemDir, "uiderrors.txt");
4143        return fname;
4144    }
4145
4146    static void reportSettingsProblem(int priority, String msg) {
4147        try {
4148            File fname = getSettingsProblemFile();
4149            FileOutputStream out = new FileOutputStream(fname, true);
4150            PrintWriter pw = new FastPrintWriter(out);
4151            SimpleDateFormat formatter = new SimpleDateFormat();
4152            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4153            pw.println(dateString + ": " + msg);
4154            pw.close();
4155            FileUtils.setPermissions(
4156                    fname.toString(),
4157                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4158                    -1, -1);
4159        } catch (java.io.IOException e) {
4160        }
4161        Slog.println(priority, TAG, msg);
4162    }
4163
4164    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
4165            PackageParser.Package pkg, File srcFile, int parseFlags) {
4166        if (ps != null
4167                && ps.codePath.equals(srcFile)
4168                && ps.timeStamp == srcFile.lastModified()
4169                && !isCompatSignatureUpdateNeeded(pkg)) {
4170            if (ps.signatures.mSignatures != null
4171                    && ps.signatures.mSignatures.length != 0) {
4172                // Optimization: reuse the existing cached certificates
4173                // if the package appears to be unchanged.
4174                pkg.mSignatures = ps.signatures.mSignatures;
4175                return true;
4176            }
4177
4178            Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
4179        } else {
4180            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4181        }
4182
4183        try {
4184            pp.collectCertificates(pkg, parseFlags);
4185            pp.collectManifestDigest(pkg);
4186        } catch (PackageParserException e) {
4187            mLastScanError = e.error;
4188            return false;
4189        }
4190        return true;
4191    }
4192
4193    /*
4194     *  Scan a package and return the newly parsed package.
4195     *  Returns null in case of errors and the error code is stored in mLastScanError
4196     */
4197    private PackageParser.Package scanPackageLI(File scanFile,
4198            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
4199        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4200        String scanPath = scanFile.getPath();
4201        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
4202        parseFlags |= mDefParseFlags;
4203        PackageParser pp = new PackageParser();
4204        pp.setSeparateProcesses(mSeparateProcesses);
4205        pp.setOnlyCoreApps(mOnlyCore);
4206        pp.setDisplayMetrics(mMetrics);
4207
4208        if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) {
4209            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4210        }
4211
4212        final PackageParser.Package pkg;
4213        try {
4214            pkg = pp.parseMonolithicPackage(scanFile, parseFlags);
4215        } catch (PackageParserException e) {
4216            mLastScanError = e.error;
4217            return null;
4218        }
4219
4220        PackageSetting ps = null;
4221        PackageSetting updatedPkg;
4222        // reader
4223        synchronized (mPackages) {
4224            // Look to see if we already know about this package.
4225            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4226            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4227                // This package has been renamed to its original name.  Let's
4228                // use that.
4229                ps = mSettings.peekPackageLPr(oldName);
4230            }
4231            // If there was no original package, see one for the real package name.
4232            if (ps == null) {
4233                ps = mSettings.peekPackageLPr(pkg.packageName);
4234            }
4235            // Check to see if this package could be hiding/updating a system
4236            // package.  Must look for it either under the original or real
4237            // package name depending on our state.
4238            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4239            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4240        }
4241        boolean updatedPkgBetter = false;
4242        // First check if this is a system package that may involve an update
4243        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4244            if (ps != null && !ps.codePath.equals(scanFile)) {
4245                // The path has changed from what was last scanned...  check the
4246                // version of the new path against what we have stored to determine
4247                // what to do.
4248                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4249                if (pkg.mVersionCode < ps.versionCode) {
4250                    // The system package has been updated and the code path does not match
4251                    // Ignore entry. Skip it.
4252                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4253                            + " ignored: updated version " + ps.versionCode
4254                            + " better than this " + pkg.mVersionCode);
4255                    if (!updatedPkg.codePath.equals(scanFile)) {
4256                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4257                                + ps.name + " changing from " + updatedPkg.codePathString
4258                                + " to " + scanFile);
4259                        updatedPkg.codePath = scanFile;
4260                        updatedPkg.codePathString = scanFile.toString();
4261                        // This is the point at which we know that the system-disk APK
4262                        // for this package has moved during a reboot (e.g. due to an OTA),
4263                        // so we need to reevaluate it for privilege policy.
4264                        if (locationIsPrivileged(scanFile)) {
4265                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4266                        }
4267                    }
4268                    updatedPkg.pkg = pkg;
4269                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4270                    return null;
4271                } else {
4272                    // The current app on the system partition is better than
4273                    // what we have updated to on the data partition; switch
4274                    // back to the system partition version.
4275                    // At this point, its safely assumed that package installation for
4276                    // apps in system partition will go through. If not there won't be a working
4277                    // version of the app
4278                    // writer
4279                    synchronized (mPackages) {
4280                        // Just remove the loaded entries from package lists.
4281                        mPackages.remove(ps.name);
4282                    }
4283                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4284                            + "reverting from " + ps.codePathString
4285                            + ": new version " + pkg.mVersionCode
4286                            + " better than installed " + ps.versionCode);
4287
4288                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4289                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4290                            getAppInstructionSetFromSettings(ps));
4291                    synchronized (mInstallLock) {
4292                        args.cleanUpResourcesLI();
4293                    }
4294                    synchronized (mPackages) {
4295                        mSettings.enableSystemPackageLPw(ps.name);
4296                    }
4297                    updatedPkgBetter = true;
4298                }
4299            }
4300        }
4301
4302        if (updatedPkg != null) {
4303            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4304            // initially
4305            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4306
4307            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4308            // flag set initially
4309            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4310                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4311            }
4312        }
4313        // Verify certificates against what was last scanned
4314        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
4315            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
4316            return null;
4317        }
4318
4319        /*
4320         * A new system app appeared, but we already had a non-system one of the
4321         * same name installed earlier.
4322         */
4323        boolean shouldHideSystemApp = false;
4324        if (updatedPkg == null && ps != null
4325                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4326            /*
4327             * Check to make sure the signatures match first. If they don't,
4328             * wipe the installed application and its data.
4329             */
4330            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4331                    != PackageManager.SIGNATURE_MATCH) {
4332                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4333                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4334                ps = null;
4335            } else {
4336                /*
4337                 * If the newly-added system app is an older version than the
4338                 * already installed version, hide it. It will be scanned later
4339                 * and re-added like an update.
4340                 */
4341                if (pkg.mVersionCode < ps.versionCode) {
4342                    shouldHideSystemApp = true;
4343                } else {
4344                    /*
4345                     * The newly found system app is a newer version that the
4346                     * one previously installed. Simply remove the
4347                     * already-installed application and replace it with our own
4348                     * while keeping the application data.
4349                     */
4350                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4351                            + ps.codePathString + ": new version " + pkg.mVersionCode
4352                            + " better than installed " + ps.versionCode);
4353                    InstallArgs args = createInstallArgs(packageFlagsToInstallFlags(ps),
4354                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4355                            getAppInstructionSetFromSettings(ps));
4356                    synchronized (mInstallLock) {
4357                        args.cleanUpResourcesLI();
4358                    }
4359                }
4360            }
4361        }
4362
4363        // The apk is forward locked (not public) if its code and resources
4364        // are kept in different files. (except for app in either system or
4365        // vendor path).
4366        // TODO grab this value from PackageSettings
4367        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4368            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4369                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4370            }
4371        }
4372
4373        final String codePath = pkg.codePath;
4374        final String[] splitCodePaths = pkg.splitCodePaths;
4375
4376        String resPath = null;
4377        String[] splitResPaths = null;
4378        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4379            if (ps != null && ps.resourcePathString != null) {
4380                resPath = ps.resourcePathString;
4381                splitResPaths = deriveSplitResPaths(pkg.splitCodePaths);
4382            } else {
4383                // Should not happen at all. Just log an error.
4384                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4385            }
4386        } else {
4387            resPath = pkg.codePath;
4388            splitResPaths = pkg.splitCodePaths;
4389        }
4390
4391        // Set application objects path explicitly.
4392        pkg.applicationInfo.sourceDir = codePath;
4393        pkg.applicationInfo.publicSourceDir = resPath;
4394        pkg.applicationInfo.splitSourceDirs = splitCodePaths;
4395        pkg.applicationInfo.splitPublicSourceDirs = splitResPaths;
4396
4397        // Note that we invoke the following method only if we are about to unpack an application
4398        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4399                | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride);
4400
4401        /*
4402         * If the system app should be overridden by a previously installed
4403         * data, hide the system app now and let the /data/app scan pick it up
4404         * again.
4405         */
4406        if (shouldHideSystemApp) {
4407            synchronized (mPackages) {
4408                /*
4409                 * We have to grant systems permissions before we hide, because
4410                 * grantPermissions will assume the package update is trying to
4411                 * expand its permissions.
4412                 */
4413                grantPermissionsLPw(pkg, true);
4414                mSettings.disableSystemPackageLPw(pkg.packageName);
4415            }
4416        }
4417
4418        return scannedPkg;
4419    }
4420
4421    private static String fixProcessName(String defProcessName,
4422            String processName, int uid) {
4423        if (processName == null) {
4424            return defProcessName;
4425        }
4426        return processName;
4427    }
4428
4429    private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) {
4430        if (pkgSetting.signatures.mSignatures != null) {
4431            // Already existing package. Make sure signatures match
4432            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4433                    == PackageManager.SIGNATURE_MATCH;
4434            if (!match) {
4435                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4436                        == PackageManager.SIGNATURE_MATCH;
4437            }
4438            if (!match) {
4439                Slog.e(TAG, "Package " + pkg.packageName
4440                        + " signatures do not match the previously installed version; ignoring!");
4441                mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4442                return false;
4443            }
4444        }
4445        // Check for shared user signatures
4446        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4447            // Already existing package. Make sure signatures match
4448            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4449                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4450            if (!match) {
4451                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4452                        == PackageManager.SIGNATURE_MATCH;
4453            }
4454            if (!match) {
4455                Slog.e(TAG, "Package " + pkg.packageName
4456                        + " has no signatures that match those in shared user "
4457                        + pkgSetting.sharedUser.name + "; ignoring!");
4458                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4459                return false;
4460            }
4461        }
4462        return true;
4463    }
4464
4465    /**
4466     * Enforces that only the system UID or root's UID can call a method exposed
4467     * via Binder.
4468     *
4469     * @param message used as message if SecurityException is thrown
4470     * @throws SecurityException if the caller is not system or root
4471     */
4472    private static final void enforceSystemOrRoot(String message) {
4473        final int uid = Binder.getCallingUid();
4474        if (uid != Process.SYSTEM_UID && uid != 0) {
4475            throw new SecurityException(message);
4476        }
4477    }
4478
4479    @Override
4480    public void performBootDexOpt() {
4481        enforceSystemOrRoot("Only the system can request dexopt be performed");
4482
4483        final HashSet<PackageParser.Package> pkgs;
4484        synchronized (mPackages) {
4485            pkgs = mDeferredDexOpt;
4486            mDeferredDexOpt = null;
4487        }
4488
4489        if (pkgs != null) {
4490            // Filter out packages that aren't recently used.
4491            //
4492            // The exception is first boot of a non-eng device, which
4493            // should do a full dexopt.
4494            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4495            if (eng || !isFirstBoot()) {
4496                // TODO: add a property to control this?
4497                long dexOptLRUThresholdInMinutes;
4498                if (eng) {
4499                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4500                } else {
4501                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4502                }
4503                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4504
4505                int total = pkgs.size();
4506                int skipped = 0;
4507                long now = System.currentTimeMillis();
4508                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4509                    PackageParser.Package pkg = i.next();
4510                    long then = pkg.mLastPackageUsageTimeInMills;
4511                    if (then + dexOptLRUThresholdInMills < now) {
4512                        if (DEBUG_DEXOPT) {
4513                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4514                                  ((then == 0) ? "never" : new Date(then)));
4515                        }
4516                        i.remove();
4517                        skipped++;
4518                    }
4519                }
4520                if (DEBUG_DEXOPT) {
4521                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4522                }
4523            }
4524
4525            int i = 0;
4526            for (PackageParser.Package pkg : pkgs) {
4527                i++;
4528                if (DEBUG_DEXOPT) {
4529                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4530                          + ": " + pkg.packageName);
4531                }
4532                if (!isFirstBoot()) {
4533                    try {
4534                        ActivityManagerNative.getDefault().showBootMessage(
4535                                mContext.getResources().getString(
4536                                        R.string.android_upgrading_apk,
4537                                        i, pkgs.size()), true);
4538                    } catch (RemoteException e) {
4539                    }
4540                }
4541                PackageParser.Package p = pkg;
4542                synchronized (mInstallLock) {
4543                    if (p.mDexOptNeeded) {
4544                        performDexOptLI(p, false /* force dex */, false /* defer */,
4545                                true /* include dependencies */);
4546                    }
4547                }
4548            }
4549        }
4550    }
4551
4552    @Override
4553    public boolean performDexOpt(String packageName) {
4554        enforceSystemOrRoot("Only the system can request dexopt be performed");
4555        return performDexOpt(packageName, true);
4556    }
4557
4558    public boolean performDexOpt(String packageName, boolean updateUsage) {
4559
4560        PackageParser.Package p;
4561        synchronized (mPackages) {
4562            p = mPackages.get(packageName);
4563            if (p == null) {
4564                return false;
4565            }
4566            if (updateUsage) {
4567                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4568            }
4569            mPackageUsage.write(false);
4570            if (!p.mDexOptNeeded) {
4571                return false;
4572            }
4573        }
4574
4575        synchronized (mInstallLock) {
4576            return performDexOptLI(p, false /* force dex */, false /* defer */,
4577                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4578        }
4579    }
4580
4581    public HashSet<String> getPackagesThatNeedDexOpt() {
4582        HashSet<String> pkgs = null;
4583        synchronized (mPackages) {
4584            for (PackageParser.Package p : mPackages.values()) {
4585                if (DEBUG_DEXOPT) {
4586                    Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded);
4587                }
4588                if (!p.mDexOptNeeded) {
4589                    continue;
4590                }
4591                if (pkgs == null) {
4592                    pkgs = new HashSet<String>();
4593                }
4594                pkgs.add(p.packageName);
4595            }
4596        }
4597        return pkgs;
4598    }
4599
4600    public void shutdown() {
4601        mPackageUsage.write(true);
4602    }
4603
4604    private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet,
4605             boolean forceDex, boolean defer, HashSet<String> done) {
4606        for (int i=0; i<libs.size(); i++) {
4607            PackageParser.Package libPkg;
4608            String libName;
4609            synchronized (mPackages) {
4610                libName = libs.get(i);
4611                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4612                if (lib != null && lib.apk != null) {
4613                    libPkg = mPackages.get(lib.apk);
4614                } else {
4615                    libPkg = null;
4616                }
4617            }
4618            if (libPkg != null && !done.contains(libName)) {
4619                performDexOptLI(libPkg, instructionSet, forceDex, defer, done);
4620            }
4621        }
4622    }
4623
4624    static final int DEX_OPT_SKIPPED = 0;
4625    static final int DEX_OPT_PERFORMED = 1;
4626    static final int DEX_OPT_DEFERRED = 2;
4627    static final int DEX_OPT_FAILED = -1;
4628
4629    private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride,
4630            boolean forceDex, boolean defer, HashSet<String> done) {
4631        final String instructionSet = instructionSetOverride != null ?
4632                instructionSetOverride : getAppInstructionSet(pkg.applicationInfo);
4633
4634        if (done != null) {
4635            done.add(pkg.packageName);
4636            if (pkg.usesLibraries != null) {
4637                performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done);
4638            }
4639            if (pkg.usesOptionalLibraries != null) {
4640                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done);
4641            }
4642        }
4643
4644        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) {
4645            final Collection<String> paths = pkg.getAllCodePaths();
4646            for (String path : paths) {
4647                try {
4648                    boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path,
4649                            pkg.packageName, instructionSet, defer);
4650                    // There are three basic cases here:
4651                    // 1.) we need to dexopt, either because we are forced or it is needed
4652                    // 2.) we are defering a needed dexopt
4653                    // 3.) we are skipping an unneeded dexopt
4654                    if (forceDex || (!defer && isDexOptNeededInternal)) {
4655                        Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
4656                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4657                        int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4658                                                    pkg.packageName, instructionSet);
4659                        // Note that we ran dexopt, since rerunning will
4660                        // probably just result in an error again.
4661                        pkg.mDexOptNeeded = false;
4662                        if (ret < 0) {
4663                            return DEX_OPT_FAILED;
4664                        }
4665                        return DEX_OPT_PERFORMED;
4666                    }
4667                    if (defer && isDexOptNeededInternal) {
4668                        if (mDeferredDexOpt == null) {
4669                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4670                        }
4671                        mDeferredDexOpt.add(pkg);
4672                        return DEX_OPT_DEFERRED;
4673                    }
4674                    pkg.mDexOptNeeded = false;
4675                    return DEX_OPT_SKIPPED;
4676                } catch (FileNotFoundException e) {
4677                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4678                    return DEX_OPT_FAILED;
4679                } catch (IOException e) {
4680                    Slog.w(TAG, "IOException reading apk: " + path, e);
4681                    return DEX_OPT_FAILED;
4682                } catch (StaleDexCacheError e) {
4683                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4684                    return DEX_OPT_FAILED;
4685                } catch (Exception e) {
4686                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4687                    return DEX_OPT_FAILED;
4688                }
4689            }
4690        }
4691        return DEX_OPT_SKIPPED;
4692    }
4693
4694    private String getAppInstructionSet(ApplicationInfo info) {
4695        String instructionSet = getPreferredInstructionSet();
4696
4697        if (info.cpuAbi != null) {
4698            instructionSet = VMRuntime.getInstructionSet(info.cpuAbi);
4699        }
4700
4701        return instructionSet;
4702    }
4703
4704    private String getAppInstructionSetFromSettings(PackageSetting ps) {
4705        String instructionSet = getPreferredInstructionSet();
4706
4707        if (ps.cpuAbiString != null) {
4708            instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
4709        }
4710
4711        return instructionSet;
4712    }
4713
4714    private static String getPreferredInstructionSet() {
4715        if (sPreferredInstructionSet == null) {
4716            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4717        }
4718
4719        return sPreferredInstructionSet;
4720    }
4721
4722    private static List<String> getAllInstructionSets() {
4723        final String[] allAbis = Build.SUPPORTED_ABIS;
4724        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4725
4726        for (String abi : allAbis) {
4727            final String instructionSet = VMRuntime.getInstructionSet(abi);
4728            if (!allInstructionSets.contains(instructionSet)) {
4729                allInstructionSets.add(instructionSet);
4730            }
4731        }
4732
4733        return allInstructionSets;
4734    }
4735
4736    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4737            boolean inclDependencies) {
4738        HashSet<String> done;
4739        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4740            done = new HashSet<String>();
4741            done.add(pkg.packageName);
4742        } else {
4743            done = null;
4744        }
4745        return performDexOptLI(pkg, null /* instruction set override */,  forceDex, defer, done);
4746    }
4747
4748    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4749        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4750            Slog.w(TAG, "Unable to update from " + oldPkg.name
4751                    + " to " + newPkg.packageName
4752                    + ": old package not in system partition");
4753            return false;
4754        } else if (mPackages.get(oldPkg.name) != null) {
4755            Slog.w(TAG, "Unable to update from " + oldPkg.name
4756                    + " to " + newPkg.packageName
4757                    + ": old package still exists");
4758            return false;
4759        }
4760        return true;
4761    }
4762
4763    File getDataPathForUser(int userId) {
4764        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4765    }
4766
4767    private File getDataPathForPackage(String packageName, int userId) {
4768        /*
4769         * Until we fully support multiple users, return the directory we
4770         * previously would have. The PackageManagerTests will need to be
4771         * revised when this is changed back..
4772         */
4773        if (userId == 0) {
4774            return new File(mAppDataDir, packageName);
4775        } else {
4776            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4777                + File.separator + packageName);
4778        }
4779    }
4780
4781    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4782        int[] users = sUserManager.getUserIds();
4783        int res = mInstaller.install(packageName, uid, uid, seinfo);
4784        if (res < 0) {
4785            return res;
4786        }
4787        for (int user : users) {
4788            if (user != 0) {
4789                res = mInstaller.createUserData(packageName,
4790                        UserHandle.getUid(user, uid), user, seinfo);
4791                if (res < 0) {
4792                    return res;
4793                }
4794            }
4795        }
4796        return res;
4797    }
4798
4799    private int removeDataDirsLI(String packageName) {
4800        int[] users = sUserManager.getUserIds();
4801        int res = 0;
4802        for (int user : users) {
4803            int resInner = mInstaller.remove(packageName, user);
4804            if (resInner < 0) {
4805                res = resInner;
4806            }
4807        }
4808
4809        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4810        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4811        if (!nativeLibraryFile.delete()) {
4812            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4813        }
4814
4815        return res;
4816    }
4817
4818    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4819            PackageParser.Package changingLib) {
4820        if (file.path != null) {
4821            usesLibraryFiles.add(file.path);
4822            return;
4823        }
4824        PackageParser.Package p = mPackages.get(file.apk);
4825        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4826            // If we are doing this while in the middle of updating a library apk,
4827            // then we need to make sure to use that new apk for determining the
4828            // dependencies here.  (We haven't yet finished committing the new apk
4829            // to the package manager state.)
4830            if (p == null || p.packageName.equals(changingLib.packageName)) {
4831                p = changingLib;
4832            }
4833        }
4834        if (p != null) {
4835            usesLibraryFiles.addAll(p.getAllCodePaths());
4836        }
4837    }
4838
4839    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4840            PackageParser.Package changingLib) {
4841        // We might be upgrading from a version of the platform that did not
4842        // provide per-package native library directories for system apps.
4843        // Fix that up here.
4844        if (isSystemApp(pkg)) {
4845            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4846            setInternalAppNativeLibraryPath(pkg, ps);
4847        }
4848
4849        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4850            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4851            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4852            for (int i=0; i<N; i++) {
4853                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4854                if (file == null) {
4855                    Slog.e(TAG, "Package " + pkg.packageName
4856                            + " requires unavailable shared library "
4857                            + pkg.usesLibraries.get(i) + "; failing!");
4858                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4859                    return false;
4860                }
4861                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4862            }
4863            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4864            for (int i=0; i<N; i++) {
4865                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4866                if (file == null) {
4867                    Slog.w(TAG, "Package " + pkg.packageName
4868                            + " desires unavailable shared library "
4869                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4870                } else {
4871                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4872                }
4873            }
4874            N = usesLibraryFiles.size();
4875            if (N > 0) {
4876                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4877            } else {
4878                pkg.usesLibraryFiles = null;
4879            }
4880        }
4881        return true;
4882    }
4883
4884    private static boolean hasString(List<String> list, List<String> which) {
4885        if (list == null) {
4886            return false;
4887        }
4888        for (int i=list.size()-1; i>=0; i--) {
4889            for (int j=which.size()-1; j>=0; j--) {
4890                if (which.get(j).equals(list.get(i))) {
4891                    return true;
4892                }
4893            }
4894        }
4895        return false;
4896    }
4897
4898    private void updateAllSharedLibrariesLPw() {
4899        for (PackageParser.Package pkg : mPackages.values()) {
4900            updateSharedLibrariesLPw(pkg, null);
4901        }
4902    }
4903
4904    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4905            PackageParser.Package changingPkg) {
4906        ArrayList<PackageParser.Package> res = null;
4907        for (PackageParser.Package pkg : mPackages.values()) {
4908            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4909                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4910                if (res == null) {
4911                    res = new ArrayList<PackageParser.Package>();
4912                }
4913                res.add(pkg);
4914                updateSharedLibrariesLPw(pkg, changingPkg);
4915            }
4916        }
4917        return res;
4918    }
4919
4920    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4921            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
4922        final File scanFile = new File(pkg.codePath);
4923        if (pkg.applicationInfo.sourceDir == null ||
4924                pkg.applicationInfo.publicSourceDir == null) {
4925            // Bail out. The resource and code paths haven't been set.
4926            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4927            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4928            return null;
4929        }
4930
4931        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4932            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4933        }
4934
4935        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4936            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4937        }
4938
4939        if (mCustomResolverComponentName != null &&
4940                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4941            setUpCustomResolverActivity(pkg);
4942        }
4943
4944        if (pkg.packageName.equals("android")) {
4945            synchronized (mPackages) {
4946                if (mAndroidApplication != null) {
4947                    Slog.w(TAG, "*************************************************");
4948                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4949                    Slog.w(TAG, " file=" + scanFile);
4950                    Slog.w(TAG, "*************************************************");
4951                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4952                    return null;
4953                }
4954
4955                // Set up information for our fall-back user intent resolution activity.
4956                mPlatformPackage = pkg;
4957                pkg.mVersionCode = mSdkVersion;
4958                mAndroidApplication = pkg.applicationInfo;
4959
4960                if (!mResolverReplaced) {
4961                    mResolveActivity.applicationInfo = mAndroidApplication;
4962                    mResolveActivity.name = ResolverActivity.class.getName();
4963                    mResolveActivity.packageName = mAndroidApplication.packageName;
4964                    mResolveActivity.processName = "system:ui";
4965                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4966                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
4967                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4968                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
4969                    mResolveActivity.exported = true;
4970                    mResolveActivity.enabled = true;
4971                    mResolveInfo.activityInfo = mResolveActivity;
4972                    mResolveInfo.priority = 0;
4973                    mResolveInfo.preferredOrder = 0;
4974                    mResolveInfo.match = 0;
4975                    mResolveComponentName = new ComponentName(
4976                            mAndroidApplication.packageName, mResolveActivity.name);
4977                }
4978            }
4979        }
4980
4981        if (DEBUG_PACKAGE_SCANNING) {
4982            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4983                Log.d(TAG, "Scanning package " + pkg.packageName);
4984        }
4985
4986        if (mPackages.containsKey(pkg.packageName)
4987                || mSharedLibraries.containsKey(pkg.packageName)) {
4988            Slog.w(TAG, "Application package " + pkg.packageName
4989                    + " already installed.  Skipping duplicate.");
4990            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4991            return null;
4992        }
4993
4994        // Initialize package source and resource directories
4995        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
4996        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
4997
4998        SharedUserSetting suid = null;
4999        PackageSetting pkgSetting = null;
5000
5001        if (!isSystemApp(pkg)) {
5002            // Only system apps can use these features.
5003            pkg.mOriginalPackages = null;
5004            pkg.mRealPackage = null;
5005            pkg.mAdoptPermissions = null;
5006        }
5007
5008        // writer
5009        synchronized (mPackages) {
5010            if (pkg.mSharedUserId != null) {
5011                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5012                if (suid == null) {
5013                    Slog.w(TAG, "Creating application package " + pkg.packageName
5014                            + " for shared user failed");
5015                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5016                    return null;
5017                }
5018                if (DEBUG_PACKAGE_SCANNING) {
5019                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5020                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5021                                + "): packages=" + suid.packages);
5022                }
5023            }
5024
5025            // Check if we are renaming from an original package name.
5026            PackageSetting origPackage = null;
5027            String realName = null;
5028            if (pkg.mOriginalPackages != null) {
5029                // This package may need to be renamed to a previously
5030                // installed name.  Let's check on that...
5031                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5032                if (pkg.mOriginalPackages.contains(renamed)) {
5033                    // This package had originally been installed as the
5034                    // original name, and we have already taken care of
5035                    // transitioning to the new one.  Just update the new
5036                    // one to continue using the old name.
5037                    realName = pkg.mRealPackage;
5038                    if (!pkg.packageName.equals(renamed)) {
5039                        // Callers into this function may have already taken
5040                        // care of renaming the package; only do it here if
5041                        // it is not already done.
5042                        pkg.setPackageName(renamed);
5043                    }
5044
5045                } else {
5046                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5047                        if ((origPackage = mSettings.peekPackageLPr(
5048                                pkg.mOriginalPackages.get(i))) != null) {
5049                            // We do have the package already installed under its
5050                            // original name...  should we use it?
5051                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5052                                // New package is not compatible with original.
5053                                origPackage = null;
5054                                continue;
5055                            } else if (origPackage.sharedUser != null) {
5056                                // Make sure uid is compatible between packages.
5057                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5058                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5059                                            + " to " + pkg.packageName + ": old uid "
5060                                            + origPackage.sharedUser.name
5061                                            + " differs from " + pkg.mSharedUserId);
5062                                    origPackage = null;
5063                                    continue;
5064                                }
5065                            } else {
5066                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5067                                        + pkg.packageName + " to old name " + origPackage.name);
5068                            }
5069                            break;
5070                        }
5071                    }
5072                }
5073            }
5074
5075            if (mTransferedPackages.contains(pkg.packageName)) {
5076                Slog.w(TAG, "Package " + pkg.packageName
5077                        + " was transferred to another, but its .apk remains");
5078            }
5079
5080            // Just create the setting, don't add it yet. For already existing packages
5081            // the PkgSetting exists already and doesn't have to be created.
5082            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5083                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
5084                    pkg.applicationInfo.cpuAbi,
5085                    pkg.applicationInfo.flags, user, false);
5086            if (pkgSetting == null) {
5087                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
5088                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5089                return null;
5090            }
5091
5092            if (pkgSetting.origPackage != null) {
5093                // If we are first transitioning from an original package,
5094                // fix up the new package's name now.  We need to do this after
5095                // looking up the package under its new name, so getPackageLP
5096                // can take care of fiddling things correctly.
5097                pkg.setPackageName(origPackage.name);
5098
5099                // File a report about this.
5100                String msg = "New package " + pkgSetting.realName
5101                        + " renamed to replace old package " + pkgSetting.name;
5102                reportSettingsProblem(Log.WARN, msg);
5103
5104                // Make a note of it.
5105                mTransferedPackages.add(origPackage.name);
5106
5107                // No longer need to retain this.
5108                pkgSetting.origPackage = null;
5109            }
5110
5111            if (realName != null) {
5112                // Make a note of it.
5113                mTransferedPackages.add(pkg.packageName);
5114            }
5115
5116            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5117                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5118            }
5119
5120            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5121                // Check all shared libraries and map to their actual file path.
5122                // We only do this here for apps not on a system dir, because those
5123                // are the only ones that can fail an install due to this.  We
5124                // will take care of the system apps by updating all of their
5125                // library paths after the scan is done.
5126                if (!updateSharedLibrariesLPw(pkg, null)) {
5127                    return null;
5128                }
5129            }
5130
5131            if (mFoundPolicyFile) {
5132                SELinuxMMAC.assignSeinfoValue(pkg);
5133            }
5134
5135            pkg.applicationInfo.uid = pkgSetting.appId;
5136            pkg.mExtras = pkgSetting;
5137
5138            if (!verifySignaturesLP(pkgSetting, pkg)) {
5139                if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5140                    return null;
5141                }
5142                // The signature has changed, but this package is in the system
5143                // image...  let's recover!
5144                pkgSetting.signatures.mSignatures = pkg.mSignatures;
5145                // However...  if this package is part of a shared user, but it
5146                // doesn't match the signature of the shared user, let's fail.
5147                // What this means is that you can't change the signatures
5148                // associated with an overall shared user, which doesn't seem all
5149                // that unreasonable.
5150                if (pkgSetting.sharedUser != null) {
5151                    if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5152                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5153                        Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
5154                        mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5155                        return null;
5156                    }
5157                }
5158                // File a report about this.
5159                String msg = "System package " + pkg.packageName
5160                        + " signature changed; retaining data.";
5161                reportSettingsProblem(Log.WARN, msg);
5162            }
5163
5164            // Verify that this new package doesn't have any content providers
5165            // that conflict with existing packages.  Only do this if the
5166            // package isn't already installed, since we don't want to break
5167            // things that are installed.
5168            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5169                final int N = pkg.providers.size();
5170                int i;
5171                for (i=0; i<N; i++) {
5172                    PackageParser.Provider p = pkg.providers.get(i);
5173                    if (p.info.authority != null) {
5174                        String names[] = p.info.authority.split(";");
5175                        for (int j = 0; j < names.length; j++) {
5176                            if (mProvidersByAuthority.containsKey(names[j])) {
5177                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5178                                Slog.w(TAG, "Can't install because provider name " + names[j] +
5179                                        " (in package " + pkg.applicationInfo.packageName +
5180                                        ") is already used by "
5181                                        + ((other != null && other.getComponentName() != null)
5182                                                ? other.getComponentName().getPackageName() : "?"));
5183                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
5184                                return null;
5185                            }
5186                        }
5187                    }
5188                }
5189            }
5190
5191            if (pkg.mAdoptPermissions != null) {
5192                // This package wants to adopt ownership of permissions from
5193                // another package.
5194                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5195                    final String origName = pkg.mAdoptPermissions.get(i);
5196                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5197                    if (orig != null) {
5198                        if (verifyPackageUpdateLPr(orig, pkg)) {
5199                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5200                                    + pkg.packageName);
5201                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5202                        }
5203                    }
5204                }
5205            }
5206        }
5207
5208        final String pkgName = pkg.packageName;
5209
5210        final long scanFileTime = scanFile.lastModified();
5211        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5212        pkg.applicationInfo.processName = fixProcessName(
5213                pkg.applicationInfo.packageName,
5214                pkg.applicationInfo.processName,
5215                pkg.applicationInfo.uid);
5216
5217        File dataPath;
5218        if (mPlatformPackage == pkg) {
5219            // The system package is special.
5220            dataPath = new File (Environment.getDataDirectory(), "system");
5221            pkg.applicationInfo.dataDir = dataPath.getPath();
5222        } else {
5223            // This is a normal package, need to make its data directory.
5224            dataPath = getDataPathForPackage(pkg.packageName, 0);
5225
5226            boolean uidError = false;
5227
5228            if (dataPath.exists()) {
5229                int currentUid = 0;
5230                try {
5231                    StructStat stat = Os.stat(dataPath.getPath());
5232                    currentUid = stat.st_uid;
5233                } catch (ErrnoException e) {
5234                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5235                }
5236
5237                // If we have mismatched owners for the data path, we have a problem.
5238                if (currentUid != pkg.applicationInfo.uid) {
5239                    boolean recovered = false;
5240                    if (currentUid == 0) {
5241                        // The directory somehow became owned by root.  Wow.
5242                        // This is probably because the system was stopped while
5243                        // installd was in the middle of messing with its libs
5244                        // directory.  Ask installd to fix that.
5245                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5246                                pkg.applicationInfo.uid);
5247                        if (ret >= 0) {
5248                            recovered = true;
5249                            String msg = "Package " + pkg.packageName
5250                                    + " unexpectedly changed to uid 0; recovered to " +
5251                                    + pkg.applicationInfo.uid;
5252                            reportSettingsProblem(Log.WARN, msg);
5253                        }
5254                    }
5255                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5256                            || (scanMode&SCAN_BOOTING) != 0)) {
5257                        // If this is a system app, we can at least delete its
5258                        // current data so the application will still work.
5259                        int ret = removeDataDirsLI(pkgName);
5260                        if (ret >= 0) {
5261                            // TODO: Kill the processes first
5262                            // Old data gone!
5263                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5264                                    ? "System package " : "Third party package ";
5265                            String msg = prefix + pkg.packageName
5266                                    + " has changed from uid: "
5267                                    + currentUid + " to "
5268                                    + pkg.applicationInfo.uid + "; old data erased";
5269                            reportSettingsProblem(Log.WARN, msg);
5270                            recovered = true;
5271
5272                            // And now re-install the app.
5273                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5274                                                   pkg.applicationInfo.seinfo);
5275                            if (ret == -1) {
5276                                // Ack should not happen!
5277                                msg = prefix + pkg.packageName
5278                                        + " could not have data directory re-created after delete.";
5279                                reportSettingsProblem(Log.WARN, msg);
5280                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5281                                return null;
5282                            }
5283                        }
5284                        if (!recovered) {
5285                            mHasSystemUidErrors = true;
5286                        }
5287                    } else if (!recovered) {
5288                        // If we allow this install to proceed, we will be broken.
5289                        // Abort, abort!
5290                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
5291                        return null;
5292                    }
5293                    if (!recovered) {
5294                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5295                            + pkg.applicationInfo.uid + "/fs_"
5296                            + currentUid;
5297                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5298                        String msg = "Package " + pkg.packageName
5299                                + " has mismatched uid: "
5300                                + currentUid + " on disk, "
5301                                + pkg.applicationInfo.uid + " in settings";
5302                        // writer
5303                        synchronized (mPackages) {
5304                            mSettings.mReadMessages.append(msg);
5305                            mSettings.mReadMessages.append('\n');
5306                            uidError = true;
5307                            if (!pkgSetting.uidError) {
5308                                reportSettingsProblem(Log.ERROR, msg);
5309                            }
5310                        }
5311                    }
5312                }
5313                pkg.applicationInfo.dataDir = dataPath.getPath();
5314                if (mShouldRestoreconData) {
5315                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5316                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5317                                pkg.applicationInfo.uid);
5318                }
5319            } else {
5320                if (DEBUG_PACKAGE_SCANNING) {
5321                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5322                        Log.v(TAG, "Want this data dir: " + dataPath);
5323                }
5324                //invoke installer to do the actual installation
5325                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5326                                           pkg.applicationInfo.seinfo);
5327                if (ret < 0) {
5328                    // Error from installer
5329                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5330                    return null;
5331                }
5332
5333                if (dataPath.exists()) {
5334                    pkg.applicationInfo.dataDir = dataPath.getPath();
5335                } else {
5336                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5337                    pkg.applicationInfo.dataDir = null;
5338                }
5339            }
5340
5341            /*
5342             * Set the data dir to the default "/data/data/<package name>/lib"
5343             * if we got here without anyone telling us different (e.g., apps
5344             * stored on SD card have their native libraries stored in the ASEC
5345             * container with the APK).
5346             *
5347             * This happens during an upgrade from a package settings file that
5348             * doesn't have a native library path attribute at all.
5349             */
5350            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
5351                if (pkgSetting.nativeLibraryPathString == null) {
5352                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
5353                } else {
5354                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
5355                }
5356            }
5357            pkgSetting.uidError = uidError;
5358        }
5359
5360        final String path = scanFile.getPath();
5361        /* Note: We don't want to unpack the native binaries for
5362         *        system applications, unless they have been updated
5363         *        (the binaries are already under /system/lib).
5364         *        Also, don't unpack libs for apps on the external card
5365         *        since they should have their libraries in the ASEC
5366         *        container already.
5367         *
5368         *        In other words, we're going to unpack the binaries
5369         *        only for non-system apps and system app upgrades.
5370         */
5371        if (pkg.applicationInfo.nativeLibraryDir != null) {
5372            // TODO: extend to extract native code from split APKs
5373            final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(scanFile);
5374            try {
5375                // Enable gross and lame hacks for apps that are built with old
5376                // SDK tools. We must scan their APKs for renderscript bitcode and
5377                // not launch them if it's present. Don't bother checking on devices
5378                // that don't have 64 bit support.
5379                String[] abiList = Build.SUPPORTED_ABIS;
5380                boolean hasLegacyRenderscriptBitcode = false;
5381                if (abiOverride != null) {
5382                    abiList = new String[] { abiOverride };
5383                } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
5384                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5385                    abiList = Build.SUPPORTED_32_BIT_ABIS;
5386                    hasLegacyRenderscriptBitcode = true;
5387                }
5388
5389                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5390                final String dataPathString = dataPath.getCanonicalPath();
5391
5392                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5393                    /*
5394                     * Upgrading from a previous version of the OS sometimes
5395                     * leaves native libraries in the /data/data/<app>/lib
5396                     * directory for system apps even when they shouldn't be.
5397                     * Recent changes in the JNI library search path
5398                     * necessitates we remove those to match previous behavior.
5399                     */
5400                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
5401                        Log.i(TAG, "removed obsolete native libraries for system package "
5402                                + path);
5403                    }
5404                    if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5405                        pkg.applicationInfo.cpuAbi = abiList[0];
5406                        pkgSetting.cpuAbiString = abiList[0];
5407                    } else {
5408                        setInternalAppAbi(pkg, pkgSetting);
5409                    }
5410                } else {
5411                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
5412                        /*
5413                        * Update native library dir if it starts with
5414                        * /data/data
5415                        */
5416                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
5417                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
5418                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5419                        }
5420
5421                        try {
5422                            int copyRet = copyNativeLibrariesForInternalApp(handle,
5423                                    nativeLibraryDir, abiList);
5424                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5425                                Slog.e(TAG, "Unable to copy native libraries");
5426                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5427                                return null;
5428                            }
5429
5430                            // We've successfully copied native libraries across, so we make a
5431                            // note of what ABI we're using
5432                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5433                                pkg.applicationInfo.cpuAbi = abiList[copyRet];
5434                            } else if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5435                                pkg.applicationInfo.cpuAbi = abiList[0];
5436                            } else {
5437                                pkg.applicationInfo.cpuAbi = null;
5438                            }
5439                        } catch (IOException e) {
5440                            Slog.e(TAG, "Unable to copy native libraries", e);
5441                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5442                            return null;
5443                        }
5444                    } else {
5445                        // We don't have to copy the shared libraries if we're in the ASEC container
5446                        // but we still need to scan the file to figure out what ABI the app needs.
5447                        //
5448                        // TODO: This duplicates work done in the default container service. It's possible
5449                        // to clean this up but we'll need to change the interface between this service
5450                        // and IMediaContainerService (but doing so will spread this logic out, rather
5451                        // than centralizing it).
5452                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5453                        if (abi >= 0) {
5454                            pkg.applicationInfo.cpuAbi = abiList[abi];
5455                        } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) {
5456                            // Note that (non upgraded) system apps will not have any native
5457                            // libraries bundled in their APK, but we're guaranteed not to be
5458                            // such an app at this point.
5459                            if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5460                                pkg.applicationInfo.cpuAbi = abiList[0];
5461                            } else {
5462                                pkg.applicationInfo.cpuAbi = null;
5463                            }
5464                        } else {
5465                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5466                            return null;
5467                        }
5468                    }
5469
5470                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5471                    final int[] userIds = sUserManager.getUserIds();
5472                    synchronized (mInstallLock) {
5473                        for (int userId : userIds) {
5474                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
5475                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
5476                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
5477                                        + ")");
5478                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5479                                return null;
5480                            }
5481                        }
5482                    }
5483                }
5484
5485                pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi;
5486            } catch (IOException ioe) {
5487                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5488            } finally {
5489                handle.close();
5490            }
5491        }
5492
5493        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5494            // We don't do this here during boot because we can do it all
5495            // at once after scanning all existing packages.
5496            //
5497            // We also do this *before* we perform dexopt on this package, so that
5498            // we can avoid redundant dexopts, and also to make sure we've got the
5499            // code and package path correct.
5500            if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5501                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) {
5502                mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE;
5503                return null;
5504            }
5505        }
5506
5507        if ((scanMode&SCAN_NO_DEX) == 0) {
5508            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5509                    == DEX_OPT_FAILED) {
5510                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5511                    removeDataDirsLI(pkg.packageName);
5512                }
5513
5514                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5515                return null;
5516            }
5517        }
5518
5519        if (mFactoryTest && pkg.requestedPermissions.contains(
5520                android.Manifest.permission.FACTORY_TEST)) {
5521            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5522        }
5523
5524        ArrayList<PackageParser.Package> clientLibPkgs = null;
5525
5526        // writer
5527        synchronized (mPackages) {
5528            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5529                // Only system apps can add new shared libraries.
5530                if (pkg.libraryNames != null) {
5531                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5532                        String name = pkg.libraryNames.get(i);
5533                        boolean allowed = false;
5534                        if (isUpdatedSystemApp(pkg)) {
5535                            // New library entries can only be added through the
5536                            // system image.  This is important to get rid of a lot
5537                            // of nasty edge cases: for example if we allowed a non-
5538                            // system update of the app to add a library, then uninstalling
5539                            // the update would make the library go away, and assumptions
5540                            // we made such as through app install filtering would now
5541                            // have allowed apps on the device which aren't compatible
5542                            // with it.  Better to just have the restriction here, be
5543                            // conservative, and create many fewer cases that can negatively
5544                            // impact the user experience.
5545                            final PackageSetting sysPs = mSettings
5546                                    .getDisabledSystemPkgLPr(pkg.packageName);
5547                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5548                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5549                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5550                                        allowed = true;
5551                                        allowed = true;
5552                                        break;
5553                                    }
5554                                }
5555                            }
5556                        } else {
5557                            allowed = true;
5558                        }
5559                        if (allowed) {
5560                            if (!mSharedLibraries.containsKey(name)) {
5561                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5562                            } else if (!name.equals(pkg.packageName)) {
5563                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5564                                        + name + " already exists; skipping");
5565                            }
5566                        } else {
5567                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5568                                    + name + " that is not declared on system image; skipping");
5569                        }
5570                    }
5571                    if ((scanMode&SCAN_BOOTING) == 0) {
5572                        // If we are not booting, we need to update any applications
5573                        // that are clients of our shared library.  If we are booting,
5574                        // this will all be done once the scan is complete.
5575                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5576                    }
5577                }
5578            }
5579        }
5580
5581        // We also need to dexopt any apps that are dependent on this library.  Note that
5582        // if these fail, we should abort the install since installing the library will
5583        // result in some apps being broken.
5584        if (clientLibPkgs != null) {
5585            if ((scanMode&SCAN_NO_DEX) == 0) {
5586                for (int i=0; i<clientLibPkgs.size(); i++) {
5587                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5588                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5589                            == DEX_OPT_FAILED) {
5590                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5591                            removeDataDirsLI(pkg.packageName);
5592                        }
5593
5594                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5595                        return null;
5596                    }
5597                }
5598            }
5599        }
5600
5601        // Request the ActivityManager to kill the process(only for existing packages)
5602        // so that we do not end up in a confused state while the user is still using the older
5603        // version of the application while the new one gets installed.
5604        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5605            // If the package lives in an asec, tell everyone that the container is going
5606            // away so they can clean up any references to its resources (which would prevent
5607            // vold from being able to unmount the asec)
5608            if (isForwardLocked(pkg) || isExternal(pkg)) {
5609                if (DEBUG_INSTALL) {
5610                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5611                }
5612                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5613                final ArrayList<String> pkgList = new ArrayList<String>(1);
5614                pkgList.add(pkg.applicationInfo.packageName);
5615                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5616            }
5617
5618            // Post the request that it be killed now that the going-away broadcast is en route
5619            killApplication(pkg.applicationInfo.packageName,
5620                        pkg.applicationInfo.uid, "update pkg");
5621        }
5622
5623        // Also need to kill any apps that are dependent on the library.
5624        if (clientLibPkgs != null) {
5625            for (int i=0; i<clientLibPkgs.size(); i++) {
5626                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5627                killApplication(clientPkg.applicationInfo.packageName,
5628                        clientPkg.applicationInfo.uid, "update lib");
5629            }
5630        }
5631
5632        // writer
5633        synchronized (mPackages) {
5634            // We don't expect installation to fail beyond this point,
5635            if ((scanMode&SCAN_MONITOR) != 0) {
5636                mAppDirs.put(pkg.codePath, pkg);
5637            }
5638            // Add the new setting to mSettings
5639            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5640            // Add the new setting to mPackages
5641            mPackages.put(pkg.applicationInfo.packageName, pkg);
5642            // Make sure we don't accidentally delete its data.
5643            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5644            while (iter.hasNext()) {
5645                PackageCleanItem item = iter.next();
5646                if (pkgName.equals(item.packageName)) {
5647                    iter.remove();
5648                }
5649            }
5650
5651            // Take care of first install / last update times.
5652            if (currentTime != 0) {
5653                if (pkgSetting.firstInstallTime == 0) {
5654                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5655                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5656                    pkgSetting.lastUpdateTime = currentTime;
5657                }
5658            } else if (pkgSetting.firstInstallTime == 0) {
5659                // We need *something*.  Take time time stamp of the file.
5660                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5661            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5662                if (scanFileTime != pkgSetting.timeStamp) {
5663                    // A package on the system image has changed; consider this
5664                    // to be an update.
5665                    pkgSetting.lastUpdateTime = scanFileTime;
5666                }
5667            }
5668
5669            // Add the package's KeySets to the global KeySetManager
5670            KeySetManager ksm = mSettings.mKeySetManager;
5671            try {
5672                ksm.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5673                if (pkg.mKeySetMapping != null) {
5674                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5675                            pkg.mKeySetMapping.entrySet()) {
5676                        if (entry.getValue() != null) {
5677                            ksm.addDefinedKeySetToPackage(pkg.packageName,
5678                                entry.getValue(), entry.getKey());
5679                        }
5680                    }
5681                }
5682            } catch (NullPointerException e) {
5683                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5684            } catch (IllegalArgumentException e) {
5685                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5686            }
5687
5688            int N = pkg.providers.size();
5689            StringBuilder r = null;
5690            int i;
5691            for (i=0; i<N; i++) {
5692                PackageParser.Provider p = pkg.providers.get(i);
5693                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5694                        p.info.processName, pkg.applicationInfo.uid);
5695                mProviders.addProvider(p);
5696                p.syncable = p.info.isSyncable;
5697                if (p.info.authority != null) {
5698                    String names[] = p.info.authority.split(";");
5699                    p.info.authority = null;
5700                    for (int j = 0; j < names.length; j++) {
5701                        if (j == 1 && p.syncable) {
5702                            // We only want the first authority for a provider to possibly be
5703                            // syncable, so if we already added this provider using a different
5704                            // authority clear the syncable flag. We copy the provider before
5705                            // changing it because the mProviders object contains a reference
5706                            // to a provider that we don't want to change.
5707                            // Only do this for the second authority since the resulting provider
5708                            // object can be the same for all future authorities for this provider.
5709                            p = new PackageParser.Provider(p);
5710                            p.syncable = false;
5711                        }
5712                        if (!mProvidersByAuthority.containsKey(names[j])) {
5713                            mProvidersByAuthority.put(names[j], p);
5714                            if (p.info.authority == null) {
5715                                p.info.authority = names[j];
5716                            } else {
5717                                p.info.authority = p.info.authority + ";" + names[j];
5718                            }
5719                            if (DEBUG_PACKAGE_SCANNING) {
5720                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5721                                    Log.d(TAG, "Registered content provider: " + names[j]
5722                                            + ", className = " + p.info.name + ", isSyncable = "
5723                                            + p.info.isSyncable);
5724                            }
5725                        } else {
5726                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5727                            Slog.w(TAG, "Skipping provider name " + names[j] +
5728                                    " (in package " + pkg.applicationInfo.packageName +
5729                                    "): name already used by "
5730                                    + ((other != null && other.getComponentName() != null)
5731                                            ? other.getComponentName().getPackageName() : "?"));
5732                        }
5733                    }
5734                }
5735                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5736                    if (r == null) {
5737                        r = new StringBuilder(256);
5738                    } else {
5739                        r.append(' ');
5740                    }
5741                    r.append(p.info.name);
5742                }
5743            }
5744            if (r != null) {
5745                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5746            }
5747
5748            N = pkg.services.size();
5749            r = null;
5750            for (i=0; i<N; i++) {
5751                PackageParser.Service s = pkg.services.get(i);
5752                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5753                        s.info.processName, pkg.applicationInfo.uid);
5754                mServices.addService(s);
5755                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5756                    if (r == null) {
5757                        r = new StringBuilder(256);
5758                    } else {
5759                        r.append(' ');
5760                    }
5761                    r.append(s.info.name);
5762                }
5763            }
5764            if (r != null) {
5765                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5766            }
5767
5768            N = pkg.receivers.size();
5769            r = null;
5770            for (i=0; i<N; i++) {
5771                PackageParser.Activity a = pkg.receivers.get(i);
5772                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5773                        a.info.processName, pkg.applicationInfo.uid);
5774                mReceivers.addActivity(a, "receiver");
5775                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5776                    if (r == null) {
5777                        r = new StringBuilder(256);
5778                    } else {
5779                        r.append(' ');
5780                    }
5781                    r.append(a.info.name);
5782                }
5783            }
5784            if (r != null) {
5785                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5786            }
5787
5788            N = pkg.activities.size();
5789            r = null;
5790            for (i=0; i<N; i++) {
5791                PackageParser.Activity a = pkg.activities.get(i);
5792                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5793                        a.info.processName, pkg.applicationInfo.uid);
5794                mActivities.addActivity(a, "activity");
5795                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5796                    if (r == null) {
5797                        r = new StringBuilder(256);
5798                    } else {
5799                        r.append(' ');
5800                    }
5801                    r.append(a.info.name);
5802                }
5803            }
5804            if (r != null) {
5805                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5806            }
5807
5808            N = pkg.permissionGroups.size();
5809            r = null;
5810            for (i=0; i<N; i++) {
5811                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5812                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5813                if (cur == null) {
5814                    mPermissionGroups.put(pg.info.name, pg);
5815                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5816                        if (r == null) {
5817                            r = new StringBuilder(256);
5818                        } else {
5819                            r.append(' ');
5820                        }
5821                        r.append(pg.info.name);
5822                    }
5823                } else {
5824                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5825                            + pg.info.packageName + " ignored: original from "
5826                            + cur.info.packageName);
5827                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5828                        if (r == null) {
5829                            r = new StringBuilder(256);
5830                        } else {
5831                            r.append(' ');
5832                        }
5833                        r.append("DUP:");
5834                        r.append(pg.info.name);
5835                    }
5836                }
5837            }
5838            if (r != null) {
5839                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5840            }
5841
5842            N = pkg.permissions.size();
5843            r = null;
5844            for (i=0; i<N; i++) {
5845                PackageParser.Permission p = pkg.permissions.get(i);
5846                HashMap<String, BasePermission> permissionMap =
5847                        p.tree ? mSettings.mPermissionTrees
5848                        : mSettings.mPermissions;
5849                p.group = mPermissionGroups.get(p.info.group);
5850                if (p.info.group == null || p.group != null) {
5851                    BasePermission bp = permissionMap.get(p.info.name);
5852                    if (bp == null) {
5853                        bp = new BasePermission(p.info.name, p.info.packageName,
5854                                BasePermission.TYPE_NORMAL);
5855                        permissionMap.put(p.info.name, bp);
5856                    }
5857                    if (bp.perm == null) {
5858                        if (bp.sourcePackage != null
5859                                && !bp.sourcePackage.equals(p.info.packageName)) {
5860                            // If this is a permission that was formerly defined by a non-system
5861                            // app, but is now defined by a system app (following an upgrade),
5862                            // discard the previous declaration and consider the system's to be
5863                            // canonical.
5864                            if (isSystemApp(p.owner)) {
5865                                String msg = "New decl " + p.owner + " of permission  "
5866                                        + p.info.name + " is system";
5867                                reportSettingsProblem(Log.WARN, msg);
5868                                bp.sourcePackage = null;
5869                            }
5870                        }
5871                        if (bp.sourcePackage == null
5872                                || bp.sourcePackage.equals(p.info.packageName)) {
5873                            BasePermission tree = findPermissionTreeLP(p.info.name);
5874                            if (tree == null
5875                                    || tree.sourcePackage.equals(p.info.packageName)) {
5876                                bp.packageSetting = pkgSetting;
5877                                bp.perm = p;
5878                                bp.uid = pkg.applicationInfo.uid;
5879                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5880                                    if (r == null) {
5881                                        r = new StringBuilder(256);
5882                                    } else {
5883                                        r.append(' ');
5884                                    }
5885                                    r.append(p.info.name);
5886                                }
5887                            } else {
5888                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5889                                        + p.info.packageName + " ignored: base tree "
5890                                        + tree.name + " is from package "
5891                                        + tree.sourcePackage);
5892                            }
5893                        } else {
5894                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5895                                    + p.info.packageName + " ignored: original from "
5896                                    + bp.sourcePackage);
5897                        }
5898                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5899                        if (r == null) {
5900                            r = new StringBuilder(256);
5901                        } else {
5902                            r.append(' ');
5903                        }
5904                        r.append("DUP:");
5905                        r.append(p.info.name);
5906                    }
5907                    if (bp.perm == p) {
5908                        bp.protectionLevel = p.info.protectionLevel;
5909                    }
5910                } else {
5911                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5912                            + p.info.packageName + " ignored: no group "
5913                            + p.group);
5914                }
5915            }
5916            if (r != null) {
5917                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5918            }
5919
5920            N = pkg.instrumentation.size();
5921            r = null;
5922            for (i=0; i<N; i++) {
5923                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5924                a.info.packageName = pkg.applicationInfo.packageName;
5925                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5926                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5927                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
5928                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
5929                a.info.dataDir = pkg.applicationInfo.dataDir;
5930                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5931                mInstrumentation.put(a.getComponentName(), a);
5932                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5933                    if (r == null) {
5934                        r = new StringBuilder(256);
5935                    } else {
5936                        r.append(' ');
5937                    }
5938                    r.append(a.info.name);
5939                }
5940            }
5941            if (r != null) {
5942                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5943            }
5944
5945            if (pkg.protectedBroadcasts != null) {
5946                N = pkg.protectedBroadcasts.size();
5947                for (i=0; i<N; i++) {
5948                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5949                }
5950            }
5951
5952            pkgSetting.setTimeStamp(scanFileTime);
5953
5954            // Create idmap files for pairs of (packages, overlay packages).
5955            // Note: "android", ie framework-res.apk, is handled by native layers.
5956            if (pkg.mOverlayTarget != null) {
5957                // This is an overlay package.
5958                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5959                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5960                        mOverlays.put(pkg.mOverlayTarget,
5961                                new HashMap<String, PackageParser.Package>());
5962                    }
5963                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5964                    map.put(pkg.packageName, pkg);
5965                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5966                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5967                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5968                        return null;
5969                    }
5970                }
5971            } else if (mOverlays.containsKey(pkg.packageName) &&
5972                    !pkg.packageName.equals("android")) {
5973                // This is a regular package, with one or more known overlay packages.
5974                createIdmapsForPackageLI(pkg);
5975            }
5976        }
5977
5978        return pkg;
5979    }
5980
5981    /**
5982     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
5983     * i.e, so that all packages can be run inside a single process if required.
5984     *
5985     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
5986     * this function will either try and make the ABI for all packages in {@code packagesForUser}
5987     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
5988     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
5989     * updating a package that belongs to a shared user.
5990     */
5991    private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
5992            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
5993        String requiredInstructionSet = null;
5994        if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) {
5995            requiredInstructionSet = VMRuntime.getInstructionSet(
5996                     scannedPackage.applicationInfo.cpuAbi);
5997        }
5998
5999        PackageSetting requirer = null;
6000        for (PackageSetting ps : packagesForUser) {
6001            // If packagesForUser contains scannedPackage, we skip it. This will happen
6002            // when scannedPackage is an update of an existing package. Without this check,
6003            // we will never be able to change the ABI of any package belonging to a shared
6004            // user, even if it's compatible with other packages.
6005            if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) {
6006                if (ps.cpuAbiString == null) {
6007                    continue;
6008                }
6009
6010                final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
6011                if (requiredInstructionSet != null) {
6012                    if (!instructionSet.equals(requiredInstructionSet)) {
6013                        // We have a mismatch between instruction sets (say arm vs arm64).
6014                        // bail out.
6015                        String errorMessage = "Instruction set mismatch, "
6016                                + ((requirer == null) ? "[caller]" : requirer)
6017                                + " requires " + requiredInstructionSet + " whereas " + ps
6018                                + " requires " + instructionSet;
6019                        Slog.e(TAG, errorMessage);
6020
6021                        reportSettingsProblem(Log.WARN, errorMessage);
6022                        // Give up, don't bother making any other changes to the package settings.
6023                        return false;
6024                    }
6025                } else {
6026                    requiredInstructionSet = instructionSet;
6027                    requirer = ps;
6028                }
6029            }
6030        }
6031
6032        if (requiredInstructionSet != null) {
6033            String adjustedAbi;
6034            if (requirer != null) {
6035                // requirer != null implies that either scannedPackage was null or that scannedPackage
6036                // did not require an ABI, in which case we have to adjust scannedPackage to match
6037                // the ABI of the set (which is the same as requirer's ABI)
6038                adjustedAbi = requirer.cpuAbiString;
6039                if (scannedPackage != null) {
6040                    scannedPackage.applicationInfo.cpuAbi = adjustedAbi;
6041                }
6042            } else {
6043                // requirer == null implies that we're updating all ABIs in the set to
6044                // match scannedPackage.
6045                adjustedAbi =  scannedPackage.applicationInfo.cpuAbi;
6046            }
6047
6048            for (PackageSetting ps : packagesForUser) {
6049                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6050                    if (ps.cpuAbiString != null) {
6051                        continue;
6052                    }
6053
6054                    ps.cpuAbiString = adjustedAbi;
6055                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6056                        ps.pkg.applicationInfo.cpuAbi = adjustedAbi;
6057                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6058
6059                        if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) {
6060                            ps.cpuAbiString = null;
6061                            ps.pkg.applicationInfo.cpuAbi = null;
6062                            return false;
6063                        } else {
6064                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
6065                        }
6066                    }
6067                }
6068            }
6069        }
6070
6071        return true;
6072    }
6073
6074    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6075        synchronized (mPackages) {
6076            mResolverReplaced = true;
6077            // Set up information for custom user intent resolution activity.
6078            mResolveActivity.applicationInfo = pkg.applicationInfo;
6079            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6080            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6081            mResolveActivity.processName = null;
6082            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6083            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6084                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6085            mResolveActivity.theme = 0;
6086            mResolveActivity.exported = true;
6087            mResolveActivity.enabled = true;
6088            mResolveInfo.activityInfo = mResolveActivity;
6089            mResolveInfo.priority = 0;
6090            mResolveInfo.preferredOrder = 0;
6091            mResolveInfo.match = 0;
6092            mResolveComponentName = mCustomResolverComponentName;
6093            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6094                    mResolveComponentName);
6095        }
6096    }
6097
6098    private String calculateApkRoot(final String codePathString) {
6099        final File codePath = new File(codePathString);
6100        final File codeRoot;
6101        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6102            codeRoot = Environment.getRootDirectory();
6103        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6104            codeRoot = Environment.getOemDirectory();
6105        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6106            codeRoot = Environment.getVendorDirectory();
6107        } else {
6108            // Unrecognized code path; take its top real segment as the apk root:
6109            // e.g. /something/app/blah.apk => /something
6110            try {
6111                File f = codePath.getCanonicalFile();
6112                File parent = f.getParentFile();    // non-null because codePath is a file
6113                File tmp;
6114                while ((tmp = parent.getParentFile()) != null) {
6115                    f = parent;
6116                    parent = tmp;
6117                }
6118                codeRoot = f;
6119                Slog.w(TAG, "Unrecognized code path "
6120                        + codePath + " - using " + codeRoot);
6121            } catch (IOException e) {
6122                // Can't canonicalize the lib path -- shenanigans?
6123                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6124                return Environment.getRootDirectory().getPath();
6125            }
6126        }
6127        return codeRoot.getPath();
6128    }
6129
6130    // This is the initial scan-time determination of how to handle a given
6131    // package for purposes of native library location.
6132    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
6133            PackageSetting pkgSetting) {
6134        // "bundled" here means system-installed with no overriding update
6135        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
6136        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6137        final File libDir;
6138        if (bundledApk) {
6139            // If "/system/lib64/apkname" exists, assume that is the per-package
6140            // native library directory to use; otherwise use "/system/lib/apkname".
6141            String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6142            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
6143            File packLib64 = new File(lib64, apkName);
6144            libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
6145        } else {
6146            libDir = mAppLibInstallDir;
6147        }
6148        final String nativeLibraryPath = (new File(libDir, apkName)).getPath();
6149        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
6150        // pkgSetting might be null during rescan following uninstall of updates
6151        // to a bundled app, so accommodate that possibility.  The settings in
6152        // that case will be established later from the parsed package.
6153        if (pkgSetting != null) {
6154            pkgSetting.nativeLibraryPathString = nativeLibraryPath;
6155        }
6156    }
6157
6158    // Deduces the required ABI of an upgraded system app.
6159    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
6160        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6161        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6162
6163        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
6164        // or similar.
6165        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
6166        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
6167
6168        // Assume that the bundled native libraries always correspond to the
6169        // most preferred 32 or 64 bit ABI.
6170        if (lib64.exists()) {
6171            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6172            pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
6173        } else if (lib.exists()) {
6174            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6175            pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
6176        } else {
6177            // This is the case where the app has no native code.
6178            pkg.applicationInfo.cpuAbi = null;
6179            pkgSetting.cpuAbiString = null;
6180        }
6181    }
6182
6183    private static int copyNativeLibrariesForInternalApp(ApkHandle handle,
6184            final File nativeLibraryDir, String[] abiList) throws IOException {
6185        if (!nativeLibraryDir.isDirectory()) {
6186            nativeLibraryDir.delete();
6187
6188            if (!nativeLibraryDir.mkdir()) {
6189                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
6190            }
6191
6192            try {
6193                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6194            } catch (ErrnoException e) {
6195                throw new IOException("Cannot chmod native library directory "
6196                        + nativeLibraryDir.getPath(), e);
6197            }
6198        } else if (!SELinux.restorecon(nativeLibraryDir)) {
6199            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
6200        }
6201
6202        /*
6203         * If this is an internal application or our nativeLibraryPath points to
6204         * the app-lib directory, unpack the libraries if necessary.
6205         */
6206        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6207        if (abi >= 0) {
6208            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
6209                    nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
6210            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6211                return copyRet;
6212            }
6213        }
6214
6215        return abi;
6216    }
6217
6218    private void killApplication(String pkgName, int appId, String reason) {
6219        // Request the ActivityManager to kill the process(only for existing packages)
6220        // so that we do not end up in a confused state while the user is still using the older
6221        // version of the application while the new one gets installed.
6222        IActivityManager am = ActivityManagerNative.getDefault();
6223        if (am != null) {
6224            try {
6225                am.killApplicationWithAppId(pkgName, appId, reason);
6226            } catch (RemoteException e) {
6227            }
6228        }
6229    }
6230
6231    void removePackageLI(PackageSetting ps, boolean chatty) {
6232        if (DEBUG_INSTALL) {
6233            if (chatty)
6234                Log.d(TAG, "Removing package " + ps.name);
6235        }
6236
6237        // writer
6238        synchronized (mPackages) {
6239            mPackages.remove(ps.name);
6240            if (ps.codePathString != null) {
6241                mAppDirs.remove(ps.codePathString);
6242            }
6243
6244            final PackageParser.Package pkg = ps.pkg;
6245            if (pkg != null) {
6246                cleanPackageDataStructuresLILPw(pkg, chatty);
6247            }
6248        }
6249    }
6250
6251    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6252        if (DEBUG_INSTALL) {
6253            if (chatty)
6254                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6255        }
6256
6257        // writer
6258        synchronized (mPackages) {
6259            mPackages.remove(pkg.applicationInfo.packageName);
6260            if (pkg.codePath != null) {
6261                mAppDirs.remove(pkg.codePath);
6262            }
6263            cleanPackageDataStructuresLILPw(pkg, chatty);
6264        }
6265    }
6266
6267    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6268        int N = pkg.providers.size();
6269        StringBuilder r = null;
6270        int i;
6271        for (i=0; i<N; i++) {
6272            PackageParser.Provider p = pkg.providers.get(i);
6273            mProviders.removeProvider(p);
6274            if (p.info.authority == null) {
6275
6276                /* There was another ContentProvider with this authority when
6277                 * this app was installed so this authority is null,
6278                 * Ignore it as we don't have to unregister the provider.
6279                 */
6280                continue;
6281            }
6282            String names[] = p.info.authority.split(";");
6283            for (int j = 0; j < names.length; j++) {
6284                if (mProvidersByAuthority.get(names[j]) == p) {
6285                    mProvidersByAuthority.remove(names[j]);
6286                    if (DEBUG_REMOVE) {
6287                        if (chatty)
6288                            Log.d(TAG, "Unregistered content provider: " + names[j]
6289                                    + ", className = " + p.info.name + ", isSyncable = "
6290                                    + p.info.isSyncable);
6291                    }
6292                }
6293            }
6294            if (DEBUG_REMOVE && chatty) {
6295                if (r == null) {
6296                    r = new StringBuilder(256);
6297                } else {
6298                    r.append(' ');
6299                }
6300                r.append(p.info.name);
6301            }
6302        }
6303        if (r != null) {
6304            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6305        }
6306
6307        N = pkg.services.size();
6308        r = null;
6309        for (i=0; i<N; i++) {
6310            PackageParser.Service s = pkg.services.get(i);
6311            mServices.removeService(s);
6312            if (chatty) {
6313                if (r == null) {
6314                    r = new StringBuilder(256);
6315                } else {
6316                    r.append(' ');
6317                }
6318                r.append(s.info.name);
6319            }
6320        }
6321        if (r != null) {
6322            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6323        }
6324
6325        N = pkg.receivers.size();
6326        r = null;
6327        for (i=0; i<N; i++) {
6328            PackageParser.Activity a = pkg.receivers.get(i);
6329            mReceivers.removeActivity(a, "receiver");
6330            if (DEBUG_REMOVE && chatty) {
6331                if (r == null) {
6332                    r = new StringBuilder(256);
6333                } else {
6334                    r.append(' ');
6335                }
6336                r.append(a.info.name);
6337            }
6338        }
6339        if (r != null) {
6340            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6341        }
6342
6343        N = pkg.activities.size();
6344        r = null;
6345        for (i=0; i<N; i++) {
6346            PackageParser.Activity a = pkg.activities.get(i);
6347            mActivities.removeActivity(a, "activity");
6348            if (DEBUG_REMOVE && chatty) {
6349                if (r == null) {
6350                    r = new StringBuilder(256);
6351                } else {
6352                    r.append(' ');
6353                }
6354                r.append(a.info.name);
6355            }
6356        }
6357        if (r != null) {
6358            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6359        }
6360
6361        N = pkg.permissions.size();
6362        r = null;
6363        for (i=0; i<N; i++) {
6364            PackageParser.Permission p = pkg.permissions.get(i);
6365            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6366            if (bp == null) {
6367                bp = mSettings.mPermissionTrees.get(p.info.name);
6368            }
6369            if (bp != null && bp.perm == p) {
6370                bp.perm = null;
6371                if (DEBUG_REMOVE && chatty) {
6372                    if (r == null) {
6373                        r = new StringBuilder(256);
6374                    } else {
6375                        r.append(' ');
6376                    }
6377                    r.append(p.info.name);
6378                }
6379            }
6380        }
6381        if (r != null) {
6382            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6383        }
6384
6385        N = pkg.instrumentation.size();
6386        r = null;
6387        for (i=0; i<N; i++) {
6388            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6389            mInstrumentation.remove(a.getComponentName());
6390            if (DEBUG_REMOVE && chatty) {
6391                if (r == null) {
6392                    r = new StringBuilder(256);
6393                } else {
6394                    r.append(' ');
6395                }
6396                r.append(a.info.name);
6397            }
6398        }
6399        if (r != null) {
6400            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6401        }
6402
6403        r = null;
6404        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6405            // Only system apps can hold shared libraries.
6406            if (pkg.libraryNames != null) {
6407                for (i=0; i<pkg.libraryNames.size(); i++) {
6408                    String name = pkg.libraryNames.get(i);
6409                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6410                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6411                        mSharedLibraries.remove(name);
6412                        if (DEBUG_REMOVE && chatty) {
6413                            if (r == null) {
6414                                r = new StringBuilder(256);
6415                            } else {
6416                                r.append(' ');
6417                            }
6418                            r.append(name);
6419                        }
6420                    }
6421                }
6422            }
6423        }
6424        if (r != null) {
6425            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6426        }
6427    }
6428
6429    private static final boolean isPackageFilename(String name) {
6430        return name != null && name.endsWith(".apk");
6431    }
6432
6433    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6434        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6435            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6436                return true;
6437            }
6438        }
6439        return false;
6440    }
6441
6442    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6443    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6444    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6445
6446    private void updatePermissionsLPw(String changingPkg,
6447            PackageParser.Package pkgInfo, int flags) {
6448        // Make sure there are no dangling permission trees.
6449        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6450        while (it.hasNext()) {
6451            final BasePermission bp = it.next();
6452            if (bp.packageSetting == null) {
6453                // We may not yet have parsed the package, so just see if
6454                // we still know about its settings.
6455                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6456            }
6457            if (bp.packageSetting == null) {
6458                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6459                        + " from package " + bp.sourcePackage);
6460                it.remove();
6461            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6462                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6463                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6464                            + " from package " + bp.sourcePackage);
6465                    flags |= UPDATE_PERMISSIONS_ALL;
6466                    it.remove();
6467                }
6468            }
6469        }
6470
6471        // Make sure all dynamic permissions have been assigned to a package,
6472        // and make sure there are no dangling permissions.
6473        it = mSettings.mPermissions.values().iterator();
6474        while (it.hasNext()) {
6475            final BasePermission bp = it.next();
6476            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6477                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6478                        + bp.name + " pkg=" + bp.sourcePackage
6479                        + " info=" + bp.pendingInfo);
6480                if (bp.packageSetting == null && bp.pendingInfo != null) {
6481                    final BasePermission tree = findPermissionTreeLP(bp.name);
6482                    if (tree != null && tree.perm != null) {
6483                        bp.packageSetting = tree.packageSetting;
6484                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6485                                new PermissionInfo(bp.pendingInfo));
6486                        bp.perm.info.packageName = tree.perm.info.packageName;
6487                        bp.perm.info.name = bp.name;
6488                        bp.uid = tree.uid;
6489                    }
6490                }
6491            }
6492            if (bp.packageSetting == null) {
6493                // We may not yet have parsed the package, so just see if
6494                // we still know about its settings.
6495                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6496            }
6497            if (bp.packageSetting == null) {
6498                Slog.w(TAG, "Removing dangling permission: " + bp.name
6499                        + " from package " + bp.sourcePackage);
6500                it.remove();
6501            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6502                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6503                    Slog.i(TAG, "Removing old permission: " + bp.name
6504                            + " from package " + bp.sourcePackage);
6505                    flags |= UPDATE_PERMISSIONS_ALL;
6506                    it.remove();
6507                }
6508            }
6509        }
6510
6511        // Now update the permissions for all packages, in particular
6512        // replace the granted permissions of the system packages.
6513        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6514            for (PackageParser.Package pkg : mPackages.values()) {
6515                if (pkg != pkgInfo) {
6516                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6517                }
6518            }
6519        }
6520
6521        if (pkgInfo != null) {
6522            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6523        }
6524    }
6525
6526    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6527        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6528        if (ps == null) {
6529            return;
6530        }
6531        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6532        HashSet<String> origPermissions = gp.grantedPermissions;
6533        boolean changedPermission = false;
6534
6535        if (replace) {
6536            ps.permissionsFixed = false;
6537            if (gp == ps) {
6538                origPermissions = new HashSet<String>(gp.grantedPermissions);
6539                gp.grantedPermissions.clear();
6540                gp.gids = mGlobalGids;
6541            }
6542        }
6543
6544        if (gp.gids == null) {
6545            gp.gids = mGlobalGids;
6546        }
6547
6548        final int N = pkg.requestedPermissions.size();
6549        for (int i=0; i<N; i++) {
6550            final String name = pkg.requestedPermissions.get(i);
6551            final boolean required = pkg.requestedPermissionsRequired.get(i);
6552            final BasePermission bp = mSettings.mPermissions.get(name);
6553            if (DEBUG_INSTALL) {
6554                if (gp != ps) {
6555                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6556                }
6557            }
6558
6559            if (bp == null || bp.packageSetting == null) {
6560                Slog.w(TAG, "Unknown permission " + name
6561                        + " in package " + pkg.packageName);
6562                continue;
6563            }
6564
6565            final String perm = bp.name;
6566            boolean allowed;
6567            boolean allowedSig = false;
6568            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6569            if (level == PermissionInfo.PROTECTION_NORMAL
6570                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6571                // We grant a normal or dangerous permission if any of the following
6572                // are true:
6573                // 1) The permission is required
6574                // 2) The permission is optional, but was granted in the past
6575                // 3) The permission is optional, but was requested by an
6576                //    app in /system (not /data)
6577                //
6578                // Otherwise, reject the permission.
6579                allowed = (required || origPermissions.contains(perm)
6580                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6581            } else if (bp.packageSetting == null) {
6582                // This permission is invalid; skip it.
6583                allowed = false;
6584            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6585                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6586                if (allowed) {
6587                    allowedSig = true;
6588                }
6589            } else {
6590                allowed = false;
6591            }
6592            if (DEBUG_INSTALL) {
6593                if (gp != ps) {
6594                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6595                }
6596            }
6597            if (allowed) {
6598                if (!isSystemApp(ps) && ps.permissionsFixed) {
6599                    // If this is an existing, non-system package, then
6600                    // we can't add any new permissions to it.
6601                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6602                        // Except...  if this is a permission that was added
6603                        // to the platform (note: need to only do this when
6604                        // updating the platform).
6605                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6606                    }
6607                }
6608                if (allowed) {
6609                    if (!gp.grantedPermissions.contains(perm)) {
6610                        changedPermission = true;
6611                        gp.grantedPermissions.add(perm);
6612                        gp.gids = appendInts(gp.gids, bp.gids);
6613                    } else if (!ps.haveGids) {
6614                        gp.gids = appendInts(gp.gids, bp.gids);
6615                    }
6616                } else {
6617                    Slog.w(TAG, "Not granting permission " + perm
6618                            + " to package " + pkg.packageName
6619                            + " because it was previously installed without");
6620                }
6621            } else {
6622                if (gp.grantedPermissions.remove(perm)) {
6623                    changedPermission = true;
6624                    gp.gids = removeInts(gp.gids, bp.gids);
6625                    Slog.i(TAG, "Un-granting permission " + perm
6626                            + " from package " + pkg.packageName
6627                            + " (protectionLevel=" + bp.protectionLevel
6628                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6629                            + ")");
6630                } else {
6631                    Slog.w(TAG, "Not granting permission " + perm
6632                            + " to package " + pkg.packageName
6633                            + " (protectionLevel=" + bp.protectionLevel
6634                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6635                            + ")");
6636                }
6637            }
6638        }
6639
6640        if ((changedPermission || replace) && !ps.permissionsFixed &&
6641                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6642            // This is the first that we have heard about this package, so the
6643            // permissions we have now selected are fixed until explicitly
6644            // changed.
6645            ps.permissionsFixed = true;
6646        }
6647        ps.haveGids = true;
6648    }
6649
6650    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6651        boolean allowed = false;
6652        final int NP = PackageParser.NEW_PERMISSIONS.length;
6653        for (int ip=0; ip<NP; ip++) {
6654            final PackageParser.NewPermissionInfo npi
6655                    = PackageParser.NEW_PERMISSIONS[ip];
6656            if (npi.name.equals(perm)
6657                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6658                allowed = true;
6659                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6660                        + pkg.packageName);
6661                break;
6662            }
6663        }
6664        return allowed;
6665    }
6666
6667    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6668                                          BasePermission bp, HashSet<String> origPermissions) {
6669        boolean allowed;
6670        allowed = (compareSignatures(
6671                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6672                        == PackageManager.SIGNATURE_MATCH)
6673                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6674                        == PackageManager.SIGNATURE_MATCH);
6675        if (!allowed && (bp.protectionLevel
6676                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6677            if (isSystemApp(pkg)) {
6678                // For updated system applications, a system permission
6679                // is granted only if it had been defined by the original application.
6680                if (isUpdatedSystemApp(pkg)) {
6681                    final PackageSetting sysPs = mSettings
6682                            .getDisabledSystemPkgLPr(pkg.packageName);
6683                    final GrantedPermissions origGp = sysPs.sharedUser != null
6684                            ? sysPs.sharedUser : sysPs;
6685
6686                    if (origGp.grantedPermissions.contains(perm)) {
6687                        // If the original was granted this permission, we take
6688                        // that grant decision as read and propagate it to the
6689                        // update.
6690                        allowed = true;
6691                    } else {
6692                        // The system apk may have been updated with an older
6693                        // version of the one on the data partition, but which
6694                        // granted a new system permission that it didn't have
6695                        // before.  In this case we do want to allow the app to
6696                        // now get the new permission if the ancestral apk is
6697                        // privileged to get it.
6698                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6699                            for (int j=0;
6700                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6701                                if (perm.equals(
6702                                        sysPs.pkg.requestedPermissions.get(j))) {
6703                                    allowed = true;
6704                                    break;
6705                                }
6706                            }
6707                        }
6708                    }
6709                } else {
6710                    allowed = isPrivilegedApp(pkg);
6711                }
6712            }
6713        }
6714        if (!allowed && (bp.protectionLevel
6715                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6716            // For development permissions, a development permission
6717            // is granted only if it was already granted.
6718            allowed = origPermissions.contains(perm);
6719        }
6720        return allowed;
6721    }
6722
6723    final class ActivityIntentResolver
6724            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6725        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6726                boolean defaultOnly, int userId) {
6727            if (!sUserManager.exists(userId)) return null;
6728            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6729            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6730        }
6731
6732        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6733                int userId) {
6734            if (!sUserManager.exists(userId)) return null;
6735            mFlags = flags;
6736            return super.queryIntent(intent, resolvedType,
6737                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6738        }
6739
6740        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6741                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6742            if (!sUserManager.exists(userId)) return null;
6743            if (packageActivities == null) {
6744                return null;
6745            }
6746            mFlags = flags;
6747            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6748            final int N = packageActivities.size();
6749            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6750                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6751
6752            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6753            for (int i = 0; i < N; ++i) {
6754                intentFilters = packageActivities.get(i).intents;
6755                if (intentFilters != null && intentFilters.size() > 0) {
6756                    PackageParser.ActivityIntentInfo[] array =
6757                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6758                    intentFilters.toArray(array);
6759                    listCut.add(array);
6760                }
6761            }
6762            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6763        }
6764
6765        public final void addActivity(PackageParser.Activity a, String type) {
6766            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6767            mActivities.put(a.getComponentName(), a);
6768            if (DEBUG_SHOW_INFO)
6769                Log.v(
6770                TAG, "  " + type + " " +
6771                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6772            if (DEBUG_SHOW_INFO)
6773                Log.v(TAG, "    Class=" + a.info.name);
6774            final int NI = a.intents.size();
6775            for (int j=0; j<NI; j++) {
6776                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6777                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6778                    intent.setPriority(0);
6779                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6780                            + a.className + " with priority > 0, forcing to 0");
6781                }
6782                if (DEBUG_SHOW_INFO) {
6783                    Log.v(TAG, "    IntentFilter:");
6784                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6785                }
6786                if (!intent.debugCheck()) {
6787                    Log.w(TAG, "==> For Activity " + a.info.name);
6788                }
6789                addFilter(intent);
6790            }
6791        }
6792
6793        public final void removeActivity(PackageParser.Activity a, String type) {
6794            mActivities.remove(a.getComponentName());
6795            if (DEBUG_SHOW_INFO) {
6796                Log.v(TAG, "  " + type + " "
6797                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6798                                : a.info.name) + ":");
6799                Log.v(TAG, "    Class=" + a.info.name);
6800            }
6801            final int NI = a.intents.size();
6802            for (int j=0; j<NI; j++) {
6803                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6804                if (DEBUG_SHOW_INFO) {
6805                    Log.v(TAG, "    IntentFilter:");
6806                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6807                }
6808                removeFilter(intent);
6809            }
6810        }
6811
6812        @Override
6813        protected boolean allowFilterResult(
6814                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6815            ActivityInfo filterAi = filter.activity.info;
6816            for (int i=dest.size()-1; i>=0; i--) {
6817                ActivityInfo destAi = dest.get(i).activityInfo;
6818                if (destAi.name == filterAi.name
6819                        && destAi.packageName == filterAi.packageName) {
6820                    return false;
6821                }
6822            }
6823            return true;
6824        }
6825
6826        @Override
6827        protected ActivityIntentInfo[] newArray(int size) {
6828            return new ActivityIntentInfo[size];
6829        }
6830
6831        @Override
6832        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6833            if (!sUserManager.exists(userId)) return true;
6834            PackageParser.Package p = filter.activity.owner;
6835            if (p != null) {
6836                PackageSetting ps = (PackageSetting)p.mExtras;
6837                if (ps != null) {
6838                    // System apps are never considered stopped for purposes of
6839                    // filtering, because there may be no way for the user to
6840                    // actually re-launch them.
6841                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6842                            && ps.getStopped(userId);
6843                }
6844            }
6845            return false;
6846        }
6847
6848        @Override
6849        protected boolean isPackageForFilter(String packageName,
6850                PackageParser.ActivityIntentInfo info) {
6851            return packageName.equals(info.activity.owner.packageName);
6852        }
6853
6854        @Override
6855        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6856                int match, int userId) {
6857            if (!sUserManager.exists(userId)) return null;
6858            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6859                return null;
6860            }
6861            final PackageParser.Activity activity = info.activity;
6862            if (mSafeMode && (activity.info.applicationInfo.flags
6863                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6864                return null;
6865            }
6866            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6867            if (ps == null) {
6868                return null;
6869            }
6870            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6871                    ps.readUserState(userId), userId);
6872            if (ai == null) {
6873                return null;
6874            }
6875            final ResolveInfo res = new ResolveInfo();
6876            res.activityInfo = ai;
6877            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6878                res.filter = info;
6879            }
6880            res.priority = info.getPriority();
6881            res.preferredOrder = activity.owner.mPreferredOrder;
6882            //System.out.println("Result: " + res.activityInfo.className +
6883            //                   " = " + res.priority);
6884            res.match = match;
6885            res.isDefault = info.hasDefault;
6886            res.labelRes = info.labelRes;
6887            res.nonLocalizedLabel = info.nonLocalizedLabel;
6888            res.icon = info.icon;
6889            res.system = isSystemApp(res.activityInfo.applicationInfo);
6890            return res;
6891        }
6892
6893        @Override
6894        protected void sortResults(List<ResolveInfo> results) {
6895            Collections.sort(results, mResolvePrioritySorter);
6896        }
6897
6898        @Override
6899        protected void dumpFilter(PrintWriter out, String prefix,
6900                PackageParser.ActivityIntentInfo filter) {
6901            out.print(prefix); out.print(
6902                    Integer.toHexString(System.identityHashCode(filter.activity)));
6903                    out.print(' ');
6904                    filter.activity.printComponentShortName(out);
6905                    out.print(" filter ");
6906                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6907        }
6908
6909//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6910//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6911//            final List<ResolveInfo> retList = Lists.newArrayList();
6912//            while (i.hasNext()) {
6913//                final ResolveInfo resolveInfo = i.next();
6914//                if (isEnabledLP(resolveInfo.activityInfo)) {
6915//                    retList.add(resolveInfo);
6916//                }
6917//            }
6918//            return retList;
6919//        }
6920
6921        // Keys are String (activity class name), values are Activity.
6922        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6923                = new HashMap<ComponentName, PackageParser.Activity>();
6924        private int mFlags;
6925    }
6926
6927    private final class ServiceIntentResolver
6928            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6929        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6930                boolean defaultOnly, int userId) {
6931            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6932            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6933        }
6934
6935        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6936                int userId) {
6937            if (!sUserManager.exists(userId)) return null;
6938            mFlags = flags;
6939            return super.queryIntent(intent, resolvedType,
6940                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6941        }
6942
6943        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6944                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6945            if (!sUserManager.exists(userId)) return null;
6946            if (packageServices == null) {
6947                return null;
6948            }
6949            mFlags = flags;
6950            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6951            final int N = packageServices.size();
6952            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6953                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6954
6955            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6956            for (int i = 0; i < N; ++i) {
6957                intentFilters = packageServices.get(i).intents;
6958                if (intentFilters != null && intentFilters.size() > 0) {
6959                    PackageParser.ServiceIntentInfo[] array =
6960                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6961                    intentFilters.toArray(array);
6962                    listCut.add(array);
6963                }
6964            }
6965            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6966        }
6967
6968        public final void addService(PackageParser.Service s) {
6969            mServices.put(s.getComponentName(), s);
6970            if (DEBUG_SHOW_INFO) {
6971                Log.v(TAG, "  "
6972                        + (s.info.nonLocalizedLabel != null
6973                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6974                Log.v(TAG, "    Class=" + s.info.name);
6975            }
6976            final int NI = s.intents.size();
6977            int j;
6978            for (j=0; j<NI; j++) {
6979                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6980                if (DEBUG_SHOW_INFO) {
6981                    Log.v(TAG, "    IntentFilter:");
6982                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6983                }
6984                if (!intent.debugCheck()) {
6985                    Log.w(TAG, "==> For Service " + s.info.name);
6986                }
6987                addFilter(intent);
6988            }
6989        }
6990
6991        public final void removeService(PackageParser.Service s) {
6992            mServices.remove(s.getComponentName());
6993            if (DEBUG_SHOW_INFO) {
6994                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
6995                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6996                Log.v(TAG, "    Class=" + s.info.name);
6997            }
6998            final int NI = s.intents.size();
6999            int j;
7000            for (j=0; j<NI; j++) {
7001                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7002                if (DEBUG_SHOW_INFO) {
7003                    Log.v(TAG, "    IntentFilter:");
7004                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7005                }
7006                removeFilter(intent);
7007            }
7008        }
7009
7010        @Override
7011        protected boolean allowFilterResult(
7012                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7013            ServiceInfo filterSi = filter.service.info;
7014            for (int i=dest.size()-1; i>=0; i--) {
7015                ServiceInfo destAi = dest.get(i).serviceInfo;
7016                if (destAi.name == filterSi.name
7017                        && destAi.packageName == filterSi.packageName) {
7018                    return false;
7019                }
7020            }
7021            return true;
7022        }
7023
7024        @Override
7025        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7026            return new PackageParser.ServiceIntentInfo[size];
7027        }
7028
7029        @Override
7030        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7031            if (!sUserManager.exists(userId)) return true;
7032            PackageParser.Package p = filter.service.owner;
7033            if (p != null) {
7034                PackageSetting ps = (PackageSetting)p.mExtras;
7035                if (ps != null) {
7036                    // System apps are never considered stopped for purposes of
7037                    // filtering, because there may be no way for the user to
7038                    // actually re-launch them.
7039                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7040                            && ps.getStopped(userId);
7041                }
7042            }
7043            return false;
7044        }
7045
7046        @Override
7047        protected boolean isPackageForFilter(String packageName,
7048                PackageParser.ServiceIntentInfo info) {
7049            return packageName.equals(info.service.owner.packageName);
7050        }
7051
7052        @Override
7053        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7054                int match, int userId) {
7055            if (!sUserManager.exists(userId)) return null;
7056            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7057            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7058                return null;
7059            }
7060            final PackageParser.Service service = info.service;
7061            if (mSafeMode && (service.info.applicationInfo.flags
7062                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7063                return null;
7064            }
7065            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7066            if (ps == null) {
7067                return null;
7068            }
7069            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7070                    ps.readUserState(userId), userId);
7071            if (si == null) {
7072                return null;
7073            }
7074            final ResolveInfo res = new ResolveInfo();
7075            res.serviceInfo = si;
7076            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7077                res.filter = filter;
7078            }
7079            res.priority = info.getPriority();
7080            res.preferredOrder = service.owner.mPreferredOrder;
7081            //System.out.println("Result: " + res.activityInfo.className +
7082            //                   " = " + res.priority);
7083            res.match = match;
7084            res.isDefault = info.hasDefault;
7085            res.labelRes = info.labelRes;
7086            res.nonLocalizedLabel = info.nonLocalizedLabel;
7087            res.icon = info.icon;
7088            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7089            return res;
7090        }
7091
7092        @Override
7093        protected void sortResults(List<ResolveInfo> results) {
7094            Collections.sort(results, mResolvePrioritySorter);
7095        }
7096
7097        @Override
7098        protected void dumpFilter(PrintWriter out, String prefix,
7099                PackageParser.ServiceIntentInfo filter) {
7100            out.print(prefix); out.print(
7101                    Integer.toHexString(System.identityHashCode(filter.service)));
7102                    out.print(' ');
7103                    filter.service.printComponentShortName(out);
7104                    out.print(" filter ");
7105                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7106        }
7107
7108//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7109//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7110//            final List<ResolveInfo> retList = Lists.newArrayList();
7111//            while (i.hasNext()) {
7112//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7113//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7114//                    retList.add(resolveInfo);
7115//                }
7116//            }
7117//            return retList;
7118//        }
7119
7120        // Keys are String (activity class name), values are Activity.
7121        private final HashMap<ComponentName, PackageParser.Service> mServices
7122                = new HashMap<ComponentName, PackageParser.Service>();
7123        private int mFlags;
7124    };
7125
7126    private final class ProviderIntentResolver
7127            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7128        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7129                boolean defaultOnly, int userId) {
7130            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7131            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7132        }
7133
7134        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7135                int userId) {
7136            if (!sUserManager.exists(userId))
7137                return null;
7138            mFlags = flags;
7139            return super.queryIntent(intent, resolvedType,
7140                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7141        }
7142
7143        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7144                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7145            if (!sUserManager.exists(userId))
7146                return null;
7147            if (packageProviders == null) {
7148                return null;
7149            }
7150            mFlags = flags;
7151            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7152            final int N = packageProviders.size();
7153            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7154                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7155
7156            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7157            for (int i = 0; i < N; ++i) {
7158                intentFilters = packageProviders.get(i).intents;
7159                if (intentFilters != null && intentFilters.size() > 0) {
7160                    PackageParser.ProviderIntentInfo[] array =
7161                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7162                    intentFilters.toArray(array);
7163                    listCut.add(array);
7164                }
7165            }
7166            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7167        }
7168
7169        public final void addProvider(PackageParser.Provider p) {
7170            if (mProviders.containsKey(p.getComponentName())) {
7171                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7172                return;
7173            }
7174
7175            mProviders.put(p.getComponentName(), p);
7176            if (DEBUG_SHOW_INFO) {
7177                Log.v(TAG, "  "
7178                        + (p.info.nonLocalizedLabel != null
7179                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7180                Log.v(TAG, "    Class=" + p.info.name);
7181            }
7182            final int NI = p.intents.size();
7183            int j;
7184            for (j = 0; j < NI; j++) {
7185                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7186                if (DEBUG_SHOW_INFO) {
7187                    Log.v(TAG, "    IntentFilter:");
7188                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7189                }
7190                if (!intent.debugCheck()) {
7191                    Log.w(TAG, "==> For Provider " + p.info.name);
7192                }
7193                addFilter(intent);
7194            }
7195        }
7196
7197        public final void removeProvider(PackageParser.Provider p) {
7198            mProviders.remove(p.getComponentName());
7199            if (DEBUG_SHOW_INFO) {
7200                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7201                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7202                Log.v(TAG, "    Class=" + p.info.name);
7203            }
7204            final int NI = p.intents.size();
7205            int j;
7206            for (j = 0; j < NI; j++) {
7207                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7208                if (DEBUG_SHOW_INFO) {
7209                    Log.v(TAG, "    IntentFilter:");
7210                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7211                }
7212                removeFilter(intent);
7213            }
7214        }
7215
7216        @Override
7217        protected boolean allowFilterResult(
7218                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7219            ProviderInfo filterPi = filter.provider.info;
7220            for (int i = dest.size() - 1; i >= 0; i--) {
7221                ProviderInfo destPi = dest.get(i).providerInfo;
7222                if (destPi.name == filterPi.name
7223                        && destPi.packageName == filterPi.packageName) {
7224                    return false;
7225                }
7226            }
7227            return true;
7228        }
7229
7230        @Override
7231        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7232            return new PackageParser.ProviderIntentInfo[size];
7233        }
7234
7235        @Override
7236        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7237            if (!sUserManager.exists(userId))
7238                return true;
7239            PackageParser.Package p = filter.provider.owner;
7240            if (p != null) {
7241                PackageSetting ps = (PackageSetting) p.mExtras;
7242                if (ps != null) {
7243                    // System apps are never considered stopped for purposes of
7244                    // filtering, because there may be no way for the user to
7245                    // actually re-launch them.
7246                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7247                            && ps.getStopped(userId);
7248                }
7249            }
7250            return false;
7251        }
7252
7253        @Override
7254        protected boolean isPackageForFilter(String packageName,
7255                PackageParser.ProviderIntentInfo info) {
7256            return packageName.equals(info.provider.owner.packageName);
7257        }
7258
7259        @Override
7260        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7261                int match, int userId) {
7262            if (!sUserManager.exists(userId))
7263                return null;
7264            final PackageParser.ProviderIntentInfo info = filter;
7265            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7266                return null;
7267            }
7268            final PackageParser.Provider provider = info.provider;
7269            if (mSafeMode && (provider.info.applicationInfo.flags
7270                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7271                return null;
7272            }
7273            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7274            if (ps == null) {
7275                return null;
7276            }
7277            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7278                    ps.readUserState(userId), userId);
7279            if (pi == null) {
7280                return null;
7281            }
7282            final ResolveInfo res = new ResolveInfo();
7283            res.providerInfo = pi;
7284            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7285                res.filter = filter;
7286            }
7287            res.priority = info.getPriority();
7288            res.preferredOrder = provider.owner.mPreferredOrder;
7289            res.match = match;
7290            res.isDefault = info.hasDefault;
7291            res.labelRes = info.labelRes;
7292            res.nonLocalizedLabel = info.nonLocalizedLabel;
7293            res.icon = info.icon;
7294            res.system = isSystemApp(res.providerInfo.applicationInfo);
7295            return res;
7296        }
7297
7298        @Override
7299        protected void sortResults(List<ResolveInfo> results) {
7300            Collections.sort(results, mResolvePrioritySorter);
7301        }
7302
7303        @Override
7304        protected void dumpFilter(PrintWriter out, String prefix,
7305                PackageParser.ProviderIntentInfo filter) {
7306            out.print(prefix);
7307            out.print(
7308                    Integer.toHexString(System.identityHashCode(filter.provider)));
7309            out.print(' ');
7310            filter.provider.printComponentShortName(out);
7311            out.print(" filter ");
7312            out.println(Integer.toHexString(System.identityHashCode(filter)));
7313        }
7314
7315        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7316                = new HashMap<ComponentName, PackageParser.Provider>();
7317        private int mFlags;
7318    };
7319
7320    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7321            new Comparator<ResolveInfo>() {
7322        public int compare(ResolveInfo r1, ResolveInfo r2) {
7323            int v1 = r1.priority;
7324            int v2 = r2.priority;
7325            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7326            if (v1 != v2) {
7327                return (v1 > v2) ? -1 : 1;
7328            }
7329            v1 = r1.preferredOrder;
7330            v2 = r2.preferredOrder;
7331            if (v1 != v2) {
7332                return (v1 > v2) ? -1 : 1;
7333            }
7334            if (r1.isDefault != r2.isDefault) {
7335                return r1.isDefault ? -1 : 1;
7336            }
7337            v1 = r1.match;
7338            v2 = r2.match;
7339            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7340            if (v1 != v2) {
7341                return (v1 > v2) ? -1 : 1;
7342            }
7343            if (r1.system != r2.system) {
7344                return r1.system ? -1 : 1;
7345            }
7346            return 0;
7347        }
7348    };
7349
7350    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7351            new Comparator<ProviderInfo>() {
7352        public int compare(ProviderInfo p1, ProviderInfo p2) {
7353            final int v1 = p1.initOrder;
7354            final int v2 = p2.initOrder;
7355            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7356        }
7357    };
7358
7359    static final void sendPackageBroadcast(String action, String pkg,
7360            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7361            int[] userIds) {
7362        IActivityManager am = ActivityManagerNative.getDefault();
7363        if (am != null) {
7364            try {
7365                if (userIds == null) {
7366                    userIds = am.getRunningUserIds();
7367                }
7368                for (int id : userIds) {
7369                    final Intent intent = new Intent(action,
7370                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7371                    if (extras != null) {
7372                        intent.putExtras(extras);
7373                    }
7374                    if (targetPkg != null) {
7375                        intent.setPackage(targetPkg);
7376                    }
7377                    // Modify the UID when posting to other users
7378                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7379                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7380                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7381                        intent.putExtra(Intent.EXTRA_UID, uid);
7382                    }
7383                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7384                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7385                    if (DEBUG_BROADCASTS) {
7386                        RuntimeException here = new RuntimeException("here");
7387                        here.fillInStackTrace();
7388                        Slog.d(TAG, "Sending to user " + id + ": "
7389                                + intent.toShortString(false, true, false, false)
7390                                + " " + intent.getExtras(), here);
7391                    }
7392                    am.broadcastIntent(null, intent, null, finishedReceiver,
7393                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7394                            finishedReceiver != null, false, id);
7395                }
7396            } catch (RemoteException ex) {
7397            }
7398        }
7399    }
7400
7401    /**
7402     * Check if the external storage media is available. This is true if there
7403     * is a mounted external storage medium or if the external storage is
7404     * emulated.
7405     */
7406    private boolean isExternalMediaAvailable() {
7407        return mMediaMounted || Environment.isExternalStorageEmulated();
7408    }
7409
7410    @Override
7411    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7412        // writer
7413        synchronized (mPackages) {
7414            if (!isExternalMediaAvailable()) {
7415                // If the external storage is no longer mounted at this point,
7416                // the caller may not have been able to delete all of this
7417                // packages files and can not delete any more.  Bail.
7418                return null;
7419            }
7420            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7421            if (lastPackage != null) {
7422                pkgs.remove(lastPackage);
7423            }
7424            if (pkgs.size() > 0) {
7425                return pkgs.get(0);
7426            }
7427        }
7428        return null;
7429    }
7430
7431    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7432        if (false) {
7433            RuntimeException here = new RuntimeException("here");
7434            here.fillInStackTrace();
7435            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7436                    + " andCode=" + andCode, here);
7437        }
7438        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7439                userId, andCode ? 1 : 0, packageName));
7440    }
7441
7442    void startCleaningPackages() {
7443        // reader
7444        synchronized (mPackages) {
7445            if (!isExternalMediaAvailable()) {
7446                return;
7447            }
7448            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7449                return;
7450            }
7451        }
7452        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7453        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7454        IActivityManager am = ActivityManagerNative.getDefault();
7455        if (am != null) {
7456            try {
7457                am.startService(null, intent, null, UserHandle.USER_OWNER);
7458            } catch (RemoteException e) {
7459            }
7460        }
7461    }
7462
7463    private final class AppDirObserver extends FileObserver {
7464        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7465            super(path, mask);
7466            mRootDir = path;
7467            mIsRom = isrom;
7468            mIsPrivileged = isPrivileged;
7469        }
7470
7471        public void onEvent(int event, String path) {
7472            String removedPackage = null;
7473            int removedAppId = -1;
7474            int[] removedUsers = null;
7475            String addedPackage = null;
7476            int addedAppId = -1;
7477            int[] addedUsers = null;
7478
7479            // TODO post a message to the handler to obtain serial ordering
7480            synchronized (mInstallLock) {
7481                String fullPathStr = null;
7482                File fullPath = null;
7483                if (path != null) {
7484                    fullPath = new File(mRootDir, path);
7485                    fullPathStr = fullPath.getPath();
7486                }
7487
7488                if (DEBUG_APP_DIR_OBSERVER)
7489                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7490
7491                if (!isPackageFilename(path)) {
7492                    if (DEBUG_APP_DIR_OBSERVER)
7493                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7494                    return;
7495                }
7496
7497                // Ignore packages that are being installed or
7498                // have just been installed.
7499                if (ignoreCodePath(fullPathStr)) {
7500                    return;
7501                }
7502                PackageParser.Package p = null;
7503                PackageSetting ps = null;
7504                // reader
7505                synchronized (mPackages) {
7506                    p = mAppDirs.get(fullPathStr);
7507                    if (p != null) {
7508                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7509                        if (ps != null) {
7510                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7511                        } else {
7512                            removedUsers = sUserManager.getUserIds();
7513                        }
7514                    }
7515                    addedUsers = sUserManager.getUserIds();
7516                }
7517                if ((event&REMOVE_EVENTS) != 0) {
7518                    if (ps != null) {
7519                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7520                        removePackageLI(ps, true);
7521                        removedPackage = ps.name;
7522                        removedAppId = ps.appId;
7523                    }
7524                }
7525
7526                if ((event&ADD_EVENTS) != 0) {
7527                    if (p == null) {
7528                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7529                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7530                        if (mIsRom) {
7531                            flags |= PackageParser.PARSE_IS_SYSTEM
7532                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7533                            if (mIsPrivileged) {
7534                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7535                            }
7536                        }
7537                        p = scanPackageLI(fullPath, flags,
7538                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7539                                System.currentTimeMillis(), UserHandle.ALL, null);
7540                        if (p != null) {
7541                            /*
7542                             * TODO this seems dangerous as the package may have
7543                             * changed since we last acquired the mPackages
7544                             * lock.
7545                             */
7546                            // writer
7547                            synchronized (mPackages) {
7548                                updatePermissionsLPw(p.packageName, p,
7549                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7550                            }
7551                            addedPackage = p.applicationInfo.packageName;
7552                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7553                        }
7554                    }
7555                }
7556
7557                // reader
7558                synchronized (mPackages) {
7559                    mSettings.writeLPr();
7560                }
7561            }
7562
7563            if (removedPackage != null) {
7564                Bundle extras = new Bundle(1);
7565                extras.putInt(Intent.EXTRA_UID, removedAppId);
7566                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7567                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7568                        extras, null, null, removedUsers);
7569            }
7570            if (addedPackage != null) {
7571                Bundle extras = new Bundle(1);
7572                extras.putInt(Intent.EXTRA_UID, addedAppId);
7573                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7574                        extras, null, null, addedUsers);
7575            }
7576        }
7577
7578        private final String mRootDir;
7579        private final boolean mIsRom;
7580        private final boolean mIsPrivileged;
7581    }
7582
7583    /*
7584     * The old-style observer methods all just trampoline to the newer signature with
7585     * expanded install observer API.  The older API continues to work but does not
7586     * supply the additional details of the Observer2 API.
7587     */
7588
7589    /* Called when a downloaded package installation has been confirmed by the user */
7590    public void installPackage(
7591            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
7592        installPackageEtc(packageURI, observer, null, flags, null);
7593    }
7594
7595    /* Called when a downloaded package installation has been confirmed by the user */
7596    @Override
7597    public void installPackage(
7598            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
7599            final String installerPackageName) {
7600        installPackageWithVerificationEtc(packageURI, observer, null, flags,
7601                installerPackageName, null, null, null);
7602    }
7603
7604    @Override
7605    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
7606            int flags, String installerPackageName, Uri verificationURI,
7607            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7608        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7609                VerificationParams.NO_UID, manifestDigest);
7610        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7611                installerPackageName, verificationParams, encryptionParams);
7612    }
7613
7614    @Override
7615    public void installPackageWithVerificationAndEncryption(Uri packageURI,
7616            IPackageInstallObserver observer, int flags, String installerPackageName,
7617            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7618        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7619                installerPackageName, verificationParams, encryptionParams);
7620    }
7621
7622    /*
7623     * And here are the "live" versions that take both observer arguments
7624     */
7625    public void installPackageEtc(
7626            final Uri packageURI, final IPackageInstallObserver observer,
7627            IPackageInstallObserver2 observer2, final int flags) {
7628        installPackageEtc(packageURI, observer, observer2, flags, null);
7629    }
7630
7631    public void installPackageEtc(
7632            final Uri packageURI, final IPackageInstallObserver observer,
7633            final IPackageInstallObserver2 observer2, final int flags,
7634            final String installerPackageName) {
7635        installPackageWithVerificationEtc(packageURI, observer, observer2, flags,
7636                installerPackageName, null, null, null);
7637    }
7638
7639    @Override
7640    public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer,
7641            IPackageInstallObserver2 observer2,
7642            int flags, String installerPackageName, Uri verificationURI,
7643            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7644        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7645                VerificationParams.NO_UID, manifestDigest);
7646        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags,
7647                installerPackageName, verificationParams, encryptionParams);
7648    }
7649
7650    /*
7651     * All of the installPackage...*() methods redirect to this one for the master implementation
7652     */
7653    public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI,
7654            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7655            int flags, String installerPackageName,
7656            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7657        if (observer == null && observer2 == null) {
7658            throw new IllegalArgumentException("No install observer supplied");
7659        }
7660        installPackageWithVerificationEncryptionAndAbiOverrideEtc(packageURI, observer, observer2,
7661                flags, installerPackageName, verificationParams, encryptionParams, null);
7662    }
7663
7664    @Override
7665    public void installPackageWithVerificationEncryptionAndAbiOverrideEtc(Uri packageURI,
7666            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7667            int flags, String installerPackageName,
7668            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams,
7669            String packageAbiOverride) {
7670        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7671                null);
7672
7673        final int uid = Binder.getCallingUid();
7674        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7675            try {
7676                if (observer != null) {
7677                    observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7678                }
7679                if (observer2 != null) {
7680                    observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7681                }
7682            } catch (RemoteException re) {
7683            }
7684            return;
7685        }
7686
7687        UserHandle user;
7688        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7689            user = UserHandle.ALL;
7690        } else {
7691            user = new UserHandle(UserHandle.getUserId(uid));
7692        }
7693
7694        final int filteredFlags;
7695
7696        if (uid == Process.SHELL_UID || uid == 0) {
7697            if (DEBUG_INSTALL) {
7698                Slog.v(TAG, "Install from ADB");
7699            }
7700            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7701        } else {
7702            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7703        }
7704
7705        verificationParams.setInstallerUid(uid);
7706
7707        final Message msg = mHandler.obtainMessage(INIT_COPY);
7708        msg.obj = new InstallParams(packageURI, observer, observer2, filteredFlags,
7709                installerPackageName, verificationParams, encryptionParams, user,
7710                packageAbiOverride);
7711        mHandler.sendMessage(msg);
7712    }
7713
7714    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7715        Bundle extras = new Bundle(1);
7716        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7717
7718        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7719                packageName, extras, null, null, new int[] {userId});
7720        try {
7721            IActivityManager am = ActivityManagerNative.getDefault();
7722            final boolean isSystem =
7723                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7724            if (isSystem && am.isUserRunning(userId, false)) {
7725                // The just-installed/enabled app is bundled on the system, so presumed
7726                // to be able to run automatically without needing an explicit launch.
7727                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7728                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7729                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7730                        .setPackage(packageName);
7731                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7732                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7733            }
7734        } catch (RemoteException e) {
7735            // shouldn't happen
7736            Slog.w(TAG, "Unable to bootstrap installed package", e);
7737        }
7738    }
7739
7740    @Override
7741    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7742            int userId) {
7743        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7744        PackageSetting pkgSetting;
7745        final int uid = Binder.getCallingUid();
7746        if (UserHandle.getUserId(uid) != userId) {
7747            mContext.enforceCallingOrSelfPermission(
7748                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7749                    "setApplicationBlockedSetting for user " + userId);
7750        }
7751
7752        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7753            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7754            return false;
7755        }
7756
7757        long callingId = Binder.clearCallingIdentity();
7758        try {
7759            boolean sendAdded = false;
7760            boolean sendRemoved = false;
7761            // writer
7762            synchronized (mPackages) {
7763                pkgSetting = mSettings.mPackages.get(packageName);
7764                if (pkgSetting == null) {
7765                    return false;
7766                }
7767                if (pkgSetting.getBlocked(userId) != blocked) {
7768                    pkgSetting.setBlocked(blocked, userId);
7769                    mSettings.writePackageRestrictionsLPr(userId);
7770                    if (blocked) {
7771                        sendRemoved = true;
7772                    } else {
7773                        sendAdded = true;
7774                    }
7775                }
7776            }
7777            if (sendAdded) {
7778                sendPackageAddedForUser(packageName, pkgSetting, userId);
7779                return true;
7780            }
7781            if (sendRemoved) {
7782                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7783                        "blocking pkg");
7784                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7785            }
7786        } finally {
7787            Binder.restoreCallingIdentity(callingId);
7788        }
7789        return false;
7790    }
7791
7792    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7793            int userId) {
7794        final PackageRemovedInfo info = new PackageRemovedInfo();
7795        info.removedPackage = packageName;
7796        info.removedUsers = new int[] {userId};
7797        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7798        info.sendBroadcast(false, false, false);
7799    }
7800
7801    /**
7802     * Returns true if application is not found or there was an error. Otherwise it returns
7803     * the blocked state of the package for the given user.
7804     */
7805    @Override
7806    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7807        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7808        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7809                "getApplicationBlocked for user " + userId);
7810        PackageSetting pkgSetting;
7811        long callingId = Binder.clearCallingIdentity();
7812        try {
7813            // writer
7814            synchronized (mPackages) {
7815                pkgSetting = mSettings.mPackages.get(packageName);
7816                if (pkgSetting == null) {
7817                    return true;
7818                }
7819                return pkgSetting.getBlocked(userId);
7820            }
7821        } finally {
7822            Binder.restoreCallingIdentity(callingId);
7823        }
7824    }
7825
7826    void installStage(String basePackageName, File stageDir, IPackageInstallObserver2 observer,
7827            int flags) {
7828        // TODO: install stage!
7829        try {
7830            observer.packageInstalled(basePackageName, null,
7831                    PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
7832        } catch (RemoteException ignored) {
7833        }
7834    }
7835
7836    /**
7837     * @hide
7838     */
7839    @Override
7840    public int installExistingPackageAsUser(String packageName, int userId) {
7841        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7842                null);
7843        PackageSetting pkgSetting;
7844        final int uid = Binder.getCallingUid();
7845        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7846        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7847            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7848        }
7849
7850        long callingId = Binder.clearCallingIdentity();
7851        try {
7852            boolean sendAdded = false;
7853            Bundle extras = new Bundle(1);
7854
7855            // writer
7856            synchronized (mPackages) {
7857                pkgSetting = mSettings.mPackages.get(packageName);
7858                if (pkgSetting == null) {
7859                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7860                }
7861                if (!pkgSetting.getInstalled(userId)) {
7862                    pkgSetting.setInstalled(true, userId);
7863                    pkgSetting.setBlocked(false, userId);
7864                    mSettings.writePackageRestrictionsLPr(userId);
7865                    sendAdded = true;
7866                }
7867            }
7868
7869            if (sendAdded) {
7870                sendPackageAddedForUser(packageName, pkgSetting, userId);
7871            }
7872        } finally {
7873            Binder.restoreCallingIdentity(callingId);
7874        }
7875
7876        return PackageManager.INSTALL_SUCCEEDED;
7877    }
7878
7879    boolean isUserRestricted(int userId, String restrictionKey) {
7880        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7881        if (restrictions.getBoolean(restrictionKey, false)) {
7882            Log.w(TAG, "User is restricted: " + restrictionKey);
7883            return true;
7884        }
7885        return false;
7886    }
7887
7888    @Override
7889    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7890        mContext.enforceCallingOrSelfPermission(
7891                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7892                "Only package verification agents can verify applications");
7893
7894        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7895        final PackageVerificationResponse response = new PackageVerificationResponse(
7896                verificationCode, Binder.getCallingUid());
7897        msg.arg1 = id;
7898        msg.obj = response;
7899        mHandler.sendMessage(msg);
7900    }
7901
7902    @Override
7903    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7904            long millisecondsToDelay) {
7905        mContext.enforceCallingOrSelfPermission(
7906                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7907                "Only package verification agents can extend verification timeouts");
7908
7909        final PackageVerificationState state = mPendingVerification.get(id);
7910        final PackageVerificationResponse response = new PackageVerificationResponse(
7911                verificationCodeAtTimeout, Binder.getCallingUid());
7912
7913        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7914            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7915        }
7916        if (millisecondsToDelay < 0) {
7917            millisecondsToDelay = 0;
7918        }
7919        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7920                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7921            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7922        }
7923
7924        if ((state != null) && !state.timeoutExtended()) {
7925            state.extendTimeout();
7926
7927            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7928            msg.arg1 = id;
7929            msg.obj = response;
7930            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7931        }
7932    }
7933
7934    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7935            int verificationCode, UserHandle user) {
7936        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7937        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7938        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7939        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7940        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7941
7942        mContext.sendBroadcastAsUser(intent, user,
7943                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7944    }
7945
7946    private ComponentName matchComponentForVerifier(String packageName,
7947            List<ResolveInfo> receivers) {
7948        ActivityInfo targetReceiver = null;
7949
7950        final int NR = receivers.size();
7951        for (int i = 0; i < NR; i++) {
7952            final ResolveInfo info = receivers.get(i);
7953            if (info.activityInfo == null) {
7954                continue;
7955            }
7956
7957            if (packageName.equals(info.activityInfo.packageName)) {
7958                targetReceiver = info.activityInfo;
7959                break;
7960            }
7961        }
7962
7963        if (targetReceiver == null) {
7964            return null;
7965        }
7966
7967        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7968    }
7969
7970    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7971            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7972        if (pkgInfo.verifiers.length == 0) {
7973            return null;
7974        }
7975
7976        final int N = pkgInfo.verifiers.length;
7977        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7978        for (int i = 0; i < N; i++) {
7979            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7980
7981            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7982                    receivers);
7983            if (comp == null) {
7984                continue;
7985            }
7986
7987            final int verifierUid = getUidForVerifier(verifierInfo);
7988            if (verifierUid == -1) {
7989                continue;
7990            }
7991
7992            if (DEBUG_VERIFY) {
7993                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
7994                        + " with the correct signature");
7995            }
7996            sufficientVerifiers.add(comp);
7997            verificationState.addSufficientVerifier(verifierUid);
7998        }
7999
8000        return sufficientVerifiers;
8001    }
8002
8003    private int getUidForVerifier(VerifierInfo verifierInfo) {
8004        synchronized (mPackages) {
8005            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8006            if (pkg == null) {
8007                return -1;
8008            } else if (pkg.mSignatures.length != 1) {
8009                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8010                        + " has more than one signature; ignoring");
8011                return -1;
8012            }
8013
8014            /*
8015             * If the public key of the package's signature does not match
8016             * our expected public key, then this is a different package and
8017             * we should skip.
8018             */
8019
8020            final byte[] expectedPublicKey;
8021            try {
8022                final Signature verifierSig = pkg.mSignatures[0];
8023                final PublicKey publicKey = verifierSig.getPublicKey();
8024                expectedPublicKey = publicKey.getEncoded();
8025            } catch (CertificateException e) {
8026                return -1;
8027            }
8028
8029            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8030
8031            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8032                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8033                        + " does not have the expected public key; ignoring");
8034                return -1;
8035            }
8036
8037            return pkg.applicationInfo.uid;
8038        }
8039    }
8040
8041    @Override
8042    public void finishPackageInstall(int token) {
8043        enforceSystemOrRoot("Only the system is allowed to finish installs");
8044
8045        if (DEBUG_INSTALL) {
8046            Slog.v(TAG, "BM finishing package install for " + token);
8047        }
8048
8049        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8050        mHandler.sendMessage(msg);
8051    }
8052
8053    /**
8054     * Get the verification agent timeout.
8055     *
8056     * @return verification timeout in milliseconds
8057     */
8058    private long getVerificationTimeout() {
8059        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8060                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8061                DEFAULT_VERIFICATION_TIMEOUT);
8062    }
8063
8064    /**
8065     * Get the default verification agent response code.
8066     *
8067     * @return default verification response code
8068     */
8069    private int getDefaultVerificationResponse() {
8070        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8071                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8072                DEFAULT_VERIFICATION_RESPONSE);
8073    }
8074
8075    /**
8076     * Check whether or not package verification has been enabled.
8077     *
8078     * @return true if verification should be performed
8079     */
8080    private boolean isVerificationEnabled(int flags) {
8081        if (!DEFAULT_VERIFY_ENABLE) {
8082            return false;
8083        }
8084
8085        // Check if installing from ADB
8086        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8087            // Do not run verification in a test harness environment
8088            if (ActivityManager.isRunningInTestHarness()) {
8089                return false;
8090            }
8091            // Check if the developer does not want package verification for ADB installs
8092            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8093                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8094                return false;
8095            }
8096        }
8097
8098        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8099                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8100    }
8101
8102    /**
8103     * Get the "allow unknown sources" setting.
8104     *
8105     * @return the current "allow unknown sources" setting
8106     */
8107    private int getUnknownSourcesSettings() {
8108        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8109                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8110                -1);
8111    }
8112
8113    @Override
8114    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8115        final int uid = Binder.getCallingUid();
8116        // writer
8117        synchronized (mPackages) {
8118            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8119            if (targetPackageSetting == null) {
8120                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8121            }
8122
8123            PackageSetting installerPackageSetting;
8124            if (installerPackageName != null) {
8125                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8126                if (installerPackageSetting == null) {
8127                    throw new IllegalArgumentException("Unknown installer package: "
8128                            + installerPackageName);
8129                }
8130            } else {
8131                installerPackageSetting = null;
8132            }
8133
8134            Signature[] callerSignature;
8135            Object obj = mSettings.getUserIdLPr(uid);
8136            if (obj != null) {
8137                if (obj instanceof SharedUserSetting) {
8138                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8139                } else if (obj instanceof PackageSetting) {
8140                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8141                } else {
8142                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8143                }
8144            } else {
8145                throw new SecurityException("Unknown calling uid " + uid);
8146            }
8147
8148            // Verify: can't set installerPackageName to a package that is
8149            // not signed with the same cert as the caller.
8150            if (installerPackageSetting != null) {
8151                if (compareSignatures(callerSignature,
8152                        installerPackageSetting.signatures.mSignatures)
8153                        != PackageManager.SIGNATURE_MATCH) {
8154                    throw new SecurityException(
8155                            "Caller does not have same cert as new installer package "
8156                            + installerPackageName);
8157                }
8158            }
8159
8160            // Verify: if target already has an installer package, it must
8161            // be signed with the same cert as the caller.
8162            if (targetPackageSetting.installerPackageName != null) {
8163                PackageSetting setting = mSettings.mPackages.get(
8164                        targetPackageSetting.installerPackageName);
8165                // If the currently set package isn't valid, then it's always
8166                // okay to change it.
8167                if (setting != null) {
8168                    if (compareSignatures(callerSignature,
8169                            setting.signatures.mSignatures)
8170                            != PackageManager.SIGNATURE_MATCH) {
8171                        throw new SecurityException(
8172                                "Caller does not have same cert as old installer package "
8173                                + targetPackageSetting.installerPackageName);
8174                    }
8175                }
8176            }
8177
8178            // Okay!
8179            targetPackageSetting.installerPackageName = installerPackageName;
8180            scheduleWriteSettingsLocked();
8181        }
8182    }
8183
8184    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8185        // Queue up an async operation since the package installation may take a little while.
8186        mHandler.post(new Runnable() {
8187            public void run() {
8188                mHandler.removeCallbacks(this);
8189                 // Result object to be returned
8190                PackageInstalledInfo res = new PackageInstalledInfo();
8191                res.returnCode = currentStatus;
8192                res.uid = -1;
8193                res.pkg = null;
8194                res.removedInfo = new PackageRemovedInfo();
8195                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8196                    args.doPreInstall(res.returnCode);
8197                    synchronized (mInstallLock) {
8198                        installPackageLI(args, true, res);
8199                    }
8200                    args.doPostInstall(res.returnCode, res.uid);
8201                }
8202
8203                // A restore should be performed at this point if (a) the install
8204                // succeeded, (b) the operation is not an update, and (c) the new
8205                // package has a backupAgent defined.
8206                final boolean update = res.removedInfo.removedPackage != null;
8207                boolean doRestore = (!update
8208                        && res.pkg != null
8209                        && res.pkg.applicationInfo.backupAgentName != null);
8210
8211                // Set up the post-install work request bookkeeping.  This will be used
8212                // and cleaned up by the post-install event handling regardless of whether
8213                // there's a restore pass performed.  Token values are >= 1.
8214                int token;
8215                if (mNextInstallToken < 0) mNextInstallToken = 1;
8216                token = mNextInstallToken++;
8217
8218                PostInstallData data = new PostInstallData(args, res);
8219                mRunningInstalls.put(token, data);
8220                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8221
8222                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8223                    // Pass responsibility to the Backup Manager.  It will perform a
8224                    // restore if appropriate, then pass responsibility back to the
8225                    // Package Manager to run the post-install observer callbacks
8226                    // and broadcasts.
8227                    IBackupManager bm = IBackupManager.Stub.asInterface(
8228                            ServiceManager.getService(Context.BACKUP_SERVICE));
8229                    if (bm != null) {
8230                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8231                                + " to BM for possible restore");
8232                        try {
8233                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8234                        } catch (RemoteException e) {
8235                            // can't happen; the backup manager is local
8236                        } catch (Exception e) {
8237                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8238                            doRestore = false;
8239                        }
8240                    } else {
8241                        Slog.e(TAG, "Backup Manager not found!");
8242                        doRestore = false;
8243                    }
8244                }
8245
8246                if (!doRestore) {
8247                    // No restore possible, or the Backup Manager was mysteriously not
8248                    // available -- just fire the post-install work request directly.
8249                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8250                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8251                    mHandler.sendMessage(msg);
8252                }
8253            }
8254        });
8255    }
8256
8257    private abstract class HandlerParams {
8258        private static final int MAX_RETRIES = 4;
8259
8260        /**
8261         * Number of times startCopy() has been attempted and had a non-fatal
8262         * error.
8263         */
8264        private int mRetries = 0;
8265
8266        /** User handle for the user requesting the information or installation. */
8267        private final UserHandle mUser;
8268
8269        HandlerParams(UserHandle user) {
8270            mUser = user;
8271        }
8272
8273        UserHandle getUser() {
8274            return mUser;
8275        }
8276
8277        final boolean startCopy() {
8278            boolean res;
8279            try {
8280                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8281
8282                if (++mRetries > MAX_RETRIES) {
8283                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8284                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8285                    handleServiceError();
8286                    return false;
8287                } else {
8288                    handleStartCopy();
8289                    res = true;
8290                }
8291            } catch (RemoteException e) {
8292                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8293                mHandler.sendEmptyMessage(MCS_RECONNECT);
8294                res = false;
8295            }
8296            handleReturnCode();
8297            return res;
8298        }
8299
8300        final void serviceError() {
8301            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8302            handleServiceError();
8303            handleReturnCode();
8304        }
8305
8306        abstract void handleStartCopy() throws RemoteException;
8307        abstract void handleServiceError();
8308        abstract void handleReturnCode();
8309    }
8310
8311    class MeasureParams extends HandlerParams {
8312        private final PackageStats mStats;
8313        private boolean mSuccess;
8314
8315        private final IPackageStatsObserver mObserver;
8316
8317        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8318            super(new UserHandle(stats.userHandle));
8319            mObserver = observer;
8320            mStats = stats;
8321        }
8322
8323        @Override
8324        public String toString() {
8325            return "MeasureParams{"
8326                + Integer.toHexString(System.identityHashCode(this))
8327                + " " + mStats.packageName + "}";
8328        }
8329
8330        @Override
8331        void handleStartCopy() throws RemoteException {
8332            synchronized (mInstallLock) {
8333                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8334            }
8335
8336            if (mSuccess) {
8337                final boolean mounted;
8338                if (Environment.isExternalStorageEmulated()) {
8339                    mounted = true;
8340                } else {
8341                    final String status = Environment.getExternalStorageState();
8342                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8343                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8344                }
8345
8346                if (mounted) {
8347                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8348
8349                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8350                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8351
8352                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8353                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8354
8355                    // Always subtract cache size, since it's a subdirectory
8356                    mStats.externalDataSize -= mStats.externalCacheSize;
8357
8358                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8359                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8360
8361                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8362                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8363                }
8364            }
8365        }
8366
8367        @Override
8368        void handleReturnCode() {
8369            if (mObserver != null) {
8370                try {
8371                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8372                } catch (RemoteException e) {
8373                    Slog.i(TAG, "Observer no longer exists.");
8374                }
8375            }
8376        }
8377
8378        @Override
8379        void handleServiceError() {
8380            Slog.e(TAG, "Could not measure application " + mStats.packageName
8381                            + " external storage");
8382        }
8383    }
8384
8385    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8386            throws RemoteException {
8387        long result = 0;
8388        for (File path : paths) {
8389            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8390        }
8391        return result;
8392    }
8393
8394    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8395        for (File path : paths) {
8396            try {
8397                mcs.clearDirectory(path.getAbsolutePath());
8398            } catch (RemoteException e) {
8399            }
8400        }
8401    }
8402
8403    class InstallParams extends HandlerParams {
8404        final IPackageInstallObserver observer;
8405        final IPackageInstallObserver2 observer2;
8406        int flags;
8407
8408        private final Uri mPackageURI;
8409        final String installerPackageName;
8410        final VerificationParams verificationParams;
8411        private InstallArgs mArgs;
8412        private int mRet;
8413        private File mTempPackage;
8414        final ContainerEncryptionParams encryptionParams;
8415        final String packageAbiOverride;
8416        final String packageInstructionSetOverride;
8417
8418        InstallParams(Uri packageURI,
8419                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
8420                int flags, String installerPackageName, VerificationParams verificationParams,
8421                ContainerEncryptionParams encryptionParams, UserHandle user,
8422                String packageAbiOverride) {
8423            super(user);
8424            this.mPackageURI = packageURI;
8425            this.flags = flags;
8426            this.observer = observer;
8427            this.observer2 = observer2;
8428            this.installerPackageName = installerPackageName;
8429            this.verificationParams = verificationParams;
8430            this.encryptionParams = encryptionParams;
8431            this.packageAbiOverride = packageAbiOverride;
8432            this.packageInstructionSetOverride = (packageAbiOverride == null) ?
8433                    packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride);
8434        }
8435
8436        @Override
8437        public String toString() {
8438            return "InstallParams{"
8439                + Integer.toHexString(System.identityHashCode(this))
8440                + " " + mPackageURI + "}";
8441        }
8442
8443        public ManifestDigest getManifestDigest() {
8444            if (verificationParams == null) {
8445                return null;
8446            }
8447            return verificationParams.getManifestDigest();
8448        }
8449
8450        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8451            String packageName = pkgLite.packageName;
8452            int installLocation = pkgLite.installLocation;
8453            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8454            // reader
8455            synchronized (mPackages) {
8456                PackageParser.Package pkg = mPackages.get(packageName);
8457                if (pkg != null) {
8458                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8459                        // Check for downgrading.
8460                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8461                            if (pkgLite.versionCode < pkg.mVersionCode) {
8462                                Slog.w(TAG, "Can't install update of " + packageName
8463                                        + " update version " + pkgLite.versionCode
8464                                        + " is older than installed version "
8465                                        + pkg.mVersionCode);
8466                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8467                            }
8468                        }
8469                        // Check for updated system application.
8470                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8471                            if (onSd) {
8472                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8473                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8474                            }
8475                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8476                        } else {
8477                            if (onSd) {
8478                                // Install flag overrides everything.
8479                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8480                            }
8481                            // If current upgrade specifies particular preference
8482                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8483                                // Application explicitly specified internal.
8484                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8485                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8486                                // App explictly prefers external. Let policy decide
8487                            } else {
8488                                // Prefer previous location
8489                                if (isExternal(pkg)) {
8490                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8491                                }
8492                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8493                            }
8494                        }
8495                    } else {
8496                        // Invalid install. Return error code
8497                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8498                    }
8499                }
8500            }
8501            // All the special cases have been taken care of.
8502            // Return result based on recommended install location.
8503            if (onSd) {
8504                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8505            }
8506            return pkgLite.recommendedInstallLocation;
8507        }
8508
8509        private long getMemoryLowThreshold() {
8510            final DeviceStorageMonitorInternal
8511                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8512            if (dsm == null) {
8513                return 0L;
8514            }
8515            return dsm.getMemoryLowThreshold();
8516        }
8517
8518        /*
8519         * Invoke remote method to get package information and install
8520         * location values. Override install location based on default
8521         * policy if needed and then create install arguments based
8522         * on the install location.
8523         */
8524        public void handleStartCopy() throws RemoteException {
8525            int ret = PackageManager.INSTALL_SUCCEEDED;
8526            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8527            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8528            PackageInfoLite pkgLite = null;
8529
8530            if (onInt && onSd) {
8531                // Check if both bits are set.
8532                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8533                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8534            } else {
8535                final long lowThreshold = getMemoryLowThreshold();
8536                if (lowThreshold == 0L) {
8537                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8538                }
8539
8540                try {
8541                    mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, mPackageURI,
8542                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8543
8544                    final File packageFile;
8545                    if (encryptionParams != null || !"file".equals(mPackageURI.getScheme())) {
8546                        mTempPackage = createTempPackageFile(mDrmAppPrivateInstallDir);
8547                        if (mTempPackage != null) {
8548                            ParcelFileDescriptor out;
8549                            try {
8550                                out = ParcelFileDescriptor.open(mTempPackage,
8551                                        ParcelFileDescriptor.MODE_READ_WRITE);
8552                            } catch (FileNotFoundException e) {
8553                                out = null;
8554                                Slog.e(TAG, "Failed to create temporary file for : " + mPackageURI);
8555                            }
8556
8557                            // Make a temporary file for decryption.
8558                            ret = mContainerService
8559                                    .copyResource(mPackageURI, encryptionParams, out);
8560                            IoUtils.closeQuietly(out);
8561
8562                            packageFile = mTempPackage;
8563
8564                            FileUtils.setPermissions(packageFile.getAbsolutePath(),
8565                                    FileUtils.S_IRUSR | FileUtils.S_IWUSR | FileUtils.S_IRGRP
8566                                            | FileUtils.S_IROTH,
8567                                    -1, -1);
8568                        } else {
8569                            packageFile = null;
8570                        }
8571                    } else {
8572                        packageFile = new File(mPackageURI.getPath());
8573                    }
8574
8575                    if (packageFile != null) {
8576                        // Remote call to find out default install location
8577                        final String packageFilePath = packageFile.getAbsolutePath();
8578                        pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath, flags,
8579                                lowThreshold, packageAbiOverride);
8580
8581                        /*
8582                         * If we have too little free space, try to free cache
8583                         * before giving up.
8584                         */
8585                        if (pkgLite.recommendedInstallLocation
8586                                == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8587                            final long size = mContainerService.calculateInstalledSize(
8588                                    packageFilePath, isForwardLocked(), packageAbiOverride);
8589                            if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8590                                pkgLite = mContainerService.getMinimalPackageInfo(packageFilePath,
8591                                        flags, lowThreshold, packageAbiOverride);
8592                            }
8593                            /*
8594                             * The cache free must have deleted the file we
8595                             * downloaded to install.
8596                             *
8597                             * TODO: fix the "freeCache" call to not delete
8598                             *       the file we care about.
8599                             */
8600                            if (pkgLite.recommendedInstallLocation
8601                                    == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8602                                pkgLite.recommendedInstallLocation
8603                                    = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8604                            }
8605                        }
8606                    }
8607                } finally {
8608                    mContext.revokeUriPermission(mPackageURI,
8609                            Intent.FLAG_GRANT_READ_URI_PERMISSION);
8610                }
8611            }
8612
8613            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8614                int loc = pkgLite.recommendedInstallLocation;
8615                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8616                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8617                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8618                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8619                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8620                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8621                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8622                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8623                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8624                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8625                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8626                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8627                } else {
8628                    // Override with defaults if needed.
8629                    loc = installLocationPolicy(pkgLite, flags);
8630                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8631                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8632                    } else if (!onSd && !onInt) {
8633                        // Override install location with flags
8634                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8635                            // Set the flag to install on external media.
8636                            flags |= PackageManager.INSTALL_EXTERNAL;
8637                            flags &= ~PackageManager.INSTALL_INTERNAL;
8638                        } else {
8639                            // Make sure the flag for installing on external
8640                            // media is unset
8641                            flags |= PackageManager.INSTALL_INTERNAL;
8642                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8643                        }
8644                    }
8645                }
8646            }
8647
8648            final InstallArgs args = createInstallArgs(this);
8649            mArgs = args;
8650
8651            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8652                 /*
8653                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8654                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8655                 */
8656                int userIdentifier = getUser().getIdentifier();
8657                if (userIdentifier == UserHandle.USER_ALL
8658                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8659                    userIdentifier = UserHandle.USER_OWNER;
8660                }
8661
8662                /*
8663                 * Determine if we have any installed package verifiers. If we
8664                 * do, then we'll defer to them to verify the packages.
8665                 */
8666                final int requiredUid = mRequiredVerifierPackage == null ? -1
8667                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8668                if (requiredUid != -1 && isVerificationEnabled(flags)) {
8669                    final Intent verification = new Intent(
8670                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8671                    verification.setDataAndType(getPackageUri(), PACKAGE_MIME_TYPE);
8672                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8673
8674                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8675                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8676                            0 /* TODO: Which userId? */);
8677
8678                    if (DEBUG_VERIFY) {
8679                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8680                                + verification.toString() + " with " + pkgLite.verifiers.length
8681                                + " optional verifiers");
8682                    }
8683
8684                    final int verificationId = mPendingVerificationToken++;
8685
8686                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8687
8688                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8689                            installerPackageName);
8690
8691                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8692
8693                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8694                            pkgLite.packageName);
8695
8696                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8697                            pkgLite.versionCode);
8698
8699                    if (verificationParams != null) {
8700                        if (verificationParams.getVerificationURI() != null) {
8701                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8702                                 verificationParams.getVerificationURI());
8703                        }
8704                        if (verificationParams.getOriginatingURI() != null) {
8705                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8706                                  verificationParams.getOriginatingURI());
8707                        }
8708                        if (verificationParams.getReferrer() != null) {
8709                            verification.putExtra(Intent.EXTRA_REFERRER,
8710                                  verificationParams.getReferrer());
8711                        }
8712                        if (verificationParams.getOriginatingUid() >= 0) {
8713                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8714                                  verificationParams.getOriginatingUid());
8715                        }
8716                        if (verificationParams.getInstallerUid() >= 0) {
8717                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8718                                  verificationParams.getInstallerUid());
8719                        }
8720                    }
8721
8722                    final PackageVerificationState verificationState = new PackageVerificationState(
8723                            requiredUid, args);
8724
8725                    mPendingVerification.append(verificationId, verificationState);
8726
8727                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8728                            receivers, verificationState);
8729
8730                    /*
8731                     * If any sufficient verifiers were listed in the package
8732                     * manifest, attempt to ask them.
8733                     */
8734                    if (sufficientVerifiers != null) {
8735                        final int N = sufficientVerifiers.size();
8736                        if (N == 0) {
8737                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8738                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8739                        } else {
8740                            for (int i = 0; i < N; i++) {
8741                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8742
8743                                final Intent sufficientIntent = new Intent(verification);
8744                                sufficientIntent.setComponent(verifierComponent);
8745
8746                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8747                            }
8748                        }
8749                    }
8750
8751                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8752                            mRequiredVerifierPackage, receivers);
8753                    if (ret == PackageManager.INSTALL_SUCCEEDED
8754                            && mRequiredVerifierPackage != null) {
8755                        /*
8756                         * Send the intent to the required verification agent,
8757                         * but only start the verification timeout after the
8758                         * target BroadcastReceivers have run.
8759                         */
8760                        verification.setComponent(requiredVerifierComponent);
8761                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8762                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8763                                new BroadcastReceiver() {
8764                                    @Override
8765                                    public void onReceive(Context context, Intent intent) {
8766                                        final Message msg = mHandler
8767                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8768                                        msg.arg1 = verificationId;
8769                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8770                                    }
8771                                }, null, 0, null, null);
8772
8773                        /*
8774                         * We don't want the copy to proceed until verification
8775                         * succeeds, so null out this field.
8776                         */
8777                        mArgs = null;
8778                    }
8779                } else {
8780                    /*
8781                     * No package verification is enabled, so immediately start
8782                     * the remote call to initiate copy using temporary file.
8783                     */
8784                    ret = args.copyApk(mContainerService, true);
8785                }
8786            }
8787
8788            mRet = ret;
8789        }
8790
8791        @Override
8792        void handleReturnCode() {
8793            // If mArgs is null, then MCS couldn't be reached. When it
8794            // reconnects, it will try again to install. At that point, this
8795            // will succeed.
8796            if (mArgs != null) {
8797                processPendingInstall(mArgs, mRet);
8798
8799                if (mTempPackage != null) {
8800                    if (!mTempPackage.delete()) {
8801                        Slog.w(TAG, "Couldn't delete temporary file: " +
8802                                mTempPackage.getAbsolutePath());
8803                    }
8804                }
8805            }
8806        }
8807
8808        @Override
8809        void handleServiceError() {
8810            mArgs = createInstallArgs(this);
8811            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8812        }
8813
8814        public boolean isForwardLocked() {
8815            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8816        }
8817
8818        public Uri getPackageUri() {
8819            if (mTempPackage != null) {
8820                return Uri.fromFile(mTempPackage);
8821            } else {
8822                return mPackageURI;
8823            }
8824        }
8825    }
8826
8827    /*
8828     * Utility class used in movePackage api.
8829     * srcArgs and targetArgs are not set for invalid flags and make
8830     * sure to do null checks when invoking methods on them.
8831     * We probably want to return ErrorPrams for both failed installs
8832     * and moves.
8833     */
8834    class MoveParams extends HandlerParams {
8835        final IPackageMoveObserver observer;
8836        final int flags;
8837        final String packageName;
8838        final InstallArgs srcArgs;
8839        final InstallArgs targetArgs;
8840        int uid;
8841        int mRet;
8842
8843        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8844                String packageName, String dataDir, String instructionSet,
8845                int uid, UserHandle user) {
8846            super(user);
8847            this.srcArgs = srcArgs;
8848            this.observer = observer;
8849            this.flags = flags;
8850            this.packageName = packageName;
8851            this.uid = uid;
8852            if (srcArgs != null) {
8853                Uri packageUri = Uri.fromFile(new File(srcArgs.getCodePath()));
8854                targetArgs = createInstallArgs(packageUri, flags, packageName, dataDir, instructionSet);
8855            } else {
8856                targetArgs = null;
8857            }
8858        }
8859
8860        @Override
8861        public String toString() {
8862            return "MoveParams{"
8863                + Integer.toHexString(System.identityHashCode(this))
8864                + " " + packageName + "}";
8865        }
8866
8867        public void handleStartCopy() throws RemoteException {
8868            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8869            // Check for storage space on target medium
8870            if (!targetArgs.checkFreeStorage(mContainerService)) {
8871                Log.w(TAG, "Insufficient storage to install");
8872                return;
8873            }
8874
8875            mRet = srcArgs.doPreCopy();
8876            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8877                return;
8878            }
8879
8880            mRet = targetArgs.copyApk(mContainerService, false);
8881            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8882                srcArgs.doPostCopy(uid);
8883                return;
8884            }
8885
8886            mRet = srcArgs.doPostCopy(uid);
8887            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8888                return;
8889            }
8890
8891            mRet = targetArgs.doPreInstall(mRet);
8892            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8893                return;
8894            }
8895
8896            if (DEBUG_SD_INSTALL) {
8897                StringBuilder builder = new StringBuilder();
8898                if (srcArgs != null) {
8899                    builder.append("src: ");
8900                    builder.append(srcArgs.getCodePath());
8901                }
8902                if (targetArgs != null) {
8903                    builder.append(" target : ");
8904                    builder.append(targetArgs.getCodePath());
8905                }
8906                Log.i(TAG, builder.toString());
8907            }
8908        }
8909
8910        @Override
8911        void handleReturnCode() {
8912            targetArgs.doPostInstall(mRet, uid);
8913            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8914            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8915                currentStatus = PackageManager.MOVE_SUCCEEDED;
8916            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8917                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8918            }
8919            processPendingMove(this, currentStatus);
8920        }
8921
8922        @Override
8923        void handleServiceError() {
8924            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8925        }
8926    }
8927
8928    /**
8929     * Used during creation of InstallArgs
8930     *
8931     * @param flags package installation flags
8932     * @return true if should be installed on external storage
8933     */
8934    private static boolean installOnSd(int flags) {
8935        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8936            return false;
8937        }
8938        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8939            return true;
8940        }
8941        return false;
8942    }
8943
8944    /**
8945     * Used during creation of InstallArgs
8946     *
8947     * @param flags package installation flags
8948     * @return true if should be installed as forward locked
8949     */
8950    private static boolean installForwardLocked(int flags) {
8951        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8952    }
8953
8954    private InstallArgs createInstallArgs(InstallParams params) {
8955        if (installOnSd(params.flags) || params.isForwardLocked()) {
8956            return new AsecInstallArgs(params);
8957        } else {
8958            return new FileInstallArgs(params);
8959        }
8960    }
8961
8962    private InstallArgs createInstallArgs(int flags, String fullCodePath, String fullResourcePath,
8963            String nativeLibraryPath, String instructionSet) {
8964        final boolean isInAsec;
8965        if (installOnSd(flags)) {
8966            /* Apps on SD card are always in ASEC containers. */
8967            isInAsec = true;
8968        } else if (installForwardLocked(flags)
8969                && !fullCodePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8970            /*
8971             * Forward-locked apps are only in ASEC containers if they're the
8972             * new style
8973             */
8974            isInAsec = true;
8975        } else {
8976            isInAsec = false;
8977        }
8978
8979        if (isInAsec) {
8980            return new AsecInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8981                    instructionSet, installOnSd(flags), installForwardLocked(flags));
8982        } else {
8983            return new FileInstallArgs(fullCodePath, fullResourcePath, nativeLibraryPath,
8984                    instructionSet);
8985        }
8986    }
8987
8988    // Used by package mover
8989    private InstallArgs createInstallArgs(Uri packageURI, int flags, String pkgName, String dataDir,
8990            String instructionSet) {
8991        if (installOnSd(flags) || installForwardLocked(flags)) {
8992            String cid = getNextCodePath(packageURI.getPath(), pkgName, "/"
8993                    + AsecInstallArgs.RES_FILE_NAME);
8994            return new AsecInstallArgs(packageURI, cid, instructionSet, installOnSd(flags),
8995                    installForwardLocked(flags));
8996        } else {
8997            return new FileInstallArgs(packageURI, pkgName, dataDir, instructionSet);
8998        }
8999    }
9000
9001    static abstract class InstallArgs {
9002        final IPackageInstallObserver observer;
9003        final IPackageInstallObserver2 observer2;
9004        // Always refers to PackageManager flags only
9005        final int flags;
9006        final Uri packageURI;
9007        final String installerPackageName;
9008        final ManifestDigest manifestDigest;
9009        final UserHandle user;
9010        final String instructionSet;
9011        final String abiOverride;
9012
9013        InstallArgs(Uri packageURI,
9014                IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
9015                int flags, String installerPackageName, ManifestDigest manifestDigest,
9016                UserHandle user, String instructionSet, String abiOverride) {
9017            this.packageURI = packageURI;
9018            this.flags = flags;
9019            this.observer = observer;
9020            this.observer2 = observer2;
9021            this.installerPackageName = installerPackageName;
9022            this.manifestDigest = manifestDigest;
9023            this.user = user;
9024            this.instructionSet = instructionSet;
9025            this.abiOverride = abiOverride;
9026        }
9027
9028        abstract void createCopyFile();
9029        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9030        abstract int doPreInstall(int status);
9031        abstract boolean doRename(int status, String pkgName, String oldCodePath);
9032
9033        abstract int doPostInstall(int status, int uid);
9034        abstract String getCodePath();
9035        abstract String getResourcePath();
9036        abstract String getNativeLibraryPath();
9037        // Need installer lock especially for dex file removal.
9038        abstract void cleanUpResourcesLI();
9039        abstract boolean doPostDeleteLI(boolean delete);
9040        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9041
9042        String[] getSplitCodePaths() {
9043            return null;
9044        }
9045
9046        /**
9047         * Called before the source arguments are copied. This is used mostly
9048         * for MoveParams when it needs to read the source file to put it in the
9049         * destination.
9050         */
9051        int doPreCopy() {
9052            return PackageManager.INSTALL_SUCCEEDED;
9053        }
9054
9055        /**
9056         * Called after the source arguments are copied. This is used mostly for
9057         * MoveParams when it needs to read the source file to put it in the
9058         * destination.
9059         *
9060         * @return
9061         */
9062        int doPostCopy(int uid) {
9063            return PackageManager.INSTALL_SUCCEEDED;
9064        }
9065
9066        protected boolean isFwdLocked() {
9067            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9068        }
9069
9070        UserHandle getUser() {
9071            return user;
9072        }
9073    }
9074
9075    class FileInstallArgs extends InstallArgs {
9076        File installDir;
9077        String codeFileName;
9078        String resourceFileName;
9079        String libraryPath;
9080        boolean created = false;
9081
9082        FileInstallArgs(InstallParams params) {
9083            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9084                    params.installerPackageName, params.getManifestDigest(),
9085                    params.getUser(), params.packageInstructionSetOverride,
9086                    params.packageAbiOverride);
9087        }
9088
9089        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9090                String instructionSet) {
9091            super(null, null, null, 0, null, null, null, instructionSet, null);
9092            File codeFile = new File(fullCodePath);
9093            installDir = codeFile.getParentFile();
9094            codeFileName = fullCodePath;
9095            resourceFileName = fullResourcePath;
9096            libraryPath = nativeLibraryPath;
9097        }
9098
9099        FileInstallArgs(Uri packageURI, String pkgName, String dataDir, String instructionSet) {
9100            super(packageURI, null, null, 0, null, null, null, instructionSet, null);
9101            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9102            String apkName = getNextCodePath(null, pkgName, ".apk");
9103            codeFileName = new File(installDir, apkName + ".apk").getPath();
9104            resourceFileName = getResourcePathFromCodePath();
9105            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
9106        }
9107
9108        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9109            final long lowThreshold;
9110
9111            final DeviceStorageMonitorInternal
9112                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9113            if (dsm == null) {
9114                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9115                lowThreshold = 0L;
9116            } else {
9117                if (dsm.isMemoryLow()) {
9118                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9119                    return false;
9120                }
9121
9122                lowThreshold = dsm.getMemoryLowThreshold();
9123            }
9124
9125            try {
9126                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9127                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9128                return imcs.checkInternalFreeStorage(packageURI, isFwdLocked(), lowThreshold);
9129            } finally {
9130                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9131            }
9132        }
9133
9134        void createCopyFile() {
9135            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9136            codeFileName = createTempPackageFile(installDir).getPath();
9137            resourceFileName = getResourcePathFromCodePath();
9138            libraryPath = getLibraryPathFromCodePath();
9139            created = true;
9140        }
9141
9142        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9143            if (temp) {
9144                // Generate temp file name
9145                createCopyFile();
9146            }
9147            // Get a ParcelFileDescriptor to write to the output file
9148            File codeFile = new File(codeFileName);
9149            if (!created) {
9150                try {
9151                    codeFile.createNewFile();
9152                    // Set permissions
9153                    if (!setPermissions()) {
9154                        // Failed setting permissions.
9155                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9156                    }
9157                } catch (IOException e) {
9158                   Slog.w(TAG, "Failed to create file " + codeFile);
9159                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9160                }
9161            }
9162            ParcelFileDescriptor out = null;
9163            try {
9164                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
9165            } catch (FileNotFoundException e) {
9166                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
9167                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9168            }
9169            // Copy the resource now
9170            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9171            try {
9172                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9173                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9174                ret = imcs.copyResource(packageURI, null, out);
9175            } finally {
9176                IoUtils.closeQuietly(out);
9177                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9178            }
9179
9180            if (isFwdLocked()) {
9181                final File destResourceFile = new File(getResourcePath());
9182
9183                // Copy the public files
9184                try {
9185                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
9186                } catch (IOException e) {
9187                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
9188                            + " forward-locked app.");
9189                    destResourceFile.delete();
9190                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9191                }
9192            }
9193
9194            final File nativeLibraryFile = new File(getNativeLibraryPath());
9195            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
9196            if (nativeLibraryFile.exists()) {
9197                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9198                nativeLibraryFile.delete();
9199            }
9200
9201            final NativeLibraryHelper.ApkHandle handle = new NativeLibraryHelper.ApkHandle(codeFile);
9202            String[] abiList = (abiOverride != null) ?
9203                    new String[] { abiOverride } : Build.SUPPORTED_ABIS;
9204            try {
9205                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
9206                        abiOverride == null &&
9207                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9208                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9209                }
9210
9211                int copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList);
9212                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9213                    return copyRet;
9214                }
9215            } catch (IOException e) {
9216                Slog.e(TAG, "Copying native libraries failed", e);
9217                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9218            } finally {
9219                handle.close();
9220            }
9221
9222            return ret;
9223        }
9224
9225        int doPreInstall(int status) {
9226            if (status != PackageManager.INSTALL_SUCCEEDED) {
9227                cleanUp();
9228            }
9229            return status;
9230        }
9231
9232        boolean doRename(int status, final String pkgName, String oldCodePath) {
9233            if (status != PackageManager.INSTALL_SUCCEEDED) {
9234                cleanUp();
9235                return false;
9236            } else {
9237                final File oldCodeFile = new File(getCodePath());
9238                final File oldResourceFile = new File(getResourcePath());
9239                final File oldLibraryFile = new File(getNativeLibraryPath());
9240
9241                // Rename APK file based on packageName
9242                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
9243                final File newCodeFile = new File(installDir, apkName + ".apk");
9244                if (!oldCodeFile.renameTo(newCodeFile)) {
9245                    return false;
9246                }
9247                codeFileName = newCodeFile.getPath();
9248
9249                // Rename public resource file if it's forward-locked.
9250                final File newResFile = new File(getResourcePathFromCodePath());
9251                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
9252                    return false;
9253                }
9254                resourceFileName = newResFile.getPath();
9255
9256                // Rename library path
9257                final File newLibraryFile = new File(getLibraryPathFromCodePath());
9258                if (newLibraryFile.exists()) {
9259                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
9260                    newLibraryFile.delete();
9261                }
9262                if (!oldLibraryFile.renameTo(newLibraryFile)) {
9263                    Slog.e(TAG, "Cannot rename native library directory "
9264                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
9265                    return false;
9266                }
9267                libraryPath = newLibraryFile.getPath();
9268
9269                // Attempt to set permissions
9270                if (!setPermissions()) {
9271                    return false;
9272                }
9273
9274                if (!SELinux.restorecon(newCodeFile)) {
9275                    return false;
9276                }
9277
9278                return true;
9279            }
9280        }
9281
9282        int doPostInstall(int status, int uid) {
9283            if (status != PackageManager.INSTALL_SUCCEEDED) {
9284                cleanUp();
9285            }
9286            return status;
9287        }
9288
9289        private String getResourcePathFromCodePath() {
9290            final String codePath = getCodePath();
9291            if (isFwdLocked()) {
9292                final StringBuilder sb = new StringBuilder();
9293
9294                sb.append(mAppInstallDir.getPath());
9295                sb.append('/');
9296                sb.append(getApkName(codePath));
9297                sb.append(".zip");
9298
9299                /*
9300                 * If our APK is a temporary file, mark the resource as a
9301                 * temporary file as well so it can be cleaned up after
9302                 * catastrophic failure.
9303                 */
9304                if (codePath.endsWith(".tmp")) {
9305                    sb.append(".tmp");
9306                }
9307
9308                return sb.toString();
9309            } else {
9310                return codePath;
9311            }
9312        }
9313
9314        private String getLibraryPathFromCodePath() {
9315            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
9316        }
9317
9318        @Override
9319        String getCodePath() {
9320            return codeFileName;
9321        }
9322
9323        @Override
9324        String getResourcePath() {
9325            return resourceFileName;
9326        }
9327
9328        @Override
9329        String getNativeLibraryPath() {
9330            if (libraryPath == null) {
9331                libraryPath = getLibraryPathFromCodePath();
9332            }
9333            return libraryPath;
9334        }
9335
9336        private boolean cleanUp() {
9337            boolean ret = true;
9338            String sourceDir = getCodePath();
9339            String publicSourceDir = getResourcePath();
9340            if (sourceDir != null) {
9341                File sourceFile = new File(sourceDir);
9342                if (!sourceFile.exists()) {
9343                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
9344                    ret = false;
9345                }
9346                // Delete application's code and resources
9347                sourceFile.delete();
9348            }
9349            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
9350                final File publicSourceFile = new File(publicSourceDir);
9351                if (!publicSourceFile.exists()) {
9352                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
9353                }
9354                if (publicSourceFile.exists()) {
9355                    publicSourceFile.delete();
9356                }
9357            }
9358
9359            if (libraryPath != null) {
9360                File nativeLibraryFile = new File(libraryPath);
9361                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9362                if (!nativeLibraryFile.delete()) {
9363                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
9364                }
9365            }
9366
9367            return ret;
9368        }
9369
9370        void cleanUpResourcesLI() {
9371            String sourceDir = getCodePath();
9372            if (cleanUp()) {
9373                if (instructionSet == null) {
9374                    throw new IllegalStateException("instructionSet == null");
9375                }
9376                int retCode = mInstaller.rmdex(sourceDir, instructionSet);
9377                if (retCode < 0) {
9378                    Slog.w(TAG, "Couldn't remove dex file for package: "
9379                            +  " at location "
9380                            + sourceDir + ", retcode=" + retCode);
9381                    // we don't consider this to be a failure of the core package deletion
9382                }
9383            }
9384        }
9385
9386        private boolean setPermissions() {
9387            // TODO Do this in a more elegant way later on. for now just a hack
9388            if (!isFwdLocked()) {
9389                final int filePermissions =
9390                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
9391                    |FileUtils.S_IROTH;
9392                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
9393                if (retCode != 0) {
9394                    Slog.e(TAG, "Couldn't set new package file permissions for " +
9395                            getCodePath()
9396                            + ". The return code was: " + retCode);
9397                    // TODO Define new internal error
9398                    return false;
9399                }
9400                return true;
9401            }
9402            return true;
9403        }
9404
9405        boolean doPostDeleteLI(boolean delete) {
9406            // XXX err, shouldn't we respect the delete flag?
9407            cleanUpResourcesLI();
9408            return true;
9409        }
9410    }
9411
9412    private boolean isAsecExternal(String cid) {
9413        final String asecPath = PackageHelper.getSdFilesystem(cid);
9414        return !asecPath.startsWith(mAsecInternalPath);
9415    }
9416
9417    /**
9418     * Extract the MountService "container ID" from the full code path of an
9419     * .apk.
9420     */
9421    static String cidFromCodePath(String fullCodePath) {
9422        int eidx = fullCodePath.lastIndexOf("/");
9423        String subStr1 = fullCodePath.substring(0, eidx);
9424        int sidx = subStr1.lastIndexOf("/");
9425        return subStr1.substring(sidx+1, eidx);
9426    }
9427
9428    class AsecInstallArgs extends InstallArgs {
9429        static final String RES_FILE_NAME = "pkg.apk";
9430        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9431
9432        String cid;
9433        String packagePath;
9434        String resourcePath;
9435        String libraryPath;
9436
9437        AsecInstallArgs(InstallParams params) {
9438            super(params.getPackageUri(), params.observer, params.observer2, params.flags,
9439                    params.installerPackageName, params.getManifestDigest(),
9440                    params.getUser(), params.packageInstructionSetOverride,
9441                    params.packageAbiOverride);
9442        }
9443
9444        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9445                String instructionSet, boolean isExternal, boolean isForwardLocked) {
9446            super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9447                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9448                    null, null, null, instructionSet, null);
9449            // Extract cid from fullCodePath
9450            int eidx = fullCodePath.lastIndexOf("/");
9451            String subStr1 = fullCodePath.substring(0, eidx);
9452            int sidx = subStr1.lastIndexOf("/");
9453            cid = subStr1.substring(sidx+1, eidx);
9454            setCachePath(subStr1);
9455        }
9456
9457        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
9458            super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
9459                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9460                    null, null, null, instructionSet, null);
9461            this.cid = cid;
9462            setCachePath(PackageHelper.getSdDir(cid));
9463        }
9464
9465        AsecInstallArgs(Uri packageURI, String cid, String instructionSet,
9466                boolean isExternal, boolean isForwardLocked) {
9467            super(packageURI, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9468                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9469                    null, null, null, instructionSet, null);
9470            this.cid = cid;
9471        }
9472
9473        void createCopyFile() {
9474            cid = getTempContainerId();
9475        }
9476
9477        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9478            try {
9479                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9480                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9481                return imcs.checkExternalFreeStorage(packageURI, isFwdLocked(), abiOverride);
9482            } finally {
9483                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9484            }
9485        }
9486
9487        private final boolean isExternal() {
9488            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9489        }
9490
9491        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9492            if (temp) {
9493                createCopyFile();
9494            } else {
9495                /*
9496                 * Pre-emptively destroy the container since it's destroyed if
9497                 * copying fails due to it existing anyway.
9498                 */
9499                PackageHelper.destroySdDir(cid);
9500            }
9501
9502            final String newCachePath;
9503            try {
9504                mContext.grantUriPermission(DEFAULT_CONTAINER_PACKAGE, packageURI,
9505                        Intent.FLAG_GRANT_READ_URI_PERMISSION);
9506                newCachePath = imcs.copyResourceToContainer(packageURI, cid, getEncryptKey(),
9507                        RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(), isFwdLocked(),
9508                        abiOverride);
9509            } finally {
9510                mContext.revokeUriPermission(packageURI, Intent.FLAG_GRANT_READ_URI_PERMISSION);
9511            }
9512
9513            if (newCachePath != null) {
9514                setCachePath(newCachePath);
9515                return PackageManager.INSTALL_SUCCEEDED;
9516            } else {
9517                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9518            }
9519        }
9520
9521        @Override
9522        String getCodePath() {
9523            return packagePath;
9524        }
9525
9526        @Override
9527        String getResourcePath() {
9528            return resourcePath;
9529        }
9530
9531        @Override
9532        String getNativeLibraryPath() {
9533            return libraryPath;
9534        }
9535
9536        int doPreInstall(int status) {
9537            if (status != PackageManager.INSTALL_SUCCEEDED) {
9538                // Destroy container
9539                PackageHelper.destroySdDir(cid);
9540            } else {
9541                boolean mounted = PackageHelper.isContainerMounted(cid);
9542                if (!mounted) {
9543                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9544                            Process.SYSTEM_UID);
9545                    if (newCachePath != null) {
9546                        setCachePath(newCachePath);
9547                    } else {
9548                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9549                    }
9550                }
9551            }
9552            return status;
9553        }
9554
9555        boolean doRename(int status, final String pkgName,
9556                String oldCodePath) {
9557            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
9558            String newCachePath = null;
9559            if (PackageHelper.isContainerMounted(cid)) {
9560                // Unmount the container
9561                if (!PackageHelper.unMountSdDir(cid)) {
9562                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9563                    return false;
9564                }
9565            }
9566            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9567                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9568                        " which might be stale. Will try to clean up.");
9569                // Clean up the stale container and proceed to recreate.
9570                if (!PackageHelper.destroySdDir(newCacheId)) {
9571                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9572                    return false;
9573                }
9574                // Successfully cleaned up stale container. Try to rename again.
9575                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9576                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9577                            + " inspite of cleaning it up.");
9578                    return false;
9579                }
9580            }
9581            if (!PackageHelper.isContainerMounted(newCacheId)) {
9582                Slog.w(TAG, "Mounting container " + newCacheId);
9583                newCachePath = PackageHelper.mountSdDir(newCacheId,
9584                        getEncryptKey(), Process.SYSTEM_UID);
9585            } else {
9586                newCachePath = PackageHelper.getSdDir(newCacheId);
9587            }
9588            if (newCachePath == null) {
9589                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9590                return false;
9591            }
9592            Log.i(TAG, "Succesfully renamed " + cid +
9593                    " to " + newCacheId +
9594                    " at new path: " + newCachePath);
9595            cid = newCacheId;
9596            setCachePath(newCachePath);
9597            return true;
9598        }
9599
9600        private void setCachePath(String newCachePath) {
9601            File cachePath = new File(newCachePath);
9602            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
9603            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9604
9605            if (isFwdLocked()) {
9606                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9607            } else {
9608                resourcePath = packagePath;
9609            }
9610        }
9611
9612        int doPostInstall(int status, int uid) {
9613            if (status != PackageManager.INSTALL_SUCCEEDED) {
9614                cleanUp();
9615            } else {
9616                final int groupOwner;
9617                final String protectedFile;
9618                if (isFwdLocked()) {
9619                    groupOwner = UserHandle.getSharedAppGid(uid);
9620                    protectedFile = RES_FILE_NAME;
9621                } else {
9622                    groupOwner = -1;
9623                    protectedFile = null;
9624                }
9625
9626                if (uid < Process.FIRST_APPLICATION_UID
9627                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9628                    Slog.e(TAG, "Failed to finalize " + cid);
9629                    PackageHelper.destroySdDir(cid);
9630                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9631                }
9632
9633                boolean mounted = PackageHelper.isContainerMounted(cid);
9634                if (!mounted) {
9635                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9636                }
9637            }
9638            return status;
9639        }
9640
9641        private void cleanUp() {
9642            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9643
9644            // Destroy secure container
9645            PackageHelper.destroySdDir(cid);
9646        }
9647
9648        void cleanUpResourcesLI() {
9649            String sourceFile = getCodePath();
9650            // Remove dex file
9651            if (instructionSet == null) {
9652                throw new IllegalStateException("instructionSet == null");
9653            }
9654            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9655            if (retCode < 0) {
9656                Slog.w(TAG, "Couldn't remove dex file for package: "
9657                        + " at location "
9658                        + sourceFile.toString() + ", retcode=" + retCode);
9659                // we don't consider this to be a failure of the core package deletion
9660            }
9661            cleanUp();
9662        }
9663
9664        boolean matchContainer(String app) {
9665            if (cid.startsWith(app)) {
9666                return true;
9667            }
9668            return false;
9669        }
9670
9671        String getPackageName() {
9672            return getAsecPackageName(cid);
9673        }
9674
9675        boolean doPostDeleteLI(boolean delete) {
9676            boolean ret = false;
9677            boolean mounted = PackageHelper.isContainerMounted(cid);
9678            if (mounted) {
9679                // Unmount first
9680                ret = PackageHelper.unMountSdDir(cid);
9681            }
9682            if (ret && delete) {
9683                cleanUpResourcesLI();
9684            }
9685            return ret;
9686        }
9687
9688        @Override
9689        int doPreCopy() {
9690            if (isFwdLocked()) {
9691                if (!PackageHelper.fixSdPermissions(cid,
9692                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9693                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9694                }
9695            }
9696
9697            return PackageManager.INSTALL_SUCCEEDED;
9698        }
9699
9700        @Override
9701        int doPostCopy(int uid) {
9702            if (isFwdLocked()) {
9703                if (uid < Process.FIRST_APPLICATION_UID
9704                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9705                                RES_FILE_NAME)) {
9706                    Slog.e(TAG, "Failed to finalize " + cid);
9707                    PackageHelper.destroySdDir(cid);
9708                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9709                }
9710            }
9711
9712            return PackageManager.INSTALL_SUCCEEDED;
9713        }
9714    }
9715
9716    static String getAsecPackageName(String packageCid) {
9717        int idx = packageCid.lastIndexOf("-");
9718        if (idx == -1) {
9719            return packageCid;
9720        }
9721        return packageCid.substring(0, idx);
9722    }
9723
9724    // Utility method used to create code paths based on package name and available index.
9725    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9726        String idxStr = "";
9727        int idx = 1;
9728        // Fall back to default value of idx=1 if prefix is not
9729        // part of oldCodePath
9730        if (oldCodePath != null) {
9731            String subStr = oldCodePath;
9732            // Drop the suffix right away
9733            if (subStr.endsWith(suffix)) {
9734                subStr = subStr.substring(0, subStr.length() - suffix.length());
9735            }
9736            // If oldCodePath already contains prefix find out the
9737            // ending index to either increment or decrement.
9738            int sidx = subStr.lastIndexOf(prefix);
9739            if (sidx != -1) {
9740                subStr = subStr.substring(sidx + prefix.length());
9741                if (subStr != null) {
9742                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9743                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9744                    }
9745                    try {
9746                        idx = Integer.parseInt(subStr);
9747                        if (idx <= 1) {
9748                            idx++;
9749                        } else {
9750                            idx--;
9751                        }
9752                    } catch(NumberFormatException e) {
9753                    }
9754                }
9755            }
9756        }
9757        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9758        return prefix + idxStr;
9759    }
9760
9761    // Utility method used to ignore ADD/REMOVE events
9762    // by directory observer.
9763    private static boolean ignoreCodePath(String fullPathStr) {
9764        String apkName = getApkName(fullPathStr);
9765        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9766        if (idx != -1 && ((idx+1) < apkName.length())) {
9767            // Make sure the package ends with a numeral
9768            String version = apkName.substring(idx+1);
9769            try {
9770                Integer.parseInt(version);
9771                return true;
9772            } catch (NumberFormatException e) {}
9773        }
9774        return false;
9775    }
9776
9777    // Utility method that returns the relative package path with respect
9778    // to the installation directory. Like say for /data/data/com.test-1.apk
9779    // string com.test-1 is returned.
9780    static String getApkName(String codePath) {
9781        if (codePath == null) {
9782            return null;
9783        }
9784        int sidx = codePath.lastIndexOf("/");
9785        int eidx = codePath.lastIndexOf(".");
9786        if (eidx == -1) {
9787            eidx = codePath.length();
9788        } else if (eidx == 0) {
9789            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
9790            return null;
9791        }
9792        return codePath.substring(sidx+1, eidx);
9793    }
9794
9795    private static String[] deriveSplitResPaths(String[] splitCodePaths) {
9796        String[] splitResPaths = null;
9797        if (!ArrayUtils.isEmpty(splitCodePaths)) {
9798            splitResPaths = new String[splitCodePaths.length];
9799            for (int i = 0; i < splitCodePaths.length; i++) {
9800                final String splitCodePath = splitCodePaths[i];
9801                final String resName = getApkName(splitCodePath) + ".zip";
9802                splitResPaths[i] = new File(new File(splitCodePath).getParentFile(),
9803                        resName).getAbsolutePath();
9804            }
9805        }
9806        return splitResPaths;
9807    }
9808
9809    class PackageInstalledInfo {
9810        String name;
9811        int uid;
9812        // The set of users that originally had this package installed.
9813        int[] origUsers;
9814        // The set of users that now have this package installed.
9815        int[] newUsers;
9816        PackageParser.Package pkg;
9817        int returnCode;
9818        PackageRemovedInfo removedInfo;
9819
9820        // In some error cases we want to convey more info back to the observer
9821        String origPackage;
9822        String origPermission;
9823    }
9824
9825    /*
9826     * Install a non-existing package.
9827     */
9828    private void installNewPackageLI(PackageParser.Package pkg,
9829            int parseFlags, int scanMode, UserHandle user,
9830            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9831        // Remember this for later, in case we need to rollback this install
9832        String pkgName = pkg.packageName;
9833
9834        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9835        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9836        synchronized(mPackages) {
9837            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9838                // A package with the same name is already installed, though
9839                // it has been renamed to an older name.  The package we
9840                // are trying to install should be installed as an update to
9841                // the existing one, but that has not been requested, so bail.
9842                Slog.w(TAG, "Attempt to re-install " + pkgName
9843                        + " without first uninstalling package running as "
9844                        + mSettings.mRenamedPackages.get(pkgName));
9845                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9846                return;
9847            }
9848            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9849                // Don't allow installation over an existing package with the same name.
9850                Slog.w(TAG, "Attempt to re-install " + pkgName
9851                        + " without first uninstalling.");
9852                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9853                return;
9854            }
9855        }
9856        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9857        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9858                System.currentTimeMillis(), user, abiOverride);
9859        if (newPackage == null) {
9860            Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
9861            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9862                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9863            }
9864        } else {
9865            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9866            // delete the partially installed application. the data directory will have to be
9867            // restored if it was already existing
9868            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9869                // remove package from internal structures.  Note that we want deletePackageX to
9870                // delete the package data and cache directories that it created in
9871                // scanPackageLocked, unless those directories existed before we even tried to
9872                // install.
9873                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9874                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9875                                res.removedInfo, true);
9876            }
9877        }
9878    }
9879
9880    private void replacePackageLI(PackageParser.Package pkg,
9881            int parseFlags, int scanMode, UserHandle user,
9882            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9883
9884        PackageParser.Package oldPackage;
9885        String pkgName = pkg.packageName;
9886        int[] allUsers;
9887        boolean[] perUserInstalled;
9888
9889        // First find the old package info and check signatures
9890        synchronized(mPackages) {
9891            oldPackage = mPackages.get(pkgName);
9892            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9893            if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9894                    != PackageManager.SIGNATURE_MATCH) {
9895                Slog.w(TAG, "New package has a different signature: " + pkgName);
9896                res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9897                return;
9898            }
9899
9900            // In case of rollback, remember per-user/profile install state
9901            PackageSetting ps = mSettings.mPackages.get(pkgName);
9902            allUsers = sUserManager.getUserIds();
9903            perUserInstalled = new boolean[allUsers.length];
9904            for (int i = 0; i < allUsers.length; i++) {
9905                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9906            }
9907        }
9908        boolean sysPkg = (isSystemApp(oldPackage));
9909        if (sysPkg) {
9910            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9911                    user, allUsers, perUserInstalled, installerPackageName, res,
9912                    abiOverride);
9913        } else {
9914            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanMode,
9915                    user, allUsers, perUserInstalled, installerPackageName, res,
9916                    abiOverride);
9917        }
9918    }
9919
9920    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9921            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
9922            int[] allUsers, boolean[] perUserInstalled,
9923            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9924        PackageParser.Package newPackage = null;
9925        String pkgName = deletedPackage.packageName;
9926        boolean deletedPkg = true;
9927        boolean updatedSettings = false;
9928
9929        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9930                + deletedPackage);
9931        long origUpdateTime;
9932        if (pkg.mExtras != null) {
9933            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9934        } else {
9935            origUpdateTime = 0;
9936        }
9937
9938        // First delete the existing package while retaining the data directory
9939        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9940                res.removedInfo, true)) {
9941            // If the existing package wasn't successfully deleted
9942            res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
9943            deletedPkg = false;
9944        } else {
9945            // Successfully deleted the old package. Now proceed with re-installation
9946            mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9947            newPackage = scanPackageLI(pkg, parseFlags, scanMode | SCAN_UPDATE_TIME,
9948                    System.currentTimeMillis(), user, abiOverride);
9949            if (newPackage == null) {
9950                Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
9951                if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9952                    res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9953                }
9954            } else {
9955                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9956                updatedSettings = true;
9957            }
9958        }
9959
9960        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9961            // remove package from internal structures.  Note that we want deletePackageX to
9962            // delete the package data and cache directories that it created in
9963            // scanPackageLocked, unless those directories existed before we even tried to
9964            // install.
9965            if(updatedSettings) {
9966                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9967                deletePackageLI(
9968                        pkgName, null, true, allUsers, perUserInstalled,
9969                        PackageManager.DELETE_KEEP_DATA,
9970                                res.removedInfo, true);
9971            }
9972            // Since we failed to install the new package we need to restore the old
9973            // package that we deleted.
9974            if (deletedPkg) {
9975                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9976                File restoreFile = new File(deletedPackage.codePath);
9977                // Parse old package
9978                boolean oldOnSd = isExternal(deletedPackage);
9979                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9980                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9981                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9982                int oldScanMode = (oldOnSd ? 0 : SCAN_MONITOR) | SCAN_UPDATE_SIGNATURE
9983                        | SCAN_UPDATE_TIME;
9984                if (scanPackageLI(restoreFile, oldParseFlags, oldScanMode,
9985                        origUpdateTime, null, null) == null) {
9986                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade");
9987                    return;
9988                }
9989                // Restore of old package succeeded. Update permissions.
9990                // writer
9991                synchronized (mPackages) {
9992                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9993                            UPDATE_PERMISSIONS_ALL);
9994                    // can downgrade to reader
9995                    mSettings.writeLPr();
9996                }
9997                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9998            }
9999        }
10000    }
10001
10002    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10003            PackageParser.Package pkg, int parseFlags, int scanMode, UserHandle user,
10004            int[] allUsers, boolean[] perUserInstalled,
10005            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
10006        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10007                + ", old=" + deletedPackage);
10008        PackageParser.Package newPackage = null;
10009        boolean updatedSettings = false;
10010        parseFlags |= PackageManager.INSTALL_REPLACE_EXISTING |
10011                PackageParser.PARSE_IS_SYSTEM;
10012        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10013            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10014        }
10015        String packageName = deletedPackage.packageName;
10016        res.returnCode = PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
10017        if (packageName == null) {
10018            Slog.w(TAG, "Attempt to delete null packageName.");
10019            return;
10020        }
10021        PackageParser.Package oldPkg;
10022        PackageSetting oldPkgSetting;
10023        // reader
10024        synchronized (mPackages) {
10025            oldPkg = mPackages.get(packageName);
10026            oldPkgSetting = mSettings.mPackages.get(packageName);
10027            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10028                    (oldPkgSetting == null)) {
10029                Slog.w(TAG, "Couldn't find package:"+packageName+" information");
10030                return;
10031            }
10032        }
10033
10034        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10035
10036        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10037        res.removedInfo.removedPackage = packageName;
10038        // Remove existing system package
10039        removePackageLI(oldPkgSetting, true);
10040        // writer
10041        synchronized (mPackages) {
10042            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10043                // We didn't need to disable the .apk as a current system package,
10044                // which means we are replacing another update that is already
10045                // installed.  We need to make sure to delete the older one's .apk.
10046                res.removedInfo.args = createInstallArgs(0,
10047                        deletedPackage.applicationInfo.sourceDir,
10048                        deletedPackage.applicationInfo.publicSourceDir,
10049                        deletedPackage.applicationInfo.nativeLibraryDir,
10050                        getAppInstructionSet(deletedPackage.applicationInfo));
10051            } else {
10052                res.removedInfo.args = null;
10053            }
10054        }
10055
10056        // Successfully disabled the old package. Now proceed with re-installation
10057        res.returnCode = mLastScanError = PackageManager.INSTALL_SUCCEEDED;
10058        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10059        newPackage = scanPackageLI(pkg, parseFlags, scanMode, 0, user, abiOverride);
10060        if (newPackage == null) {
10061            Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
10062            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
10063                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
10064            }
10065        } else {
10066            if (newPackage.mExtras != null) {
10067                final PackageSetting newPkgSetting = (PackageSetting)newPackage.mExtras;
10068                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10069                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10070
10071                // is the update attempting to change shared user? that isn't going to work...
10072                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10073                    Slog.w(TAG, "Forbidding shared user change from " + oldPkgSetting.sharedUser
10074                            + " to " + newPkgSetting.sharedUser);
10075                    res.returnCode = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
10076                    updatedSettings = true;
10077                }
10078            }
10079
10080            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10081                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10082                updatedSettings = true;
10083            }
10084        }
10085
10086        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10087            // Re installation failed. Restore old information
10088            // Remove new pkg information
10089            if (newPackage != null) {
10090                removeInstalledPackageLI(newPackage, true);
10091            }
10092            // Add back the old system package
10093            scanPackageLI(oldPkg, parseFlags, SCAN_MONITOR | SCAN_UPDATE_SIGNATURE, 0, user, null);
10094            // Restore the old system information in Settings
10095            synchronized(mPackages) {
10096                if (updatedSettings) {
10097                    mSettings.enableSystemPackageLPw(packageName);
10098                    mSettings.setInstallerPackageName(packageName,
10099                            oldPkgSetting.installerPackageName);
10100                }
10101                mSettings.writeLPr();
10102            }
10103        }
10104    }
10105
10106    // Utility method used to move dex files during install.
10107    private int moveDexFilesLI(String oldCodePath, PackageParser.Package newPackage) {
10108        // TODO: extend to move split APK dex files
10109        if ((newPackage.applicationInfo.flags&ApplicationInfo.FLAG_HAS_CODE) != 0) {
10110            final String instructionSet = getAppInstructionSet(newPackage.applicationInfo);
10111            int retCode = mInstaller.movedex(oldCodePath, newPackage.codePath,
10112                                             instructionSet);
10113            if (retCode != 0) {
10114                /*
10115                 * Programs may be lazily run through dexopt, so the
10116                 * source may not exist. However, something seems to
10117                 * have gone wrong, so note that dexopt needs to be
10118                 * run again and remove the source file. In addition,
10119                 * remove the target to make sure there isn't a stale
10120                 * file from a previous version of the package.
10121                 */
10122                newPackage.mDexOptNeeded = true;
10123                mInstaller.rmdex(oldCodePath, instructionSet);
10124                mInstaller.rmdex(newPackage.codePath, instructionSet);
10125            }
10126        }
10127        return PackageManager.INSTALL_SUCCEEDED;
10128    }
10129
10130    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10131            int[] allUsers, boolean[] perUserInstalled,
10132            PackageInstalledInfo res) {
10133        String pkgName = newPackage.packageName;
10134        synchronized (mPackages) {
10135            //write settings. the installStatus will be incomplete at this stage.
10136            //note that the new package setting would have already been
10137            //added to mPackages. It hasn't been persisted yet.
10138            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10139            mSettings.writeLPr();
10140        }
10141
10142        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10143
10144        synchronized (mPackages) {
10145            updatePermissionsLPw(newPackage.packageName, newPackage,
10146                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10147                            ? UPDATE_PERMISSIONS_ALL : 0));
10148            // For system-bundled packages, we assume that installing an upgraded version
10149            // of the package implies that the user actually wants to run that new code,
10150            // so we enable the package.
10151            if (isSystemApp(newPackage)) {
10152                // NB: implicit assumption that system package upgrades apply to all users
10153                if (DEBUG_INSTALL) {
10154                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10155                }
10156                PackageSetting ps = mSettings.mPackages.get(pkgName);
10157                if (ps != null) {
10158                    if (res.origUsers != null) {
10159                        for (int userHandle : res.origUsers) {
10160                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10161                                    userHandle, installerPackageName);
10162                        }
10163                    }
10164                    // Also convey the prior install/uninstall state
10165                    if (allUsers != null && perUserInstalled != null) {
10166                        for (int i = 0; i < allUsers.length; i++) {
10167                            if (DEBUG_INSTALL) {
10168                                Slog.d(TAG, "    user " + allUsers[i]
10169                                        + " => " + perUserInstalled[i]);
10170                            }
10171                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10172                        }
10173                        // these install state changes will be persisted in the
10174                        // upcoming call to mSettings.writeLPr().
10175                    }
10176                }
10177            }
10178            res.name = pkgName;
10179            res.uid = newPackage.applicationInfo.uid;
10180            res.pkg = newPackage;
10181            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10182            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10183            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10184            //to update install status
10185            mSettings.writeLPr();
10186        }
10187    }
10188
10189    private void installPackageLI(InstallArgs args,
10190            boolean newInstall, PackageInstalledInfo res) {
10191        int pFlags = args.flags;
10192        String installerPackageName = args.installerPackageName;
10193        File tmpPackageFile = new File(args.getCodePath());
10194        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10195        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10196        boolean replace = false;
10197        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10198                | (newInstall ? SCAN_NEW_INSTALL : 0);
10199        // Result object to be returned
10200        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10201
10202        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10203        // Retrieve PackageSettings and parse package
10204        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10205                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10206                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10207        PackageParser pp = new PackageParser();
10208        pp.setSeparateProcesses(mSeparateProcesses);
10209        pp.setDisplayMetrics(mMetrics);
10210
10211        final PackageParser.Package pkg;
10212        try {
10213            pkg = pp.parseMonolithicPackage(tmpPackageFile, parseFlags);
10214        } catch (PackageParserException e) {
10215            res.returnCode = e.error;
10216            return;
10217        }
10218
10219        String pkgName = res.name = pkg.packageName;
10220        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10221            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10222                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
10223                return;
10224            }
10225        }
10226
10227        try {
10228            pp.collectCertificates(pkg, parseFlags);
10229            pp.collectManifestDigest(pkg);
10230        } catch (PackageParserException e) {
10231            res.returnCode = e.error;
10232            return;
10233        }
10234
10235        /* If the installer passed in a manifest digest, compare it now. */
10236        if (args.manifestDigest != null) {
10237            if (DEBUG_INSTALL) {
10238                final String parsedManifest = pkg.manifestDigest == null ? "null"
10239                        : pkg.manifestDigest.toString();
10240                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10241                        + parsedManifest);
10242            }
10243
10244            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10245                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
10246                return;
10247            }
10248        } else if (DEBUG_INSTALL) {
10249            final String parsedManifest = pkg.manifestDigest == null
10250                    ? "null" : pkg.manifestDigest.toString();
10251            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10252        }
10253
10254        // Get rid of all references to package scan path via parser.
10255        pp = null;
10256        String oldCodePath = null;
10257        boolean systemApp = false;
10258        synchronized (mPackages) {
10259            // Check whether the newly-scanned package wants to define an already-defined perm
10260            int N = pkg.permissions.size();
10261            for (int i = N-1; i >= 0; i--) {
10262                PackageParser.Permission perm = pkg.permissions.get(i);
10263                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10264                if (bp != null) {
10265                    // If the defining package is signed with our cert, it's okay.  This
10266                    // also includes the "updating the same package" case, of course.
10267                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10268                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10269                        // If the owning package is the system itself, we log but allow
10270                        // install to proceed; we fail the install on all other permission
10271                        // redefinitions.
10272                        if (!bp.sourcePackage.equals("android")) {
10273                            Slog.w(TAG, "Package " + pkg.packageName
10274                                    + " attempting to redeclare permission " + perm.info.name
10275                                    + " already owned by " + bp.sourcePackage);
10276                            res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
10277                            res.origPermission = perm.info.name;
10278                            res.origPackage = bp.sourcePackage;
10279                            return;
10280                        } else {
10281                            Slog.w(TAG, "Package " + pkg.packageName
10282                                    + " attempting to redeclare system permission "
10283                                    + perm.info.name + "; ignoring new declaration");
10284                            pkg.permissions.remove(i);
10285                        }
10286                    }
10287                }
10288            }
10289
10290            // Check if installing already existing package
10291            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10292                String oldName = mSettings.mRenamedPackages.get(pkgName);
10293                if (pkg.mOriginalPackages != null
10294                        && pkg.mOriginalPackages.contains(oldName)
10295                        && mPackages.containsKey(oldName)) {
10296                    // This package is derived from an original package,
10297                    // and this device has been updating from that original
10298                    // name.  We must continue using the original name, so
10299                    // rename the new package here.
10300                    pkg.setPackageName(oldName);
10301                    pkgName = pkg.packageName;
10302                    replace = true;
10303                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10304                            + oldName + " pkgName=" + pkgName);
10305                } else if (mPackages.containsKey(pkgName)) {
10306                    // This package, under its official name, already exists
10307                    // on the device; we should replace it.
10308                    replace = true;
10309                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10310                }
10311            }
10312            PackageSetting ps = mSettings.mPackages.get(pkgName);
10313            if (ps != null) {
10314                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10315                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10316                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10317                    systemApp = (ps.pkg.applicationInfo.flags &
10318                            ApplicationInfo.FLAG_SYSTEM) != 0;
10319                }
10320                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10321            }
10322        }
10323
10324        if (systemApp && onSd) {
10325            // Disable updates to system apps on sdcard
10326            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
10327            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10328            return;
10329        }
10330
10331        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
10332            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10333            return;
10334        }
10335        // Set application objects path explicitly after the rename
10336        pkg.codePath = args.getCodePath();
10337        pkg.applicationInfo.sourceDir = args.getCodePath();
10338        pkg.applicationInfo.publicSourceDir = args.getResourcePath();
10339        pkg.applicationInfo.splitSourceDirs = args.getSplitCodePaths();
10340        pkg.applicationInfo.splitPublicSourceDirs = deriveSplitResPaths(
10341                pkg.applicationInfo.splitSourceDirs);
10342        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
10343        if (replace) {
10344            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10345                    installerPackageName, res, args.abiOverride);
10346        } else {
10347            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10348                    installerPackageName, res, args.abiOverride);
10349        }
10350        synchronized (mPackages) {
10351            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10352            if (ps != null) {
10353                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10354            }
10355        }
10356    }
10357
10358    private static boolean isForwardLocked(PackageParser.Package pkg) {
10359        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10360    }
10361
10362
10363    private boolean isForwardLocked(PackageSetting ps) {
10364        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10365    }
10366
10367    private static boolean isExternal(PackageParser.Package pkg) {
10368        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10369    }
10370
10371    private static boolean isExternal(PackageSetting ps) {
10372        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10373    }
10374
10375    private static boolean isSystemApp(PackageParser.Package pkg) {
10376        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10377    }
10378
10379    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10380        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10381    }
10382
10383    private static boolean isSystemApp(ApplicationInfo info) {
10384        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10385    }
10386
10387    private static boolean isSystemApp(PackageSetting ps) {
10388        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10389    }
10390
10391    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10392        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10393    }
10394
10395    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10396        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10397    }
10398
10399    private int packageFlagsToInstallFlags(PackageSetting ps) {
10400        int installFlags = 0;
10401        if (isExternal(ps)) {
10402            installFlags |= PackageManager.INSTALL_EXTERNAL;
10403        }
10404        if (isForwardLocked(ps)) {
10405            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10406        }
10407        return installFlags;
10408    }
10409
10410    private void deleteTempPackageFiles() {
10411        final FilenameFilter filter = new FilenameFilter() {
10412            public boolean accept(File dir, String name) {
10413                return name.startsWith("vmdl") && name.endsWith(".tmp");
10414            }
10415        };
10416        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
10417        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
10418    }
10419
10420    private static final void deleteTempPackageFilesInDirectory(File directory,
10421            FilenameFilter filter) {
10422        final String[] tmpFilesList = directory.list(filter);
10423        if (tmpFilesList == null) {
10424            return;
10425        }
10426        for (int i = 0; i < tmpFilesList.length; i++) {
10427            final File tmpFile = new File(directory, tmpFilesList[i]);
10428            tmpFile.delete();
10429        }
10430    }
10431
10432    private File createTempPackageFile(File installDir) {
10433        File tmpPackageFile;
10434        try {
10435            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
10436        } catch (IOException e) {
10437            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
10438            return null;
10439        }
10440        try {
10441            FileUtils.setPermissions(
10442                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
10443                    -1, -1);
10444            if (!SELinux.restorecon(tmpPackageFile)) {
10445                return null;
10446            }
10447        } catch (IOException e) {
10448            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
10449            return null;
10450        }
10451        return tmpPackageFile;
10452    }
10453
10454    @Override
10455    public void deletePackageAsUser(final String packageName,
10456                                    final IPackageDeleteObserver observer,
10457                                    final int userId, final int flags) {
10458        mContext.enforceCallingOrSelfPermission(
10459                android.Manifest.permission.DELETE_PACKAGES, null);
10460        final int uid = Binder.getCallingUid();
10461        if (UserHandle.getUserId(uid) != userId) {
10462            mContext.enforceCallingPermission(
10463                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10464                    "deletePackage for user " + userId);
10465        }
10466        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10467            try {
10468                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10469            } catch (RemoteException re) {
10470            }
10471            return;
10472        }
10473
10474        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10475        // Queue up an async operation since the package deletion may take a little while.
10476        mHandler.post(new Runnable() {
10477            public void run() {
10478                mHandler.removeCallbacks(this);
10479                final int returnCode = deletePackageX(packageName, userId, flags);
10480                if (observer != null) {
10481                    try {
10482                        observer.packageDeleted(packageName, returnCode);
10483                    } catch (RemoteException e) {
10484                        Log.i(TAG, "Observer no longer exists.");
10485                    } //end catch
10486                } //end if
10487            } //end run
10488        });
10489    }
10490
10491    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10492        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10493                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10494        try {
10495            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10496                    || dpm.isDeviceOwner(packageName))) {
10497                return true;
10498            }
10499        } catch (RemoteException e) {
10500        }
10501        return false;
10502    }
10503
10504    /**
10505     *  This method is an internal method that could be get invoked either
10506     *  to delete an installed package or to clean up a failed installation.
10507     *  After deleting an installed package, a broadcast is sent to notify any
10508     *  listeners that the package has been installed. For cleaning up a failed
10509     *  installation, the broadcast is not necessary since the package's
10510     *  installation wouldn't have sent the initial broadcast either
10511     *  The key steps in deleting a package are
10512     *  deleting the package information in internal structures like mPackages,
10513     *  deleting the packages base directories through installd
10514     *  updating mSettings to reflect current status
10515     *  persisting settings for later use
10516     *  sending a broadcast if necessary
10517     */
10518    private int deletePackageX(String packageName, int userId, int flags) {
10519        final PackageRemovedInfo info = new PackageRemovedInfo();
10520        final boolean res;
10521
10522        if (isPackageDeviceAdmin(packageName, userId)) {
10523            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10524            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10525        }
10526
10527        boolean removedForAllUsers = false;
10528        boolean systemUpdate = false;
10529
10530        // for the uninstall-updates case and restricted profiles, remember the per-
10531        // userhandle installed state
10532        int[] allUsers;
10533        boolean[] perUserInstalled;
10534        synchronized (mPackages) {
10535            PackageSetting ps = mSettings.mPackages.get(packageName);
10536            allUsers = sUserManager.getUserIds();
10537            perUserInstalled = new boolean[allUsers.length];
10538            for (int i = 0; i < allUsers.length; i++) {
10539                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10540            }
10541        }
10542
10543        synchronized (mInstallLock) {
10544            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10545            res = deletePackageLI(packageName,
10546                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10547                            ? UserHandle.ALL : new UserHandle(userId),
10548                    true, allUsers, perUserInstalled,
10549                    flags | REMOVE_CHATTY, info, true);
10550            systemUpdate = info.isRemovedPackageSystemUpdate;
10551            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10552                removedForAllUsers = true;
10553            }
10554            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10555                    + " removedForAllUsers=" + removedForAllUsers);
10556        }
10557
10558        if (res) {
10559            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10560
10561            // If the removed package was a system update, the old system package
10562            // was re-enabled; we need to broadcast this information
10563            if (systemUpdate) {
10564                Bundle extras = new Bundle(1);
10565                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10566                        ? info.removedAppId : info.uid);
10567                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10568
10569                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10570                        extras, null, null, null);
10571                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10572                        extras, null, null, null);
10573                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10574                        null, packageName, null, null);
10575            }
10576        }
10577        // Force a gc here.
10578        Runtime.getRuntime().gc();
10579        // Delete the resources here after sending the broadcast to let
10580        // other processes clean up before deleting resources.
10581        if (info.args != null) {
10582            synchronized (mInstallLock) {
10583                info.args.doPostDeleteLI(true);
10584            }
10585        }
10586
10587        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10588    }
10589
10590    static class PackageRemovedInfo {
10591        String removedPackage;
10592        int uid = -1;
10593        int removedAppId = -1;
10594        int[] removedUsers = null;
10595        boolean isRemovedPackageSystemUpdate = false;
10596        // Clean up resources deleted packages.
10597        InstallArgs args = null;
10598
10599        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10600            Bundle extras = new Bundle(1);
10601            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10602            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10603            if (replacing) {
10604                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10605            }
10606            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10607            if (removedPackage != null) {
10608                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10609                        extras, null, null, removedUsers);
10610                if (fullRemove && !replacing) {
10611                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10612                            extras, null, null, removedUsers);
10613                }
10614            }
10615            if (removedAppId >= 0) {
10616                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10617                        removedUsers);
10618            }
10619        }
10620    }
10621
10622    /*
10623     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10624     * flag is not set, the data directory is removed as well.
10625     * make sure this flag is set for partially installed apps. If not its meaningless to
10626     * delete a partially installed application.
10627     */
10628    private void removePackageDataLI(PackageSetting ps,
10629            int[] allUserHandles, boolean[] perUserInstalled,
10630            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10631        String packageName = ps.name;
10632        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10633        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10634        // Retrieve object to delete permissions for shared user later on
10635        final PackageSetting deletedPs;
10636        // reader
10637        synchronized (mPackages) {
10638            deletedPs = mSettings.mPackages.get(packageName);
10639            if (outInfo != null) {
10640                outInfo.removedPackage = packageName;
10641                outInfo.removedUsers = deletedPs != null
10642                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10643                        : null;
10644            }
10645        }
10646        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10647            removeDataDirsLI(packageName);
10648            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10649        }
10650        // writer
10651        synchronized (mPackages) {
10652            if (deletedPs != null) {
10653                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10654                    if (outInfo != null) {
10655                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10656                    }
10657                    if (deletedPs != null) {
10658                        updatePermissionsLPw(deletedPs.name, null, 0);
10659                        if (deletedPs.sharedUser != null) {
10660                            // remove permissions associated with package
10661                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10662                        }
10663                    }
10664                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10665                }
10666                // make sure to preserve per-user disabled state if this removal was just
10667                // a downgrade of a system app to the factory package
10668                if (allUserHandles != null && perUserInstalled != null) {
10669                    if (DEBUG_REMOVE) {
10670                        Slog.d(TAG, "Propagating install state across downgrade");
10671                    }
10672                    for (int i = 0; i < allUserHandles.length; i++) {
10673                        if (DEBUG_REMOVE) {
10674                            Slog.d(TAG, "    user " + allUserHandles[i]
10675                                    + " => " + perUserInstalled[i]);
10676                        }
10677                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10678                    }
10679                }
10680            }
10681            // can downgrade to reader
10682            if (writeSettings) {
10683                // Save settings now
10684                mSettings.writeLPr();
10685            }
10686        }
10687        if (outInfo != null) {
10688            // A user ID was deleted here. Go through all users and remove it
10689            // from KeyStore.
10690            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10691        }
10692    }
10693
10694    static boolean locationIsPrivileged(File path) {
10695        try {
10696            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10697                    .getCanonicalPath();
10698            return path.getCanonicalPath().startsWith(privilegedAppDir);
10699        } catch (IOException e) {
10700            Slog.e(TAG, "Unable to access code path " + path);
10701        }
10702        return false;
10703    }
10704
10705    /*
10706     * Tries to delete system package.
10707     */
10708    private boolean deleteSystemPackageLI(PackageSetting newPs,
10709            int[] allUserHandles, boolean[] perUserInstalled,
10710            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10711        final boolean applyUserRestrictions
10712                = (allUserHandles != null) && (perUserInstalled != null);
10713        PackageSetting disabledPs = null;
10714        // Confirm if the system package has been updated
10715        // An updated system app can be deleted. This will also have to restore
10716        // the system pkg from system partition
10717        // reader
10718        synchronized (mPackages) {
10719            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10720        }
10721        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10722                + " disabledPs=" + disabledPs);
10723        if (disabledPs == null) {
10724            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10725            return false;
10726        } else if (DEBUG_REMOVE) {
10727            Slog.d(TAG, "Deleting system pkg from data partition");
10728        }
10729        if (DEBUG_REMOVE) {
10730            if (applyUserRestrictions) {
10731                Slog.d(TAG, "Remembering install states:");
10732                for (int i = 0; i < allUserHandles.length; i++) {
10733                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10734                }
10735            }
10736        }
10737        // Delete the updated package
10738        outInfo.isRemovedPackageSystemUpdate = true;
10739        if (disabledPs.versionCode < newPs.versionCode) {
10740            // Delete data for downgrades
10741            flags &= ~PackageManager.DELETE_KEEP_DATA;
10742        } else {
10743            // Preserve data by setting flag
10744            flags |= PackageManager.DELETE_KEEP_DATA;
10745        }
10746        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10747                allUserHandles, perUserInstalled, outInfo, writeSettings);
10748        if (!ret) {
10749            return false;
10750        }
10751        // writer
10752        synchronized (mPackages) {
10753            // Reinstate the old system package
10754            mSettings.enableSystemPackageLPw(newPs.name);
10755            // Remove any native libraries from the upgraded package.
10756            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10757        }
10758        // Install the system package
10759        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10760        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10761        if (locationIsPrivileged(disabledPs.codePath)) {
10762            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10763        }
10764        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10765                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null);
10766
10767        if (newPkg == null) {
10768            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10769                    + " with error:" + mLastScanError);
10770            return false;
10771        }
10772        // writer
10773        synchronized (mPackages) {
10774            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10775            setInternalAppNativeLibraryPath(newPkg, ps);
10776            updatePermissionsLPw(newPkg.packageName, newPkg,
10777                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10778            if (applyUserRestrictions) {
10779                if (DEBUG_REMOVE) {
10780                    Slog.d(TAG, "Propagating install state across reinstall");
10781                }
10782                for (int i = 0; i < allUserHandles.length; i++) {
10783                    if (DEBUG_REMOVE) {
10784                        Slog.d(TAG, "    user " + allUserHandles[i]
10785                                + " => " + perUserInstalled[i]);
10786                    }
10787                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10788                }
10789                // Regardless of writeSettings we need to ensure that this restriction
10790                // state propagation is persisted
10791                mSettings.writeAllUsersPackageRestrictionsLPr();
10792            }
10793            // can downgrade to reader here
10794            if (writeSettings) {
10795                mSettings.writeLPr();
10796            }
10797        }
10798        return true;
10799    }
10800
10801    private boolean deleteInstalledPackageLI(PackageSetting ps,
10802            boolean deleteCodeAndResources, int flags,
10803            int[] allUserHandles, boolean[] perUserInstalled,
10804            PackageRemovedInfo outInfo, boolean writeSettings) {
10805        if (outInfo != null) {
10806            outInfo.uid = ps.appId;
10807        }
10808
10809        // Delete package data from internal structures and also remove data if flag is set
10810        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10811
10812        // Delete application code and resources
10813        if (deleteCodeAndResources && (outInfo != null)) {
10814            outInfo.args = createInstallArgs(packageFlagsToInstallFlags(ps), ps.codePathString,
10815                    ps.resourcePathString, ps.nativeLibraryPathString,
10816                    getAppInstructionSetFromSettings(ps));
10817        }
10818        return true;
10819    }
10820
10821    /*
10822     * This method handles package deletion in general
10823     */
10824    private boolean deletePackageLI(String packageName, UserHandle user,
10825            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10826            int flags, PackageRemovedInfo outInfo,
10827            boolean writeSettings) {
10828        if (packageName == null) {
10829            Slog.w(TAG, "Attempt to delete null packageName.");
10830            return false;
10831        }
10832        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10833        PackageSetting ps;
10834        boolean dataOnly = false;
10835        int removeUser = -1;
10836        int appId = -1;
10837        synchronized (mPackages) {
10838            ps = mSettings.mPackages.get(packageName);
10839            if (ps == null) {
10840                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10841                return false;
10842            }
10843            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10844                    && user.getIdentifier() != UserHandle.USER_ALL) {
10845                // The caller is asking that the package only be deleted for a single
10846                // user.  To do this, we just mark its uninstalled state and delete
10847                // its data.  If this is a system app, we only allow this to happen if
10848                // they have set the special DELETE_SYSTEM_APP which requests different
10849                // semantics than normal for uninstalling system apps.
10850                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10851                ps.setUserState(user.getIdentifier(),
10852                        COMPONENT_ENABLED_STATE_DEFAULT,
10853                        false, //installed
10854                        true,  //stopped
10855                        true,  //notLaunched
10856                        false, //blocked
10857                        null, null, null);
10858                if (!isSystemApp(ps)) {
10859                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10860                        // Other user still have this package installed, so all
10861                        // we need to do is clear this user's data and save that
10862                        // it is uninstalled.
10863                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10864                        removeUser = user.getIdentifier();
10865                        appId = ps.appId;
10866                        mSettings.writePackageRestrictionsLPr(removeUser);
10867                    } else {
10868                        // We need to set it back to 'installed' so the uninstall
10869                        // broadcasts will be sent correctly.
10870                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10871                        ps.setInstalled(true, user.getIdentifier());
10872                    }
10873                } else {
10874                    // This is a system app, so we assume that the
10875                    // other users still have this package installed, so all
10876                    // we need to do is clear this user's data and save that
10877                    // it is uninstalled.
10878                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10879                    removeUser = user.getIdentifier();
10880                    appId = ps.appId;
10881                    mSettings.writePackageRestrictionsLPr(removeUser);
10882                }
10883            }
10884        }
10885
10886        if (removeUser >= 0) {
10887            // From above, we determined that we are deleting this only
10888            // for a single user.  Continue the work here.
10889            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10890            if (outInfo != null) {
10891                outInfo.removedPackage = packageName;
10892                outInfo.removedAppId = appId;
10893                outInfo.removedUsers = new int[] {removeUser};
10894            }
10895            mInstaller.clearUserData(packageName, removeUser);
10896            removeKeystoreDataIfNeeded(removeUser, appId);
10897            schedulePackageCleaning(packageName, removeUser, false);
10898            return true;
10899        }
10900
10901        if (dataOnly) {
10902            // Delete application data first
10903            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10904            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10905            return true;
10906        }
10907
10908        boolean ret = false;
10909        mSettings.mKeySetManager.removeAppKeySetData(packageName);
10910        if (isSystemApp(ps)) {
10911            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10912            // When an updated system application is deleted we delete the existing resources as well and
10913            // fall back to existing code in system partition
10914            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10915                    flags, outInfo, writeSettings);
10916        } else {
10917            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10918            // Kill application pre-emptively especially for apps on sd.
10919            killApplication(packageName, ps.appId, "uninstall pkg");
10920            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10921                    allUserHandles, perUserInstalled,
10922                    outInfo, writeSettings);
10923        }
10924
10925        return ret;
10926    }
10927
10928    private final class ClearStorageConnection implements ServiceConnection {
10929        IMediaContainerService mContainerService;
10930
10931        @Override
10932        public void onServiceConnected(ComponentName name, IBinder service) {
10933            synchronized (this) {
10934                mContainerService = IMediaContainerService.Stub.asInterface(service);
10935                notifyAll();
10936            }
10937        }
10938
10939        @Override
10940        public void onServiceDisconnected(ComponentName name) {
10941        }
10942    }
10943
10944    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10945        final boolean mounted;
10946        if (Environment.isExternalStorageEmulated()) {
10947            mounted = true;
10948        } else {
10949            final String status = Environment.getExternalStorageState();
10950
10951            mounted = status.equals(Environment.MEDIA_MOUNTED)
10952                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10953        }
10954
10955        if (!mounted) {
10956            return;
10957        }
10958
10959        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10960        int[] users;
10961        if (userId == UserHandle.USER_ALL) {
10962            users = sUserManager.getUserIds();
10963        } else {
10964            users = new int[] { userId };
10965        }
10966        final ClearStorageConnection conn = new ClearStorageConnection();
10967        if (mContext.bindServiceAsUser(
10968                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10969            try {
10970                for (int curUser : users) {
10971                    long timeout = SystemClock.uptimeMillis() + 5000;
10972                    synchronized (conn) {
10973                        long now = SystemClock.uptimeMillis();
10974                        while (conn.mContainerService == null && now < timeout) {
10975                            try {
10976                                conn.wait(timeout - now);
10977                            } catch (InterruptedException e) {
10978                            }
10979                        }
10980                    }
10981                    if (conn.mContainerService == null) {
10982                        return;
10983                    }
10984
10985                    final UserEnvironment userEnv = new UserEnvironment(curUser);
10986                    clearDirectory(conn.mContainerService,
10987                            userEnv.buildExternalStorageAppCacheDirs(packageName));
10988                    if (allData) {
10989                        clearDirectory(conn.mContainerService,
10990                                userEnv.buildExternalStorageAppDataDirs(packageName));
10991                        clearDirectory(conn.mContainerService,
10992                                userEnv.buildExternalStorageAppMediaDirs(packageName));
10993                    }
10994                }
10995            } finally {
10996                mContext.unbindService(conn);
10997            }
10998        }
10999    }
11000
11001    @Override
11002    public void clearApplicationUserData(final String packageName,
11003            final IPackageDataObserver observer, final int userId) {
11004        mContext.enforceCallingOrSelfPermission(
11005                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11006        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11007        // Queue up an async operation since the package deletion may take a little while.
11008        mHandler.post(new Runnable() {
11009            public void run() {
11010                mHandler.removeCallbacks(this);
11011                final boolean succeeded;
11012                synchronized (mInstallLock) {
11013                    succeeded = clearApplicationUserDataLI(packageName, userId);
11014                }
11015                clearExternalStorageDataSync(packageName, userId, true);
11016                if (succeeded) {
11017                    // invoke DeviceStorageMonitor's update method to clear any notifications
11018                    DeviceStorageMonitorInternal
11019                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11020                    if (dsm != null) {
11021                        dsm.checkMemory();
11022                    }
11023                }
11024                if(observer != null) {
11025                    try {
11026                        observer.onRemoveCompleted(packageName, succeeded);
11027                    } catch (RemoteException e) {
11028                        Log.i(TAG, "Observer no longer exists.");
11029                    }
11030                } //end if observer
11031            } //end run
11032        });
11033    }
11034
11035    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11036        if (packageName == null) {
11037            Slog.w(TAG, "Attempt to delete null packageName.");
11038            return false;
11039        }
11040        PackageParser.Package p;
11041        boolean dataOnly = false;
11042        final int appId;
11043        synchronized (mPackages) {
11044            p = mPackages.get(packageName);
11045            if (p == null) {
11046                dataOnly = true;
11047                PackageSetting ps = mSettings.mPackages.get(packageName);
11048                if ((ps == null) || (ps.pkg == null)) {
11049                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11050                    return false;
11051                }
11052                p = ps.pkg;
11053            }
11054            if (!dataOnly) {
11055                // need to check this only for fully installed applications
11056                if (p == null) {
11057                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11058                    return false;
11059                }
11060                final ApplicationInfo applicationInfo = p.applicationInfo;
11061                if (applicationInfo == null) {
11062                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11063                    return false;
11064                }
11065            }
11066            if (p != null && p.applicationInfo != null) {
11067                appId = p.applicationInfo.uid;
11068            } else {
11069                appId = -1;
11070            }
11071        }
11072        int retCode = mInstaller.clearUserData(packageName, userId);
11073        if (retCode < 0) {
11074            Slog.w(TAG, "Couldn't remove cache files for package: "
11075                    + packageName);
11076            return false;
11077        }
11078        removeKeystoreDataIfNeeded(userId, appId);
11079        return true;
11080    }
11081
11082    /**
11083     * Remove entries from the keystore daemon. Will only remove it if the
11084     * {@code appId} is valid.
11085     */
11086    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11087        if (appId < 0) {
11088            return;
11089        }
11090
11091        final KeyStore keyStore = KeyStore.getInstance();
11092        if (keyStore != null) {
11093            if (userId == UserHandle.USER_ALL) {
11094                for (final int individual : sUserManager.getUserIds()) {
11095                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11096                }
11097            } else {
11098                keyStore.clearUid(UserHandle.getUid(userId, appId));
11099            }
11100        } else {
11101            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11102        }
11103    }
11104
11105    @Override
11106    public void deleteApplicationCacheFiles(final String packageName,
11107            final IPackageDataObserver observer) {
11108        mContext.enforceCallingOrSelfPermission(
11109                android.Manifest.permission.DELETE_CACHE_FILES, null);
11110        // Queue up an async operation since the package deletion may take a little while.
11111        final int userId = UserHandle.getCallingUserId();
11112        mHandler.post(new Runnable() {
11113            public void run() {
11114                mHandler.removeCallbacks(this);
11115                final boolean succeded;
11116                synchronized (mInstallLock) {
11117                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11118                }
11119                clearExternalStorageDataSync(packageName, userId, false);
11120                if(observer != null) {
11121                    try {
11122                        observer.onRemoveCompleted(packageName, succeded);
11123                    } catch (RemoteException e) {
11124                        Log.i(TAG, "Observer no longer exists.");
11125                    }
11126                } //end if observer
11127            } //end run
11128        });
11129    }
11130
11131    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11132        if (packageName == null) {
11133            Slog.w(TAG, "Attempt to delete null packageName.");
11134            return false;
11135        }
11136        PackageParser.Package p;
11137        synchronized (mPackages) {
11138            p = mPackages.get(packageName);
11139        }
11140        if (p == null) {
11141            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11142            return false;
11143        }
11144        final ApplicationInfo applicationInfo = p.applicationInfo;
11145        if (applicationInfo == null) {
11146            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11147            return false;
11148        }
11149        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11150        if (retCode < 0) {
11151            Slog.w(TAG, "Couldn't remove cache files for package: "
11152                       + packageName + " u" + userId);
11153            return false;
11154        }
11155        return true;
11156    }
11157
11158    @Override
11159    public void getPackageSizeInfo(final String packageName, int userHandle,
11160            final IPackageStatsObserver observer) {
11161        mContext.enforceCallingOrSelfPermission(
11162                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11163        if (packageName == null) {
11164            throw new IllegalArgumentException("Attempt to get size of null packageName");
11165        }
11166
11167        PackageStats stats = new PackageStats(packageName, userHandle);
11168
11169        /*
11170         * Queue up an async operation since the package measurement may take a
11171         * little while.
11172         */
11173        Message msg = mHandler.obtainMessage(INIT_COPY);
11174        msg.obj = new MeasureParams(stats, observer);
11175        mHandler.sendMessage(msg);
11176    }
11177
11178    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11179            PackageStats pStats) {
11180        if (packageName == null) {
11181            Slog.w(TAG, "Attempt to get size of null packageName.");
11182            return false;
11183        }
11184        PackageParser.Package p;
11185        boolean dataOnly = false;
11186        String libDirPath = null;
11187        String asecPath = null;
11188        PackageSetting ps = null;
11189        synchronized (mPackages) {
11190            p = mPackages.get(packageName);
11191            ps = mSettings.mPackages.get(packageName);
11192            if(p == null) {
11193                dataOnly = true;
11194                if((ps == null) || (ps.pkg == null)) {
11195                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11196                    return false;
11197                }
11198                p = ps.pkg;
11199            }
11200            if (ps != null) {
11201                libDirPath = ps.nativeLibraryPathString;
11202            }
11203            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11204                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
11205                if (secureContainerId != null) {
11206                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11207                }
11208            }
11209        }
11210        String publicSrcDir = null;
11211        if(!dataOnly) {
11212            final ApplicationInfo applicationInfo = p.applicationInfo;
11213            if (applicationInfo == null) {
11214                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11215                return false;
11216            }
11217            if (isForwardLocked(p)) {
11218                publicSrcDir = applicationInfo.publicSourceDir;
11219            }
11220        }
11221        int res = mInstaller.getSizeInfo(packageName, userHandle, p.codePath, libDirPath,
11222                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
11223                pStats);
11224        if (res < 0) {
11225            return false;
11226        }
11227
11228        // Fix-up for forward-locked applications in ASEC containers.
11229        if (!isExternal(p)) {
11230            pStats.codeSize += pStats.externalCodeSize;
11231            pStats.externalCodeSize = 0L;
11232        }
11233
11234        return true;
11235    }
11236
11237
11238    @Override
11239    public void addPackageToPreferred(String packageName) {
11240        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11241    }
11242
11243    @Override
11244    public void removePackageFromPreferred(String packageName) {
11245        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11246    }
11247
11248    @Override
11249    public List<PackageInfo> getPreferredPackages(int flags) {
11250        return new ArrayList<PackageInfo>();
11251    }
11252
11253    private int getUidTargetSdkVersionLockedLPr(int uid) {
11254        Object obj = mSettings.getUserIdLPr(uid);
11255        if (obj instanceof SharedUserSetting) {
11256            final SharedUserSetting sus = (SharedUserSetting) obj;
11257            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11258            final Iterator<PackageSetting> it = sus.packages.iterator();
11259            while (it.hasNext()) {
11260                final PackageSetting ps = it.next();
11261                if (ps.pkg != null) {
11262                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11263                    if (v < vers) vers = v;
11264                }
11265            }
11266            return vers;
11267        } else if (obj instanceof PackageSetting) {
11268            final PackageSetting ps = (PackageSetting) obj;
11269            if (ps.pkg != null) {
11270                return ps.pkg.applicationInfo.targetSdkVersion;
11271            }
11272        }
11273        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11274    }
11275
11276    @Override
11277    public void addPreferredActivity(IntentFilter filter, int match,
11278            ComponentName[] set, ComponentName activity, int userId) {
11279        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11280    }
11281
11282    private void addPreferredActivityInternal(IntentFilter filter, int match,
11283            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11284        // writer
11285        int callingUid = Binder.getCallingUid();
11286        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11287        if (filter.countActions() == 0) {
11288            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11289            return;
11290        }
11291        synchronized (mPackages) {
11292            if (mContext.checkCallingOrSelfPermission(
11293                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11294                    != PackageManager.PERMISSION_GRANTED) {
11295                if (getUidTargetSdkVersionLockedLPr(callingUid)
11296                        < Build.VERSION_CODES.FROYO) {
11297                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11298                            + callingUid);
11299                    return;
11300                }
11301                mContext.enforceCallingOrSelfPermission(
11302                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11303            }
11304
11305            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11306            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11307            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11308                    new PreferredActivity(filter, match, set, activity, always));
11309            mSettings.writePackageRestrictionsLPr(userId);
11310        }
11311    }
11312
11313    @Override
11314    public void replacePreferredActivity(IntentFilter filter, int match,
11315            ComponentName[] set, ComponentName activity) {
11316        if (filter.countActions() != 1) {
11317            throw new IllegalArgumentException(
11318                    "replacePreferredActivity expects filter to have only 1 action.");
11319        }
11320        if (filter.countDataAuthorities() != 0
11321                || filter.countDataPaths() != 0
11322                || filter.countDataSchemes() > 1
11323                || filter.countDataTypes() != 0) {
11324            throw new IllegalArgumentException(
11325                    "replacePreferredActivity expects filter to have no data authorities, " +
11326                    "paths, or types; and at most one scheme.");
11327        }
11328        synchronized (mPackages) {
11329            if (mContext.checkCallingOrSelfPermission(
11330                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11331                    != PackageManager.PERMISSION_GRANTED) {
11332                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11333                        < Build.VERSION_CODES.FROYO) {
11334                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11335                            + Binder.getCallingUid());
11336                    return;
11337                }
11338                mContext.enforceCallingOrSelfPermission(
11339                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11340            }
11341
11342            final int callingUserId = UserHandle.getCallingUserId();
11343            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11344            if (pir != null) {
11345                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11346                if (filter.countDataSchemes() == 1) {
11347                    Uri.Builder builder = new Uri.Builder();
11348                    builder.scheme(filter.getDataScheme(0));
11349                    intent.setData(builder.build());
11350                }
11351                List<PreferredActivity> matches = pir.queryIntent(
11352                        intent, null, true, callingUserId);
11353                if (DEBUG_PREFERRED) {
11354                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11355                }
11356                for (int i = 0; i < matches.size(); i++) {
11357                    PreferredActivity pa = matches.get(i);
11358                    if (DEBUG_PREFERRED) {
11359                        Slog.i(TAG, "Removing preferred activity "
11360                                + pa.mPref.mComponent + ":");
11361                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11362                    }
11363                    pir.removeFilter(pa);
11364                }
11365            }
11366            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11367        }
11368    }
11369
11370    @Override
11371    public void clearPackagePreferredActivities(String packageName) {
11372        final int uid = Binder.getCallingUid();
11373        // writer
11374        synchronized (mPackages) {
11375            PackageParser.Package pkg = mPackages.get(packageName);
11376            if (pkg == null || pkg.applicationInfo.uid != uid) {
11377                if (mContext.checkCallingOrSelfPermission(
11378                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11379                        != PackageManager.PERMISSION_GRANTED) {
11380                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11381                            < Build.VERSION_CODES.FROYO) {
11382                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11383                                + Binder.getCallingUid());
11384                        return;
11385                    }
11386                    mContext.enforceCallingOrSelfPermission(
11387                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11388                }
11389            }
11390
11391            int user = UserHandle.getCallingUserId();
11392            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11393                mSettings.writePackageRestrictionsLPr(user);
11394                scheduleWriteSettingsLocked();
11395            }
11396        }
11397    }
11398
11399    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11400    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11401        ArrayList<PreferredActivity> removed = null;
11402        boolean changed = false;
11403        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11404            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11405            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11406            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11407                continue;
11408            }
11409            Iterator<PreferredActivity> it = pir.filterIterator();
11410            while (it.hasNext()) {
11411                PreferredActivity pa = it.next();
11412                // Mark entry for removal only if it matches the package name
11413                // and the entry is of type "always".
11414                if (packageName == null ||
11415                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11416                                && pa.mPref.mAlways)) {
11417                    if (removed == null) {
11418                        removed = new ArrayList<PreferredActivity>();
11419                    }
11420                    removed.add(pa);
11421                }
11422            }
11423            if (removed != null) {
11424                for (int j=0; j<removed.size(); j++) {
11425                    PreferredActivity pa = removed.get(j);
11426                    pir.removeFilter(pa);
11427                }
11428                changed = true;
11429            }
11430        }
11431        return changed;
11432    }
11433
11434    @Override
11435    public void resetPreferredActivities(int userId) {
11436        mContext.enforceCallingOrSelfPermission(
11437                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11438        // writer
11439        synchronized (mPackages) {
11440            int user = UserHandle.getCallingUserId();
11441            clearPackagePreferredActivitiesLPw(null, user);
11442            mSettings.readDefaultPreferredAppsLPw(this, user);
11443            mSettings.writePackageRestrictionsLPr(user);
11444            scheduleWriteSettingsLocked();
11445        }
11446    }
11447
11448    @Override
11449    public int getPreferredActivities(List<IntentFilter> outFilters,
11450            List<ComponentName> outActivities, String packageName) {
11451
11452        int num = 0;
11453        final int userId = UserHandle.getCallingUserId();
11454        // reader
11455        synchronized (mPackages) {
11456            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11457            if (pir != null) {
11458                final Iterator<PreferredActivity> it = pir.filterIterator();
11459                while (it.hasNext()) {
11460                    final PreferredActivity pa = it.next();
11461                    if (packageName == null
11462                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11463                                    && pa.mPref.mAlways)) {
11464                        if (outFilters != null) {
11465                            outFilters.add(new IntentFilter(pa));
11466                        }
11467                        if (outActivities != null) {
11468                            outActivities.add(pa.mPref.mComponent);
11469                        }
11470                    }
11471                }
11472            }
11473        }
11474
11475        return num;
11476    }
11477
11478    @Override
11479    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11480            int userId) {
11481        int callingUid = Binder.getCallingUid();
11482        if (callingUid != Process.SYSTEM_UID) {
11483            throw new SecurityException(
11484                    "addPersistentPreferredActivity can only be run by the system");
11485        }
11486        if (filter.countActions() == 0) {
11487            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11488            return;
11489        }
11490        synchronized (mPackages) {
11491            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11492                    " :");
11493            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11494            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11495                    new PersistentPreferredActivity(filter, activity));
11496            mSettings.writePackageRestrictionsLPr(userId);
11497        }
11498    }
11499
11500    @Override
11501    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11502        int callingUid = Binder.getCallingUid();
11503        if (callingUid != Process.SYSTEM_UID) {
11504            throw new SecurityException(
11505                    "clearPackagePersistentPreferredActivities can only be run by the system");
11506        }
11507        ArrayList<PersistentPreferredActivity> removed = null;
11508        boolean changed = false;
11509        synchronized (mPackages) {
11510            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11511                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11512                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11513                        .valueAt(i);
11514                if (userId != thisUserId) {
11515                    continue;
11516                }
11517                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11518                while (it.hasNext()) {
11519                    PersistentPreferredActivity ppa = it.next();
11520                    // Mark entry for removal only if it matches the package name.
11521                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11522                        if (removed == null) {
11523                            removed = new ArrayList<PersistentPreferredActivity>();
11524                        }
11525                        removed.add(ppa);
11526                    }
11527                }
11528                if (removed != null) {
11529                    for (int j=0; j<removed.size(); j++) {
11530                        PersistentPreferredActivity ppa = removed.get(j);
11531                        ppir.removeFilter(ppa);
11532                    }
11533                    changed = true;
11534                }
11535            }
11536
11537            if (changed) {
11538                mSettings.writePackageRestrictionsLPr(userId);
11539            }
11540        }
11541    }
11542
11543    @Override
11544    public void addCrossProfileIntentFilter(IntentFilter filter, boolean removable,
11545            int sourceUserId, int targetUserId) {
11546        mContext.enforceCallingOrSelfPermission(
11547                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11548        if (filter.countActions() == 0) {
11549            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11550            return;
11551        }
11552        synchronized (mPackages) {
11553            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(
11554                    new CrossProfileIntentFilter(filter, removable, targetUserId));
11555            mSettings.writePackageRestrictionsLPr(sourceUserId);
11556        }
11557    }
11558
11559    @Override
11560    public void clearCrossProfileIntentFilters(int sourceUserId) {
11561        mContext.enforceCallingOrSelfPermission(
11562                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11563        synchronized (mPackages) {
11564            CrossProfileIntentResolver cpir =
11565                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11566            HashSet<CrossProfileIntentFilter> set =
11567                    new HashSet<CrossProfileIntentFilter>(cpir.filterSet());
11568            for (CrossProfileIntentFilter cpif : set) {
11569                if (cpif.isRemovable()) cpir.removeFilter(cpif);
11570            }
11571            mSettings.writePackageRestrictionsLPr(sourceUserId);
11572        }
11573    }
11574
11575    @Override
11576    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11577        Intent intent = new Intent(Intent.ACTION_MAIN);
11578        intent.addCategory(Intent.CATEGORY_HOME);
11579
11580        final int callingUserId = UserHandle.getCallingUserId();
11581        List<ResolveInfo> list = queryIntentActivities(intent, null,
11582                PackageManager.GET_META_DATA, callingUserId);
11583        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11584                true, false, false, callingUserId);
11585
11586        allHomeCandidates.clear();
11587        if (list != null) {
11588            for (ResolveInfo ri : list) {
11589                allHomeCandidates.add(ri);
11590            }
11591        }
11592        return (preferred == null || preferred.activityInfo == null)
11593                ? null
11594                : new ComponentName(preferred.activityInfo.packageName,
11595                        preferred.activityInfo.name);
11596    }
11597
11598    @Override
11599    public void setApplicationEnabledSetting(String appPackageName,
11600            int newState, int flags, int userId, String callingPackage) {
11601        if (!sUserManager.exists(userId)) return;
11602        if (callingPackage == null) {
11603            callingPackage = Integer.toString(Binder.getCallingUid());
11604        }
11605        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11606    }
11607
11608    @Override
11609    public void setComponentEnabledSetting(ComponentName componentName,
11610            int newState, int flags, int userId) {
11611        if (!sUserManager.exists(userId)) return;
11612        setEnabledSetting(componentName.getPackageName(),
11613                componentName.getClassName(), newState, flags, userId, null);
11614    }
11615
11616    private void setEnabledSetting(final String packageName, String className, int newState,
11617            final int flags, int userId, String callingPackage) {
11618        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11619              || newState == COMPONENT_ENABLED_STATE_ENABLED
11620              || newState == COMPONENT_ENABLED_STATE_DISABLED
11621              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11622              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11623            throw new IllegalArgumentException("Invalid new component state: "
11624                    + newState);
11625        }
11626        PackageSetting pkgSetting;
11627        final int uid = Binder.getCallingUid();
11628        final int permission = mContext.checkCallingOrSelfPermission(
11629                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11630        enforceCrossUserPermission(uid, userId, false, "set enabled");
11631        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11632        boolean sendNow = false;
11633        boolean isApp = (className == null);
11634        String componentName = isApp ? packageName : className;
11635        int packageUid = -1;
11636        ArrayList<String> components;
11637
11638        // writer
11639        synchronized (mPackages) {
11640            pkgSetting = mSettings.mPackages.get(packageName);
11641            if (pkgSetting == null) {
11642                if (className == null) {
11643                    throw new IllegalArgumentException(
11644                            "Unknown package: " + packageName);
11645                }
11646                throw new IllegalArgumentException(
11647                        "Unknown component: " + packageName
11648                        + "/" + className);
11649            }
11650            // Allow root and verify that userId is not being specified by a different user
11651            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11652                throw new SecurityException(
11653                        "Permission Denial: attempt to change component state from pid="
11654                        + Binder.getCallingPid()
11655                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11656            }
11657            if (className == null) {
11658                // We're dealing with an application/package level state change
11659                if (pkgSetting.getEnabled(userId) == newState) {
11660                    // Nothing to do
11661                    return;
11662                }
11663                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11664                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11665                    // Don't care about who enables an app.
11666                    callingPackage = null;
11667                }
11668                pkgSetting.setEnabled(newState, userId, callingPackage);
11669                // pkgSetting.pkg.mSetEnabled = newState;
11670            } else {
11671                // We're dealing with a component level state change
11672                // First, verify that this is a valid class name.
11673                PackageParser.Package pkg = pkgSetting.pkg;
11674                if (pkg == null || !pkg.hasComponentClassName(className)) {
11675                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11676                        throw new IllegalArgumentException("Component class " + className
11677                                + " does not exist in " + packageName);
11678                    } else {
11679                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11680                                + className + " does not exist in " + packageName);
11681                    }
11682                }
11683                switch (newState) {
11684                case COMPONENT_ENABLED_STATE_ENABLED:
11685                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11686                        return;
11687                    }
11688                    break;
11689                case COMPONENT_ENABLED_STATE_DISABLED:
11690                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11691                        return;
11692                    }
11693                    break;
11694                case COMPONENT_ENABLED_STATE_DEFAULT:
11695                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11696                        return;
11697                    }
11698                    break;
11699                default:
11700                    Slog.e(TAG, "Invalid new component state: " + newState);
11701                    return;
11702                }
11703            }
11704            mSettings.writePackageRestrictionsLPr(userId);
11705            components = mPendingBroadcasts.get(userId, packageName);
11706            final boolean newPackage = components == null;
11707            if (newPackage) {
11708                components = new ArrayList<String>();
11709            }
11710            if (!components.contains(componentName)) {
11711                components.add(componentName);
11712            }
11713            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11714                sendNow = true;
11715                // Purge entry from pending broadcast list if another one exists already
11716                // since we are sending one right away.
11717                mPendingBroadcasts.remove(userId, packageName);
11718            } else {
11719                if (newPackage) {
11720                    mPendingBroadcasts.put(userId, packageName, components);
11721                }
11722                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11723                    // Schedule a message
11724                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11725                }
11726            }
11727        }
11728
11729        long callingId = Binder.clearCallingIdentity();
11730        try {
11731            if (sendNow) {
11732                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11733                sendPackageChangedBroadcast(packageName,
11734                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11735            }
11736        } finally {
11737            Binder.restoreCallingIdentity(callingId);
11738        }
11739    }
11740
11741    private void sendPackageChangedBroadcast(String packageName,
11742            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11743        if (DEBUG_INSTALL)
11744            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11745                    + componentNames);
11746        Bundle extras = new Bundle(4);
11747        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11748        String nameList[] = new String[componentNames.size()];
11749        componentNames.toArray(nameList);
11750        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11751        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11752        extras.putInt(Intent.EXTRA_UID, packageUid);
11753        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11754                new int[] {UserHandle.getUserId(packageUid)});
11755    }
11756
11757    @Override
11758    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11759        if (!sUserManager.exists(userId)) return;
11760        final int uid = Binder.getCallingUid();
11761        final int permission = mContext.checkCallingOrSelfPermission(
11762                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11763        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11764        enforceCrossUserPermission(uid, userId, true, "stop package");
11765        // writer
11766        synchronized (mPackages) {
11767            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11768                    uid, userId)) {
11769                scheduleWritePackageRestrictionsLocked(userId);
11770            }
11771        }
11772    }
11773
11774    @Override
11775    public String getInstallerPackageName(String packageName) {
11776        // reader
11777        synchronized (mPackages) {
11778            return mSettings.getInstallerPackageNameLPr(packageName);
11779        }
11780    }
11781
11782    @Override
11783    public int getApplicationEnabledSetting(String packageName, int userId) {
11784        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11785        int uid = Binder.getCallingUid();
11786        enforceCrossUserPermission(uid, userId, false, "get enabled");
11787        // reader
11788        synchronized (mPackages) {
11789            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11790        }
11791    }
11792
11793    @Override
11794    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11795        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11796        int uid = Binder.getCallingUid();
11797        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11798        // reader
11799        synchronized (mPackages) {
11800            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11801        }
11802    }
11803
11804    @Override
11805    public void enterSafeMode() {
11806        enforceSystemOrRoot("Only the system can request entering safe mode");
11807
11808        if (!mSystemReady) {
11809            mSafeMode = true;
11810        }
11811    }
11812
11813    @Override
11814    public void systemReady() {
11815        mSystemReady = true;
11816
11817        // Read the compatibilty setting when the system is ready.
11818        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11819                mContext.getContentResolver(),
11820                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11821        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11822        if (DEBUG_SETTINGS) {
11823            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11824        }
11825
11826        synchronized (mPackages) {
11827            // Verify that all of the preferred activity components actually
11828            // exist.  It is possible for applications to be updated and at
11829            // that point remove a previously declared activity component that
11830            // had been set as a preferred activity.  We try to clean this up
11831            // the next time we encounter that preferred activity, but it is
11832            // possible for the user flow to never be able to return to that
11833            // situation so here we do a sanity check to make sure we haven't
11834            // left any junk around.
11835            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11836            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11837                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11838                removed.clear();
11839                for (PreferredActivity pa : pir.filterSet()) {
11840                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11841                        removed.add(pa);
11842                    }
11843                }
11844                if (removed.size() > 0) {
11845                    for (int r=0; r<removed.size(); r++) {
11846                        PreferredActivity pa = removed.get(r);
11847                        Slog.w(TAG, "Removing dangling preferred activity: "
11848                                + pa.mPref.mComponent);
11849                        pir.removeFilter(pa);
11850                    }
11851                    mSettings.writePackageRestrictionsLPr(
11852                            mSettings.mPreferredActivities.keyAt(i));
11853                }
11854            }
11855        }
11856        sUserManager.systemReady();
11857    }
11858
11859    @Override
11860    public boolean isSafeMode() {
11861        return mSafeMode;
11862    }
11863
11864    @Override
11865    public boolean hasSystemUidErrors() {
11866        return mHasSystemUidErrors;
11867    }
11868
11869    static String arrayToString(int[] array) {
11870        StringBuffer buf = new StringBuffer(128);
11871        buf.append('[');
11872        if (array != null) {
11873            for (int i=0; i<array.length; i++) {
11874                if (i > 0) buf.append(", ");
11875                buf.append(array[i]);
11876            }
11877        }
11878        buf.append(']');
11879        return buf.toString();
11880    }
11881
11882    static class DumpState {
11883        public static final int DUMP_LIBS = 1 << 0;
11884
11885        public static final int DUMP_FEATURES = 1 << 1;
11886
11887        public static final int DUMP_RESOLVERS = 1 << 2;
11888
11889        public static final int DUMP_PERMISSIONS = 1 << 3;
11890
11891        public static final int DUMP_PACKAGES = 1 << 4;
11892
11893        public static final int DUMP_SHARED_USERS = 1 << 5;
11894
11895        public static final int DUMP_MESSAGES = 1 << 6;
11896
11897        public static final int DUMP_PROVIDERS = 1 << 7;
11898
11899        public static final int DUMP_VERIFIERS = 1 << 8;
11900
11901        public static final int DUMP_PREFERRED = 1 << 9;
11902
11903        public static final int DUMP_PREFERRED_XML = 1 << 10;
11904
11905        public static final int DUMP_KEYSETS = 1 << 11;
11906
11907        public static final int DUMP_VERSION = 1 << 12;
11908
11909        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11910
11911        private int mTypes;
11912
11913        private int mOptions;
11914
11915        private boolean mTitlePrinted;
11916
11917        private SharedUserSetting mSharedUser;
11918
11919        public boolean isDumping(int type) {
11920            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11921                return true;
11922            }
11923
11924            return (mTypes & type) != 0;
11925        }
11926
11927        public void setDump(int type) {
11928            mTypes |= type;
11929        }
11930
11931        public boolean isOptionEnabled(int option) {
11932            return (mOptions & option) != 0;
11933        }
11934
11935        public void setOptionEnabled(int option) {
11936            mOptions |= option;
11937        }
11938
11939        public boolean onTitlePrinted() {
11940            final boolean printed = mTitlePrinted;
11941            mTitlePrinted = true;
11942            return printed;
11943        }
11944
11945        public boolean getTitlePrinted() {
11946            return mTitlePrinted;
11947        }
11948
11949        public void setTitlePrinted(boolean enabled) {
11950            mTitlePrinted = enabled;
11951        }
11952
11953        public SharedUserSetting getSharedUser() {
11954            return mSharedUser;
11955        }
11956
11957        public void setSharedUser(SharedUserSetting user) {
11958            mSharedUser = user;
11959        }
11960    }
11961
11962    @Override
11963    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
11964        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
11965                != PackageManager.PERMISSION_GRANTED) {
11966            pw.println("Permission Denial: can't dump ActivityManager from from pid="
11967                    + Binder.getCallingPid()
11968                    + ", uid=" + Binder.getCallingUid()
11969                    + " without permission "
11970                    + android.Manifest.permission.DUMP);
11971            return;
11972        }
11973
11974        DumpState dumpState = new DumpState();
11975        boolean fullPreferred = false;
11976        boolean checkin = false;
11977
11978        String packageName = null;
11979
11980        int opti = 0;
11981        while (opti < args.length) {
11982            String opt = args[opti];
11983            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
11984                break;
11985            }
11986            opti++;
11987            if ("-a".equals(opt)) {
11988                // Right now we only know how to print all.
11989            } else if ("-h".equals(opt)) {
11990                pw.println("Package manager dump options:");
11991                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
11992                pw.println("    --checkin: dump for a checkin");
11993                pw.println("    -f: print details of intent filters");
11994                pw.println("    -h: print this help");
11995                pw.println("  cmd may be one of:");
11996                pw.println("    l[ibraries]: list known shared libraries");
11997                pw.println("    f[ibraries]: list device features");
11998                pw.println("    k[eysets]: print known keysets");
11999                pw.println("    r[esolvers]: dump intent resolvers");
12000                pw.println("    perm[issions]: dump permissions");
12001                pw.println("    pref[erred]: print preferred package settings");
12002                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12003                pw.println("    prov[iders]: dump content providers");
12004                pw.println("    p[ackages]: dump installed packages");
12005                pw.println("    s[hared-users]: dump shared user IDs");
12006                pw.println("    m[essages]: print collected runtime messages");
12007                pw.println("    v[erifiers]: print package verifier info");
12008                pw.println("    version: print database version info");
12009                pw.println("    write: write current settings now");
12010                pw.println("    <package.name>: info about given package");
12011                return;
12012            } else if ("--checkin".equals(opt)) {
12013                checkin = true;
12014            } else if ("-f".equals(opt)) {
12015                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12016            } else {
12017                pw.println("Unknown argument: " + opt + "; use -h for help");
12018            }
12019        }
12020
12021        // Is the caller requesting to dump a particular piece of data?
12022        if (opti < args.length) {
12023            String cmd = args[opti];
12024            opti++;
12025            // Is this a package name?
12026            if ("android".equals(cmd) || cmd.contains(".")) {
12027                packageName = cmd;
12028                // When dumping a single package, we always dump all of its
12029                // filter information since the amount of data will be reasonable.
12030                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12031            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12032                dumpState.setDump(DumpState.DUMP_LIBS);
12033            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12034                dumpState.setDump(DumpState.DUMP_FEATURES);
12035            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12036                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12037            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12038                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12039            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12040                dumpState.setDump(DumpState.DUMP_PREFERRED);
12041            } else if ("preferred-xml".equals(cmd)) {
12042                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12043                if (opti < args.length && "--full".equals(args[opti])) {
12044                    fullPreferred = true;
12045                    opti++;
12046                }
12047            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12048                dumpState.setDump(DumpState.DUMP_PACKAGES);
12049            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12050                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12051            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12052                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12053            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12054                dumpState.setDump(DumpState.DUMP_MESSAGES);
12055            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12056                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12057            } else if ("version".equals(cmd)) {
12058                dumpState.setDump(DumpState.DUMP_VERSION);
12059            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12060                dumpState.setDump(DumpState.DUMP_KEYSETS);
12061            } else if ("write".equals(cmd)) {
12062                synchronized (mPackages) {
12063                    mSettings.writeLPr();
12064                    pw.println("Settings written.");
12065                    return;
12066                }
12067            }
12068        }
12069
12070        if (checkin) {
12071            pw.println("vers,1");
12072        }
12073
12074        // reader
12075        synchronized (mPackages) {
12076            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12077                if (!checkin) {
12078                    if (dumpState.onTitlePrinted())
12079                        pw.println();
12080                    pw.println("Database versions:");
12081                    pw.print("  SDK Version:");
12082                    pw.print(" internal=");
12083                    pw.print(mSettings.mInternalSdkPlatform);
12084                    pw.print(" external=");
12085                    pw.println(mSettings.mExternalSdkPlatform);
12086                    pw.print("  DB Version:");
12087                    pw.print(" internal=");
12088                    pw.print(mSettings.mInternalDatabaseVersion);
12089                    pw.print(" external=");
12090                    pw.println(mSettings.mExternalDatabaseVersion);
12091                }
12092            }
12093
12094            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12095                if (!checkin) {
12096                    if (dumpState.onTitlePrinted())
12097                        pw.println();
12098                    pw.println("Verifiers:");
12099                    pw.print("  Required: ");
12100                    pw.print(mRequiredVerifierPackage);
12101                    pw.print(" (uid=");
12102                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12103                    pw.println(")");
12104                } else if (mRequiredVerifierPackage != null) {
12105                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12106                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12107                }
12108            }
12109
12110            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12111                boolean printedHeader = false;
12112                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12113                while (it.hasNext()) {
12114                    String name = it.next();
12115                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12116                    if (!checkin) {
12117                        if (!printedHeader) {
12118                            if (dumpState.onTitlePrinted())
12119                                pw.println();
12120                            pw.println("Libraries:");
12121                            printedHeader = true;
12122                        }
12123                        pw.print("  ");
12124                    } else {
12125                        pw.print("lib,");
12126                    }
12127                    pw.print(name);
12128                    if (!checkin) {
12129                        pw.print(" -> ");
12130                    }
12131                    if (ent.path != null) {
12132                        if (!checkin) {
12133                            pw.print("(jar) ");
12134                            pw.print(ent.path);
12135                        } else {
12136                            pw.print(",jar,");
12137                            pw.print(ent.path);
12138                        }
12139                    } else {
12140                        if (!checkin) {
12141                            pw.print("(apk) ");
12142                            pw.print(ent.apk);
12143                        } else {
12144                            pw.print(",apk,");
12145                            pw.print(ent.apk);
12146                        }
12147                    }
12148                    pw.println();
12149                }
12150            }
12151
12152            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12153                if (dumpState.onTitlePrinted())
12154                    pw.println();
12155                if (!checkin) {
12156                    pw.println("Features:");
12157                }
12158                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12159                while (it.hasNext()) {
12160                    String name = it.next();
12161                    if (!checkin) {
12162                        pw.print("  ");
12163                    } else {
12164                        pw.print("feat,");
12165                    }
12166                    pw.println(name);
12167                }
12168            }
12169
12170            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12171                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12172                        : "Activity Resolver Table:", "  ", packageName,
12173                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12174                    dumpState.setTitlePrinted(true);
12175                }
12176                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12177                        : "Receiver Resolver Table:", "  ", packageName,
12178                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12179                    dumpState.setTitlePrinted(true);
12180                }
12181                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12182                        : "Service Resolver Table:", "  ", packageName,
12183                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12184                    dumpState.setTitlePrinted(true);
12185                }
12186                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12187                        : "Provider Resolver Table:", "  ", packageName,
12188                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12189                    dumpState.setTitlePrinted(true);
12190                }
12191            }
12192
12193            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12194                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12195                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12196                    int user = mSettings.mPreferredActivities.keyAt(i);
12197                    if (pir.dump(pw,
12198                            dumpState.getTitlePrinted()
12199                                ? "\nPreferred Activities User " + user + ":"
12200                                : "Preferred Activities User " + user + ":", "  ",
12201                            packageName, true)) {
12202                        dumpState.setTitlePrinted(true);
12203                    }
12204                }
12205            }
12206
12207            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12208                pw.flush();
12209                FileOutputStream fout = new FileOutputStream(fd);
12210                BufferedOutputStream str = new BufferedOutputStream(fout);
12211                XmlSerializer serializer = new FastXmlSerializer();
12212                try {
12213                    serializer.setOutput(str, "utf-8");
12214                    serializer.startDocument(null, true);
12215                    serializer.setFeature(
12216                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12217                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12218                    serializer.endDocument();
12219                    serializer.flush();
12220                } catch (IllegalArgumentException e) {
12221                    pw.println("Failed writing: " + e);
12222                } catch (IllegalStateException e) {
12223                    pw.println("Failed writing: " + e);
12224                } catch (IOException e) {
12225                    pw.println("Failed writing: " + e);
12226                }
12227            }
12228
12229            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12230                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12231            }
12232
12233            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12234                boolean printedSomething = false;
12235                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12236                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12237                        continue;
12238                    }
12239                    if (!printedSomething) {
12240                        if (dumpState.onTitlePrinted())
12241                            pw.println();
12242                        pw.println("Registered ContentProviders:");
12243                        printedSomething = true;
12244                    }
12245                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12246                    pw.print("    "); pw.println(p.toString());
12247                }
12248                printedSomething = false;
12249                for (Map.Entry<String, PackageParser.Provider> entry :
12250                        mProvidersByAuthority.entrySet()) {
12251                    PackageParser.Provider p = entry.getValue();
12252                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12253                        continue;
12254                    }
12255                    if (!printedSomething) {
12256                        if (dumpState.onTitlePrinted())
12257                            pw.println();
12258                        pw.println("ContentProvider Authorities:");
12259                        printedSomething = true;
12260                    }
12261                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12262                    pw.print("    "); pw.println(p.toString());
12263                    if (p.info != null && p.info.applicationInfo != null) {
12264                        final String appInfo = p.info.applicationInfo.toString();
12265                        pw.print("      applicationInfo="); pw.println(appInfo);
12266                    }
12267                }
12268            }
12269
12270            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12271                mSettings.mKeySetManager.dump(pw, packageName, dumpState);
12272            }
12273
12274            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12275                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12276            }
12277
12278            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12279                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12280            }
12281
12282            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12283                if (dumpState.onTitlePrinted())
12284                    pw.println();
12285                mSettings.dumpReadMessagesLPr(pw, dumpState);
12286
12287                pw.println();
12288                pw.println("Package warning messages:");
12289                final File fname = getSettingsProblemFile();
12290                FileInputStream in = null;
12291                try {
12292                    in = new FileInputStream(fname);
12293                    final int avail = in.available();
12294                    final byte[] data = new byte[avail];
12295                    in.read(data);
12296                    pw.print(new String(data));
12297                } catch (FileNotFoundException e) {
12298                } catch (IOException e) {
12299                } finally {
12300                    if (in != null) {
12301                        try {
12302                            in.close();
12303                        } catch (IOException e) {
12304                        }
12305                    }
12306                }
12307            }
12308        }
12309    }
12310
12311    // ------- apps on sdcard specific code -------
12312    static final boolean DEBUG_SD_INSTALL = false;
12313
12314    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12315
12316    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12317
12318    private boolean mMediaMounted = false;
12319
12320    private String getEncryptKey() {
12321        try {
12322            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12323                    SD_ENCRYPTION_KEYSTORE_NAME);
12324            if (sdEncKey == null) {
12325                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12326                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12327                if (sdEncKey == null) {
12328                    Slog.e(TAG, "Failed to create encryption keys");
12329                    return null;
12330                }
12331            }
12332            return sdEncKey;
12333        } catch (NoSuchAlgorithmException nsae) {
12334            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12335            return null;
12336        } catch (IOException ioe) {
12337            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12338            return null;
12339        }
12340
12341    }
12342
12343    /* package */static String getTempContainerId() {
12344        int tmpIdx = 1;
12345        String list[] = PackageHelper.getSecureContainerList();
12346        if (list != null) {
12347            for (final String name : list) {
12348                // Ignore null and non-temporary container entries
12349                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12350                    continue;
12351                }
12352
12353                String subStr = name.substring(mTempContainerPrefix.length());
12354                try {
12355                    int cid = Integer.parseInt(subStr);
12356                    if (cid >= tmpIdx) {
12357                        tmpIdx = cid + 1;
12358                    }
12359                } catch (NumberFormatException e) {
12360                }
12361            }
12362        }
12363        return mTempContainerPrefix + tmpIdx;
12364    }
12365
12366    /*
12367     * Update media status on PackageManager.
12368     */
12369    @Override
12370    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12371        int callingUid = Binder.getCallingUid();
12372        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12373            throw new SecurityException("Media status can only be updated by the system");
12374        }
12375        // reader; this apparently protects mMediaMounted, but should probably
12376        // be a different lock in that case.
12377        synchronized (mPackages) {
12378            Log.i(TAG, "Updating external media status from "
12379                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12380                    + (mediaStatus ? "mounted" : "unmounted"));
12381            if (DEBUG_SD_INSTALL)
12382                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12383                        + ", mMediaMounted=" + mMediaMounted);
12384            if (mediaStatus == mMediaMounted) {
12385                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12386                        : 0, -1);
12387                mHandler.sendMessage(msg);
12388                return;
12389            }
12390            mMediaMounted = mediaStatus;
12391        }
12392        // Queue up an async operation since the package installation may take a
12393        // little while.
12394        mHandler.post(new Runnable() {
12395            public void run() {
12396                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12397            }
12398        });
12399    }
12400
12401    /**
12402     * Called by MountService when the initial ASECs to scan are available.
12403     * Should block until all the ASEC containers are finished being scanned.
12404     */
12405    public void scanAvailableAsecs() {
12406        updateExternalMediaStatusInner(true, false, false);
12407        if (mShouldRestoreconData) {
12408            SELinuxMMAC.setRestoreconDone();
12409            mShouldRestoreconData = false;
12410        }
12411    }
12412
12413    /*
12414     * Collect information of applications on external media, map them against
12415     * existing containers and update information based on current mount status.
12416     * Please note that we always have to report status if reportStatus has been
12417     * set to true especially when unloading packages.
12418     */
12419    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12420            boolean externalStorage) {
12421        // Collection of uids
12422        int uidArr[] = null;
12423        // Collection of stale containers
12424        HashSet<String> removeCids = new HashSet<String>();
12425        // Collection of packages on external media with valid containers.
12426        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12427        // Get list of secure containers.
12428        final String list[] = PackageHelper.getSecureContainerList();
12429        if (list == null || list.length == 0) {
12430            Log.i(TAG, "No secure containers on sdcard");
12431        } else {
12432            // Process list of secure containers and categorize them
12433            // as active or stale based on their package internal state.
12434            int uidList[] = new int[list.length];
12435            int num = 0;
12436            // reader
12437            synchronized (mPackages) {
12438                for (String cid : list) {
12439                    if (DEBUG_SD_INSTALL)
12440                        Log.i(TAG, "Processing container " + cid);
12441                    String pkgName = getAsecPackageName(cid);
12442                    if (pkgName == null) {
12443                        if (DEBUG_SD_INSTALL)
12444                            Log.i(TAG, "Container : " + cid + " stale");
12445                        removeCids.add(cid);
12446                        continue;
12447                    }
12448                    if (DEBUG_SD_INSTALL)
12449                        Log.i(TAG, "Looking for pkg : " + pkgName);
12450
12451                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12452                    if (ps == null) {
12453                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12454                        removeCids.add(cid);
12455                        continue;
12456                    }
12457
12458                    /*
12459                     * Skip packages that are not external if we're unmounting
12460                     * external storage.
12461                     */
12462                    if (externalStorage && !isMounted && !isExternal(ps)) {
12463                        continue;
12464                    }
12465
12466                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12467                            getAppInstructionSetFromSettings(ps),
12468                            isForwardLocked(ps));
12469                    // The package status is changed only if the code path
12470                    // matches between settings and the container id.
12471                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12472                        if (DEBUG_SD_INSTALL) {
12473                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12474                                    + " at code path: " + ps.codePathString);
12475                        }
12476
12477                        // We do have a valid package installed on sdcard
12478                        processCids.put(args, ps.codePathString);
12479                        final int uid = ps.appId;
12480                        if (uid != -1) {
12481                            uidList[num++] = uid;
12482                        }
12483                    } else {
12484                        Log.i(TAG, "Deleting stale container for " + cid);
12485                        removeCids.add(cid);
12486                    }
12487                }
12488            }
12489
12490            if (num > 0) {
12491                // Sort uid list
12492                Arrays.sort(uidList, 0, num);
12493                // Throw away duplicates
12494                uidArr = new int[num];
12495                uidArr[0] = uidList[0];
12496                int di = 0;
12497                for (int i = 1; i < num; i++) {
12498                    if (uidList[i - 1] != uidList[i]) {
12499                        uidArr[di++] = uidList[i];
12500                    }
12501                }
12502            }
12503        }
12504        // Process packages with valid entries.
12505        if (isMounted) {
12506            if (DEBUG_SD_INSTALL)
12507                Log.i(TAG, "Loading packages");
12508            loadMediaPackages(processCids, uidArr, removeCids);
12509            startCleaningPackages();
12510        } else {
12511            if (DEBUG_SD_INSTALL)
12512                Log.i(TAG, "Unloading packages");
12513            unloadMediaPackages(processCids, uidArr, reportStatus);
12514        }
12515    }
12516
12517   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12518           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12519        int size = pkgList.size();
12520        if (size > 0) {
12521            // Send broadcasts here
12522            Bundle extras = new Bundle();
12523            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12524                    .toArray(new String[size]));
12525            if (uidArr != null) {
12526                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12527            }
12528            if (replacing) {
12529                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12530            }
12531            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12532                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12533            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12534        }
12535    }
12536
12537   /*
12538     * Look at potentially valid container ids from processCids If package
12539     * information doesn't match the one on record or package scanning fails,
12540     * the cid is added to list of removeCids. We currently don't delete stale
12541     * containers.
12542     */
12543   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12544            HashSet<String> removeCids) {
12545        ArrayList<String> pkgList = new ArrayList<String>();
12546        Set<AsecInstallArgs> keys = processCids.keySet();
12547        boolean doGc = false;
12548        for (AsecInstallArgs args : keys) {
12549            String codePath = processCids.get(args);
12550            if (DEBUG_SD_INSTALL)
12551                Log.i(TAG, "Loading container : " + args.cid);
12552            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12553            try {
12554                // Make sure there are no container errors first.
12555                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12556                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12557                            + " when installing from sdcard");
12558                    continue;
12559                }
12560                // Check code path here.
12561                if (codePath == null || !codePath.equals(args.getCodePath())) {
12562                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12563                            + " does not match one in settings " + codePath);
12564                    continue;
12565                }
12566                // Parse package
12567                int parseFlags = mDefParseFlags;
12568                if (args.isExternal()) {
12569                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12570                }
12571                if (args.isFwdLocked()) {
12572                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12573                }
12574
12575                doGc = true;
12576                synchronized (mInstallLock) {
12577                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
12578                            0, 0, null, null);
12579                    // Scan the package
12580                    if (pkg != null) {
12581                        /*
12582                         * TODO why is the lock being held? doPostInstall is
12583                         * called in other places without the lock. This needs
12584                         * to be straightened out.
12585                         */
12586                        // writer
12587                        synchronized (mPackages) {
12588                            retCode = PackageManager.INSTALL_SUCCEEDED;
12589                            pkgList.add(pkg.packageName);
12590                            // Post process args
12591                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12592                                    pkg.applicationInfo.uid);
12593                        }
12594                    } else {
12595                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12596                    }
12597                }
12598
12599            } finally {
12600                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12601                    // Don't destroy container here. Wait till gc clears things
12602                    // up.
12603                    removeCids.add(args.cid);
12604                }
12605            }
12606        }
12607        // writer
12608        synchronized (mPackages) {
12609            // If the platform SDK has changed since the last time we booted,
12610            // we need to re-grant app permission to catch any new ones that
12611            // appear. This is really a hack, and means that apps can in some
12612            // cases get permissions that the user didn't initially explicitly
12613            // allow... it would be nice to have some better way to handle
12614            // this situation.
12615            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12616            if (regrantPermissions)
12617                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12618                        + mSdkVersion + "; regranting permissions for external storage");
12619            mSettings.mExternalSdkPlatform = mSdkVersion;
12620
12621            // Make sure group IDs have been assigned, and any permission
12622            // changes in other apps are accounted for
12623            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12624                    | (regrantPermissions
12625                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12626                            : 0));
12627
12628            mSettings.updateExternalDatabaseVersion();
12629
12630            // can downgrade to reader
12631            // Persist settings
12632            mSettings.writeLPr();
12633        }
12634        // Send a broadcast to let everyone know we are done processing
12635        if (pkgList.size() > 0) {
12636            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12637        }
12638        // Force gc to avoid any stale parser references that we might have.
12639        if (doGc) {
12640            Runtime.getRuntime().gc();
12641        }
12642        // List stale containers and destroy stale temporary containers.
12643        if (removeCids != null) {
12644            for (String cid : removeCids) {
12645                if (cid.startsWith(mTempContainerPrefix)) {
12646                    Log.i(TAG, "Destroying stale temporary container " + cid);
12647                    PackageHelper.destroySdDir(cid);
12648                } else {
12649                    Log.w(TAG, "Container " + cid + " is stale");
12650               }
12651           }
12652        }
12653    }
12654
12655   /*
12656     * Utility method to unload a list of specified containers
12657     */
12658    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12659        // Just unmount all valid containers.
12660        for (AsecInstallArgs arg : cidArgs) {
12661            synchronized (mInstallLock) {
12662                arg.doPostDeleteLI(false);
12663           }
12664       }
12665   }
12666
12667    /*
12668     * Unload packages mounted on external media. This involves deleting package
12669     * data from internal structures, sending broadcasts about diabled packages,
12670     * gc'ing to free up references, unmounting all secure containers
12671     * corresponding to packages on external media, and posting a
12672     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12673     * that we always have to post this message if status has been requested no
12674     * matter what.
12675     */
12676    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12677            final boolean reportStatus) {
12678        if (DEBUG_SD_INSTALL)
12679            Log.i(TAG, "unloading media packages");
12680        ArrayList<String> pkgList = new ArrayList<String>();
12681        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12682        final Set<AsecInstallArgs> keys = processCids.keySet();
12683        for (AsecInstallArgs args : keys) {
12684            String pkgName = args.getPackageName();
12685            if (DEBUG_SD_INSTALL)
12686                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12687            // Delete package internally
12688            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12689            synchronized (mInstallLock) {
12690                boolean res = deletePackageLI(pkgName, null, false, null, null,
12691                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12692                if (res) {
12693                    pkgList.add(pkgName);
12694                } else {
12695                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12696                    failedList.add(args);
12697                }
12698            }
12699        }
12700
12701        // reader
12702        synchronized (mPackages) {
12703            // We didn't update the settings after removing each package;
12704            // write them now for all packages.
12705            mSettings.writeLPr();
12706        }
12707
12708        // We have to absolutely send UPDATED_MEDIA_STATUS only
12709        // after confirming that all the receivers processed the ordered
12710        // broadcast when packages get disabled, force a gc to clean things up.
12711        // and unload all the containers.
12712        if (pkgList.size() > 0) {
12713            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12714                    new IIntentReceiver.Stub() {
12715                public void performReceive(Intent intent, int resultCode, String data,
12716                        Bundle extras, boolean ordered, boolean sticky,
12717                        int sendingUser) throws RemoteException {
12718                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12719                            reportStatus ? 1 : 0, 1, keys);
12720                    mHandler.sendMessage(msg);
12721                }
12722            });
12723        } else {
12724            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12725                    keys);
12726            mHandler.sendMessage(msg);
12727        }
12728    }
12729
12730    /** Binder call */
12731    @Override
12732    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12733            final int flags) {
12734        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12735        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12736        int returnCode = PackageManager.MOVE_SUCCEEDED;
12737        int currFlags = 0;
12738        int newFlags = 0;
12739        // reader
12740        synchronized (mPackages) {
12741            PackageParser.Package pkg = mPackages.get(packageName);
12742            if (pkg == null) {
12743                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12744            } else {
12745                // Disable moving fwd locked apps and system packages
12746                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12747                    Slog.w(TAG, "Cannot move system application");
12748                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12749                } else if (pkg.mOperationPending) {
12750                    Slog.w(TAG, "Attempt to move package which has pending operations");
12751                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12752                } else {
12753                    // Find install location first
12754                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12755                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12756                        Slog.w(TAG, "Ambigous flags specified for move location.");
12757                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12758                    } else {
12759                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12760                                : PackageManager.INSTALL_INTERNAL;
12761                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12762                                : PackageManager.INSTALL_INTERNAL;
12763
12764                        if (newFlags == currFlags) {
12765                            Slog.w(TAG, "No move required. Trying to move to same location");
12766                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12767                        } else {
12768                            if (isForwardLocked(pkg)) {
12769                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12770                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12771                            }
12772                        }
12773                    }
12774                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12775                        pkg.mOperationPending = true;
12776                    }
12777                }
12778            }
12779
12780            /*
12781             * TODO this next block probably shouldn't be inside the lock. We
12782             * can't guarantee these won't change after this is fired off
12783             * anyway.
12784             */
12785            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12786                processPendingMove(new MoveParams(null, observer, 0, packageName, null,
12787                        null, -1, user),
12788                        returnCode);
12789            } else {
12790                Message msg = mHandler.obtainMessage(INIT_COPY);
12791                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
12792                InstallArgs srcArgs = createInstallArgs(currFlags, pkg.applicationInfo.sourceDir,
12793                        pkg.applicationInfo.publicSourceDir, pkg.applicationInfo.nativeLibraryDir,
12794                        instructionSet);
12795                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12796                        pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user);
12797                msg.obj = mp;
12798                mHandler.sendMessage(msg);
12799            }
12800        }
12801    }
12802
12803    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12804        // Queue up an async operation since the package deletion may take a
12805        // little while.
12806        mHandler.post(new Runnable() {
12807            public void run() {
12808                // TODO fix this; this does nothing.
12809                mHandler.removeCallbacks(this);
12810                int returnCode = currentStatus;
12811                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12812                    int uidArr[] = null;
12813                    ArrayList<String> pkgList = null;
12814                    synchronized (mPackages) {
12815                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12816                        if (pkg == null) {
12817                            Slog.w(TAG, " Package " + mp.packageName
12818                                    + " doesn't exist. Aborting move");
12819                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12820                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
12821                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12822                                    + mp.srcArgs.getCodePath() + " to "
12823                                    + pkg.applicationInfo.sourceDir
12824                                    + " Aborting move and returning error");
12825                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12826                        } else {
12827                            uidArr = new int[] {
12828                                pkg.applicationInfo.uid
12829                            };
12830                            pkgList = new ArrayList<String>();
12831                            pkgList.add(mp.packageName);
12832                        }
12833                    }
12834                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12835                        // Send resources unavailable broadcast
12836                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12837                        // Update package code and resource paths
12838                        synchronized (mInstallLock) {
12839                            synchronized (mPackages) {
12840                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12841                                // Recheck for package again.
12842                                if (pkg == null) {
12843                                    Slog.w(TAG, " Package " + mp.packageName
12844                                            + " doesn't exist. Aborting move");
12845                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12846                                } else if (!mp.srcArgs.getCodePath().equals(
12847                                        pkg.applicationInfo.sourceDir)) {
12848                                    Slog.w(TAG, "Package " + mp.packageName
12849                                            + " code path changed from " + mp.srcArgs.getCodePath()
12850                                            + " to " + pkg.applicationInfo.sourceDir
12851                                            + " Aborting move and returning error");
12852                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12853                                } else {
12854                                    final String oldCodePath = pkg.codePath;
12855                                    final String newCodePath = mp.targetArgs.getCodePath();
12856                                    final String newResPath = mp.targetArgs.getResourcePath();
12857                                    final String newNativePath = mp.targetArgs
12858                                            .getNativeLibraryPath();
12859
12860                                    final File newNativeDir = new File(newNativePath);
12861
12862                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12863                                        // NOTE: We do not report any errors from the APK scan and library
12864                                        // copy at this point.
12865                                        NativeLibraryHelper.ApkHandle handle =
12866                                                new NativeLibraryHelper.ApkHandle(newCodePath);
12867                                        final int abi = NativeLibraryHelper.findSupportedAbi(
12868                                                handle, Build.SUPPORTED_ABIS);
12869                                        if (abi >= 0) {
12870                                            NativeLibraryHelper.copyNativeBinariesIfNeededLI(
12871                                                    handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
12872                                        }
12873                                        handle.close();
12874                                    }
12875                                    final int[] users = sUserManager.getUserIds();
12876                                    for (int user : users) {
12877                                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
12878                                                newNativePath, user) < 0) {
12879                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12880                                        }
12881                                    }
12882
12883                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12884                                        pkg.codePath = newCodePath;
12885                                        // Move dex files around
12886                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
12887                                            // Moving of dex files failed. Set
12888                                            // error code and abort move.
12889                                            pkg.codePath = oldCodePath;
12890                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12891                                        }
12892                                    }
12893
12894                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12895                                        pkg.applicationInfo.sourceDir = newCodePath;
12896                                        pkg.applicationInfo.publicSourceDir = newResPath;
12897                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
12898                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
12899                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
12900                                        ps.codePathString = ps.codePath.getPath();
12901                                        ps.resourcePath = new File(
12902                                                pkg.applicationInfo.publicSourceDir);
12903                                        ps.resourcePathString = ps.resourcePath.getPath();
12904                                        ps.nativeLibraryPathString = newNativePath;
12905                                        // Set the application info flag
12906                                        // correctly.
12907                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
12908                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12909                                        } else {
12910                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12911                                        }
12912                                        ps.setFlags(pkg.applicationInfo.flags);
12913                                        mAppDirs.remove(oldCodePath);
12914                                        mAppDirs.put(newCodePath, pkg);
12915                                        // Persist settings
12916                                        mSettings.writeLPr();
12917                                    }
12918                                }
12919                            }
12920                        }
12921                        // Send resources available broadcast
12922                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12923                    }
12924                }
12925                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12926                    // Clean up failed installation
12927                    if (mp.targetArgs != null) {
12928                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
12929                                -1);
12930                    }
12931                } else {
12932                    // Force a gc to clear things up.
12933                    Runtime.getRuntime().gc();
12934                    // Delete older code
12935                    synchronized (mInstallLock) {
12936                        mp.srcArgs.doPostDeleteLI(true);
12937                    }
12938                }
12939
12940                // Allow more operations on this file if we didn't fail because
12941                // an operation was already pending for this package.
12942                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
12943                    synchronized (mPackages) {
12944                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12945                        if (pkg != null) {
12946                            pkg.mOperationPending = false;
12947                       }
12948                   }
12949                }
12950
12951                IPackageMoveObserver observer = mp.observer;
12952                if (observer != null) {
12953                    try {
12954                        observer.packageMoved(mp.packageName, returnCode);
12955                    } catch (RemoteException e) {
12956                        Log.i(TAG, "Observer no longer exists.");
12957                    }
12958                }
12959            }
12960        });
12961    }
12962
12963    @Override
12964    public boolean setInstallLocation(int loc) {
12965        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12966                null);
12967        if (getInstallLocation() == loc) {
12968            return true;
12969        }
12970        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12971                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12972            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12973                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12974            return true;
12975        }
12976        return false;
12977   }
12978
12979    @Override
12980    public int getInstallLocation() {
12981        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12982                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12983                PackageHelper.APP_INSTALL_AUTO);
12984    }
12985
12986    /** Called by UserManagerService */
12987    void cleanUpUserLILPw(int userHandle) {
12988        mDirtyUsers.remove(userHandle);
12989        mSettings.removeUserLPr(userHandle);
12990        mPendingBroadcasts.remove(userHandle);
12991        if (mInstaller != null) {
12992            // Technically, we shouldn't be doing this with the package lock
12993            // held.  However, this is very rare, and there is already so much
12994            // other disk I/O going on, that we'll let it slide for now.
12995            mInstaller.removeUserDataDirs(userHandle);
12996        }
12997    }
12998
12999    /** Called by UserManagerService */
13000    void createNewUserLILPw(int userHandle, File path) {
13001        if (mInstaller != null) {
13002            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13003        }
13004    }
13005
13006    @Override
13007    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13008        mContext.enforceCallingOrSelfPermission(
13009                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13010                "Only package verification agents can read the verifier device identity");
13011
13012        synchronized (mPackages) {
13013            return mSettings.getVerifierDeviceIdentityLPw();
13014        }
13015    }
13016
13017    @Override
13018    public void setPermissionEnforced(String permission, boolean enforced) {
13019        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13020        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13021            synchronized (mPackages) {
13022                if (mSettings.mReadExternalStorageEnforced == null
13023                        || mSettings.mReadExternalStorageEnforced != enforced) {
13024                    mSettings.mReadExternalStorageEnforced = enforced;
13025                    mSettings.writeLPr();
13026                }
13027            }
13028            // kill any non-foreground processes so we restart them and
13029            // grant/revoke the GID.
13030            final IActivityManager am = ActivityManagerNative.getDefault();
13031            if (am != null) {
13032                final long token = Binder.clearCallingIdentity();
13033                try {
13034                    am.killProcessesBelowForeground("setPermissionEnforcement");
13035                } catch (RemoteException e) {
13036                } finally {
13037                    Binder.restoreCallingIdentity(token);
13038                }
13039            }
13040        } else {
13041            throw new IllegalArgumentException("No selective enforcement for " + permission);
13042        }
13043    }
13044
13045    @Override
13046    @Deprecated
13047    public boolean isPermissionEnforced(String permission) {
13048        return true;
13049    }
13050
13051    @Override
13052    public boolean isStorageLow() {
13053        final long token = Binder.clearCallingIdentity();
13054        try {
13055            final DeviceStorageMonitorInternal
13056                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13057            if (dsm != null) {
13058                return dsm.isMemoryLow();
13059            } else {
13060                return false;
13061            }
13062        } finally {
13063            Binder.restoreCallingIdentity(token);
13064        }
13065    }
13066
13067    @Override
13068    public IPackageInstaller getPackageInstaller() {
13069        return mInstallerService;
13070    }
13071}
13072