PackageManagerService.java revision 0c54798aac8a86fed24b14a66f09797d58ad0399
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.content.pm.PackageParser.isApkFile;
28import static android.os.Process.PACKAGE_INFO_GID;
29import static android.os.Process.SYSTEM_UID;
30import static android.system.OsConstants.S_IRGRP;
31import static android.system.OsConstants.S_IROTH;
32import static android.system.OsConstants.S_IRWXU;
33import static android.system.OsConstants.S_IXGRP;
34import static android.system.OsConstants.S_IXOTH;
35import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
36import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
37import static com.android.internal.util.ArrayUtils.appendInt;
38import static com.android.internal.util.ArrayUtils.removeInt;
39
40import android.util.ArrayMap;
41
42import com.android.internal.R;
43import com.android.internal.app.IMediaContainerService;
44import com.android.internal.app.ResolverActivity;
45import com.android.internal.content.NativeLibraryHelper;
46import com.android.internal.content.PackageHelper;
47import com.android.internal.util.ArrayUtils;
48import com.android.internal.util.FastPrintWriter;
49import com.android.internal.util.FastXmlSerializer;
50import com.android.internal.util.Preconditions;
51import com.android.internal.util.XmlUtils;
52import com.android.server.EventLogTags;
53import com.android.server.IntentResolver;
54import com.android.server.LocalServices;
55import com.android.server.ServiceThread;
56import com.android.server.SystemConfig;
57import com.android.server.Watchdog;
58import com.android.server.pm.Settings.DatabaseVersion;
59import com.android.server.storage.DeviceStorageMonitorInternal;
60
61import org.xmlpull.v1.XmlPullParser;
62import org.xmlpull.v1.XmlPullParserException;
63import org.xmlpull.v1.XmlSerializer;
64
65import android.app.ActivityManager;
66import android.app.ActivityManagerNative;
67import android.app.IActivityManager;
68import android.app.PackageInstallObserver;
69import android.app.admin.IDevicePolicyManager;
70import android.app.backup.IBackupManager;
71import android.content.BroadcastReceiver;
72import android.content.ComponentName;
73import android.content.Context;
74import android.content.IIntentReceiver;
75import android.content.Intent;
76import android.content.IntentFilter;
77import android.content.IntentSender;
78import android.content.IntentSender.SendIntentException;
79import android.content.ServiceConnection;
80import android.content.pm.ActivityInfo;
81import android.content.pm.ApplicationInfo;
82import android.content.pm.ContainerEncryptionParams;
83import android.content.pm.FeatureInfo;
84import android.content.pm.IPackageDataObserver;
85import android.content.pm.IPackageDeleteObserver;
86import android.content.pm.IPackageInstallObserver;
87import android.content.pm.IPackageInstallObserver2;
88import android.content.pm.IPackageInstaller;
89import android.content.pm.IPackageManager;
90import android.content.pm.IPackageMoveObserver;
91import android.content.pm.IPackageStatsObserver;
92import android.content.pm.InstrumentationInfo;
93import android.content.pm.ManifestDigest;
94import android.content.pm.PackageCleanItem;
95import android.content.pm.PackageInfo;
96import android.content.pm.PackageInfoLite;
97import android.content.pm.PackageInstallerParams;
98import android.content.pm.PackageManager;
99import android.content.pm.PackageParser.ActivityIntentInfo;
100import android.content.pm.PackageParser.PackageParserException;
101import android.content.pm.PackageParser;
102import android.content.pm.PackageStats;
103import android.content.pm.PackageUserState;
104import android.content.pm.ParceledListSlice;
105import android.content.pm.PermissionGroupInfo;
106import android.content.pm.PermissionInfo;
107import android.content.pm.ProviderInfo;
108import android.content.pm.ResolveInfo;
109import android.content.pm.ServiceInfo;
110import android.content.pm.Signature;
111import android.content.pm.UserInfo;
112import android.content.pm.VerificationParams;
113import android.content.pm.VerifierDeviceIdentity;
114import android.content.pm.VerifierInfo;
115import android.content.res.Resources;
116import android.hardware.display.DisplayManager;
117import android.net.Uri;
118import android.os.Binder;
119import android.os.Build;
120import android.os.Bundle;
121import android.os.Environment;
122import android.os.Environment.UserEnvironment;
123import android.os.FileObserver;
124import android.os.FileUtils;
125import android.os.Handler;
126import android.os.IBinder;
127import android.os.Looper;
128import android.os.Message;
129import android.os.Parcel;
130import android.os.ParcelFileDescriptor;
131import android.os.Process;
132import android.os.RemoteException;
133import android.os.SELinux;
134import android.os.ServiceManager;
135import android.os.SystemClock;
136import android.os.SystemProperties;
137import android.os.UserHandle;
138import android.os.UserManager;
139import android.security.KeyStore;
140import android.security.SystemKeyStore;
141import android.system.ErrnoException;
142import android.system.Os;
143import android.system.StructStat;
144import android.text.TextUtils;
145import android.util.ArraySet;
146import android.util.AtomicFile;
147import android.util.DisplayMetrics;
148import android.util.EventLog;
149import android.util.Log;
150import android.util.LogPrinter;
151import android.util.PrintStreamPrinter;
152import android.util.Slog;
153import android.util.SparseArray;
154import android.util.SparseBooleanArray;
155import android.util.Xml;
156import android.view.Display;
157
158import java.io.BufferedInputStream;
159import java.io.BufferedOutputStream;
160import java.io.File;
161import java.io.FileDescriptor;
162import java.io.FileInputStream;
163import java.io.FileNotFoundException;
164import java.io.FileOutputStream;
165import java.io.FileReader;
166import java.io.FilenameFilter;
167import java.io.IOException;
168import java.io.InputStream;
169import java.io.PrintWriter;
170import java.nio.charset.StandardCharsets;
171import java.security.NoSuchAlgorithmException;
172import java.security.PublicKey;
173import java.security.cert.CertificateEncodingException;
174import java.security.cert.CertificateException;
175import java.text.SimpleDateFormat;
176import java.util.ArrayList;
177import java.util.Arrays;
178import java.util.Collection;
179import java.util.Collections;
180import java.util.Comparator;
181import java.util.Date;
182import java.util.HashMap;
183import java.util.HashSet;
184import java.util.Iterator;
185import java.util.List;
186import java.util.Map;
187import java.util.Set;
188import java.util.concurrent.atomic.AtomicBoolean;
189import java.util.concurrent.atomic.AtomicLong;
190
191import dalvik.system.DexFile;
192import dalvik.system.StaleDexCacheError;
193import dalvik.system.VMRuntime;
194
195import libcore.io.IoUtils;
196
197/**
198 * Keep track of all those .apks everywhere.
199 *
200 * This is very central to the platform's security; please run the unit
201 * tests whenever making modifications here:
202 *
203mmm frameworks/base/tests/AndroidTests
204adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
205adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
206 *
207 * {@hide}
208 */
209public class PackageManagerService extends IPackageManager.Stub {
210    static final String TAG = "PackageManager";
211    static final boolean DEBUG_SETTINGS = false;
212    static final boolean DEBUG_PREFERRED = false;
213    static final boolean DEBUG_UPGRADE = false;
214    private static final boolean DEBUG_INSTALL = false;
215    private static final boolean DEBUG_REMOVE = false;
216    private static final boolean DEBUG_BROADCASTS = false;
217    private static final boolean DEBUG_SHOW_INFO = false;
218    private static final boolean DEBUG_PACKAGE_INFO = false;
219    private static final boolean DEBUG_INTENT_MATCHING = false;
220    private static final boolean DEBUG_PACKAGE_SCANNING = false;
221    private static final boolean DEBUG_APP_DIR_OBSERVER = false;
222    private static final boolean DEBUG_VERIFY = false;
223    private static final boolean DEBUG_DEXOPT = false;
224
225    private static final int RADIO_UID = Process.PHONE_UID;
226    private static final int LOG_UID = Process.LOG_UID;
227    private static final int NFC_UID = Process.NFC_UID;
228    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
229    private static final int SHELL_UID = Process.SHELL_UID;
230
231    // Cap the size of permission trees that 3rd party apps can define
232    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
233
234    private static final int REMOVE_EVENTS =
235        FileObserver.CLOSE_WRITE | FileObserver.DELETE | FileObserver.MOVED_FROM;
236    private static final int ADD_EVENTS =
237        FileObserver.CLOSE_WRITE /*| FileObserver.CREATE*/ | FileObserver.MOVED_TO;
238
239    private static final int OBSERVER_EVENTS = REMOVE_EVENTS | ADD_EVENTS;
240    // Suffix used during package installation when copying/moving
241    // package apks to install directory.
242    private static final String INSTALL_PACKAGE_SUFFIX = "-";
243
244    static final int SCAN_MONITOR = 1<<0;
245    static final int SCAN_NO_DEX = 1<<1;
246    static final int SCAN_FORCE_DEX = 1<<2;
247    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
248    static final int SCAN_NEW_INSTALL = 1<<4;
249    static final int SCAN_NO_PATHS = 1<<5;
250    static final int SCAN_UPDATE_TIME = 1<<6;
251    static final int SCAN_DEFER_DEX = 1<<7;
252    static final int SCAN_BOOTING = 1<<8;
253    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
254    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
255
256    static final int REMOVE_CHATTY = 1<<16;
257
258    /**
259     * Timeout (in milliseconds) after which the watchdog should declare that
260     * our handler thread is wedged.  The usual default for such things is one
261     * minute but we sometimes do very lengthy I/O operations on this thread,
262     * such as installing multi-gigabyte applications, so ours needs to be longer.
263     */
264    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
265
266    /**
267     * Whether verification is enabled by default.
268     */
269    private static final boolean DEFAULT_VERIFY_ENABLE = true;
270
271    /**
272     * The default maximum time to wait for the verification agent to return in
273     * milliseconds.
274     */
275    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
276
277    /**
278     * The default response for package verification timeout.
279     *
280     * This can be either PackageManager.VERIFICATION_ALLOW or
281     * PackageManager.VERIFICATION_REJECT.
282     */
283    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
284
285    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
286
287    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
288            DEFAULT_CONTAINER_PACKAGE,
289            "com.android.defcontainer.DefaultContainerService");
290
291    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
292
293    private static final String LIB_DIR_NAME = "lib";
294    private static final String LIB64_DIR_NAME = "lib64";
295
296    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
297
298    static final String mTempContainerPrefix = "smdl2tmp";
299
300    private static String sPreferredInstructionSet;
301
302    final ServiceThread mHandlerThread;
303
304    private static final String IDMAP_PREFIX = "/data/resource-cache/";
305    private static final String IDMAP_SUFFIX = "@idmap";
306
307    final PackageHandler mHandler;
308
309    final int mSdkVersion = Build.VERSION.SDK_INT;
310
311    final Context mContext;
312    final boolean mFactoryTest;
313    final boolean mOnlyCore;
314    final DisplayMetrics mMetrics;
315    final int mDefParseFlags;
316    final String[] mSeparateProcesses;
317
318    // This is where all application persistent data goes.
319    final File mAppDataDir;
320
321    // This is where all application persistent data goes for secondary users.
322    final File mUserAppDataDir;
323
324    /** The location for ASEC container files on internal storage. */
325    final String mAsecInternalPath;
326
327    // This is the object monitoring the framework dir.
328    final FileObserver mFrameworkInstallObserver;
329
330    // This is the object monitoring the system app dir.
331    final FileObserver mSystemInstallObserver;
332
333    // This is the object monitoring the privileged system app dir.
334    final FileObserver mPrivilegedInstallObserver;
335
336    // This is the object monitoring the vendor app dir.
337    final FileObserver mVendorInstallObserver;
338
339    // This is the object monitoring the vendor overlay package dir.
340    final FileObserver mVendorOverlayInstallObserver;
341
342    // This is the object monitoring the OEM app dir.
343    final FileObserver mOemInstallObserver;
344
345    // This is the object monitoring mAppInstallDir.
346    final FileObserver mAppInstallObserver;
347
348    // This is the object monitoring mDrmAppPrivateInstallDir.
349    final FileObserver mDrmAppInstallObserver;
350
351    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
352    // LOCK HELD.  Can be called with mInstallLock held.
353    final Installer mInstaller;
354
355    /** Directory where installed third-party apps stored */
356    final File mAppInstallDir;
357
358    /**
359     * Directory to which applications installed internally have native
360     * libraries copied.
361     */
362    private File mAppLibInstallDir;
363
364    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
365    // apps.
366    final File mDrmAppPrivateInstallDir;
367
368    /** Directory where third-party apps are staged before install */
369    final File mAppStagingDir;
370
371    // ----------------------------------------------------------------
372
373    // Lock for state used when installing and doing other long running
374    // operations.  Methods that must be called with this lock held have
375    // the suffix "LI".
376    final Object mInstallLock = new Object();
377
378    // These are the directories in the 3rd party applications installed dir
379    // that we have currently loaded packages from.  Keys are the application's
380    // installed zip file (absolute codePath), and values are Package.
381    final HashMap<String, PackageParser.Package> mAppDirs =
382            new HashMap<String, PackageParser.Package>();
383
384    // Information for the parser to write more useful error messages.
385    int mLastScanError;
386
387    // ----------------------------------------------------------------
388
389    // Keys are String (package name), values are Package.  This also serves
390    // as the lock for the global state.  Methods that must be called with
391    // this lock held have the prefix "LP".
392    final HashMap<String, PackageParser.Package> mPackages =
393            new HashMap<String, PackageParser.Package>();
394
395    // Tracks available target package names -> overlay package paths.
396    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
397        new HashMap<String, HashMap<String, PackageParser.Package>>();
398
399    final Settings mSettings;
400    boolean mRestoredSettings;
401
402    // System configuration read by SystemConfig.
403    final int[] mGlobalGids;
404    final SparseArray<HashSet<String>> mSystemPermissions;
405    final HashMap<String, FeatureInfo> mAvailableFeatures;
406
407    // If mac_permissions.xml was found for seinfo labeling.
408    boolean mFoundPolicyFile;
409
410    // If a recursive restorecon of /data/data/<pkg> is needed.
411    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
412
413    public static final class SharedLibraryEntry {
414        public final String path;
415        public final String apk;
416
417        SharedLibraryEntry(String _path, String _apk) {
418            path = _path;
419            apk = _apk;
420        }
421    }
422
423    // Currently known shared libraries.
424    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
425            new HashMap<String, SharedLibraryEntry>();
426
427    // All available activities, for your resolving pleasure.
428    final ActivityIntentResolver mActivities =
429            new ActivityIntentResolver();
430
431    // All available receivers, for your resolving pleasure.
432    final ActivityIntentResolver mReceivers =
433            new ActivityIntentResolver();
434
435    // All available services, for your resolving pleasure.
436    final ServiceIntentResolver mServices = new ServiceIntentResolver();
437
438    // All available providers, for your resolving pleasure.
439    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
440
441    // Mapping from provider base names (first directory in content URI codePath)
442    // to the provider information.
443    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
444            new HashMap<String, PackageParser.Provider>();
445
446    // Mapping from instrumentation class names to info about them.
447    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
448            new HashMap<ComponentName, PackageParser.Instrumentation>();
449
450    // Mapping from permission names to info about them.
451    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
452            new HashMap<String, PackageParser.PermissionGroup>();
453
454    // Packages whose data we have transfered into another package, thus
455    // should no longer exist.
456    final HashSet<String> mTransferedPackages = new HashSet<String>();
457
458    // Broadcast actions that are only available to the system.
459    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
460
461    /** List of packages waiting for verification. */
462    final SparseArray<PackageVerificationState> mPendingVerification
463            = new SparseArray<PackageVerificationState>();
464
465    final PackageInstallerService mInstallerService;
466
467    HashSet<PackageParser.Package> mDeferredDexOpt = null;
468
469    // Cache of users who need badging.
470    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
471
472    /** Token for keys in mPendingVerification. */
473    private int mPendingVerificationToken = 0;
474
475    boolean mSystemReady;
476    boolean mSafeMode;
477    boolean mHasSystemUidErrors;
478
479    ApplicationInfo mAndroidApplication;
480    final ActivityInfo mResolveActivity = new ActivityInfo();
481    final ResolveInfo mResolveInfo = new ResolveInfo();
482    ComponentName mResolveComponentName;
483    PackageParser.Package mPlatformPackage;
484    ComponentName mCustomResolverComponentName;
485
486    boolean mResolverReplaced = false;
487
488    // Set of pending broadcasts for aggregating enable/disable of components.
489    static class PendingPackageBroadcasts {
490        // for each user id, a map of <package name -> components within that package>
491        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
492
493        public PendingPackageBroadcasts() {
494            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
495        }
496
497        public ArrayList<String> get(int userId, String packageName) {
498            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
499            return packages.get(packageName);
500        }
501
502        public void put(int userId, String packageName, ArrayList<String> components) {
503            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
504            packages.put(packageName, components);
505        }
506
507        public void remove(int userId, String packageName) {
508            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
509            if (packages != null) {
510                packages.remove(packageName);
511            }
512        }
513
514        public void remove(int userId) {
515            mUidMap.remove(userId);
516        }
517
518        public int userIdCount() {
519            return mUidMap.size();
520        }
521
522        public int userIdAt(int n) {
523            return mUidMap.keyAt(n);
524        }
525
526        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
527            return mUidMap.get(userId);
528        }
529
530        public int size() {
531            // total number of pending broadcast entries across all userIds
532            int num = 0;
533            for (int i = 0; i< mUidMap.size(); i++) {
534                num += mUidMap.valueAt(i).size();
535            }
536            return num;
537        }
538
539        public void clear() {
540            mUidMap.clear();
541        }
542
543        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
544            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
545            if (map == null) {
546                map = new HashMap<String, ArrayList<String>>();
547                mUidMap.put(userId, map);
548            }
549            return map;
550        }
551    }
552    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
553
554    // Service Connection to remote media container service to copy
555    // package uri's from external media onto secure containers
556    // or internal storage.
557    private IMediaContainerService mContainerService = null;
558
559    static final int SEND_PENDING_BROADCAST = 1;
560    static final int MCS_BOUND = 3;
561    static final int END_COPY = 4;
562    static final int INIT_COPY = 5;
563    static final int MCS_UNBIND = 6;
564    static final int START_CLEANING_PACKAGE = 7;
565    static final int FIND_INSTALL_LOC = 8;
566    static final int POST_INSTALL = 9;
567    static final int MCS_RECONNECT = 10;
568    static final int MCS_GIVE_UP = 11;
569    static final int UPDATED_MEDIA_STATUS = 12;
570    static final int WRITE_SETTINGS = 13;
571    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
572    static final int PACKAGE_VERIFIED = 15;
573    static final int CHECK_PENDING_VERIFICATION = 16;
574
575    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
576
577    // Delay time in millisecs
578    static final int BROADCAST_DELAY = 10 * 1000;
579
580    static UserManagerService sUserManager;
581
582    // Stores a list of users whose package restrictions file needs to be updated
583    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
584
585    final private DefaultContainerConnection mDefContainerConn =
586            new DefaultContainerConnection();
587    class DefaultContainerConnection implements ServiceConnection {
588        public void onServiceConnected(ComponentName name, IBinder service) {
589            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
590            IMediaContainerService imcs =
591                IMediaContainerService.Stub.asInterface(service);
592            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
593        }
594
595        public void onServiceDisconnected(ComponentName name) {
596            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
597        }
598    };
599
600    // Recordkeeping of restore-after-install operations that are currently in flight
601    // between the Package Manager and the Backup Manager
602    class PostInstallData {
603        public InstallArgs args;
604        public PackageInstalledInfo res;
605
606        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
607            args = _a;
608            res = _r;
609        }
610    };
611    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
612    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
613
614    private final String mRequiredVerifierPackage;
615
616    private final PackageUsage mPackageUsage = new PackageUsage();
617
618    private class PackageUsage {
619        private static final int WRITE_INTERVAL
620            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
621
622        private final Object mFileLock = new Object();
623        private final AtomicLong mLastWritten = new AtomicLong(0);
624        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
625
626        private boolean mIsHistoricalPackageUsageAvailable = true;
627
628        boolean isHistoricalPackageUsageAvailable() {
629            return mIsHistoricalPackageUsageAvailable;
630        }
631
632        void write(boolean force) {
633            if (force) {
634                writeInternal();
635                return;
636            }
637            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
638                && !DEBUG_DEXOPT) {
639                return;
640            }
641            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
642                new Thread("PackageUsage_DiskWriter") {
643                    @Override
644                    public void run() {
645                        try {
646                            writeInternal();
647                        } finally {
648                            mBackgroundWriteRunning.set(false);
649                        }
650                    }
651                }.start();
652            }
653        }
654
655        private void writeInternal() {
656            synchronized (mPackages) {
657                synchronized (mFileLock) {
658                    AtomicFile file = getFile();
659                    FileOutputStream f = null;
660                    try {
661                        f = file.startWrite();
662                        BufferedOutputStream out = new BufferedOutputStream(f);
663                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
664                        StringBuilder sb = new StringBuilder();
665                        for (PackageParser.Package pkg : mPackages.values()) {
666                            if (pkg.mLastPackageUsageTimeInMills == 0) {
667                                continue;
668                            }
669                            sb.setLength(0);
670                            sb.append(pkg.packageName);
671                            sb.append(' ');
672                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
673                            sb.append('\n');
674                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
675                        }
676                        out.flush();
677                        file.finishWrite(f);
678                    } catch (IOException e) {
679                        if (f != null) {
680                            file.failWrite(f);
681                        }
682                        Log.e(TAG, "Failed to write package usage times", e);
683                    }
684                }
685            }
686            mLastWritten.set(SystemClock.elapsedRealtime());
687        }
688
689        void readLP() {
690            synchronized (mFileLock) {
691                AtomicFile file = getFile();
692                BufferedInputStream in = null;
693                try {
694                    in = new BufferedInputStream(file.openRead());
695                    StringBuffer sb = new StringBuffer();
696                    while (true) {
697                        String packageName = readToken(in, sb, ' ');
698                        if (packageName == null) {
699                            break;
700                        }
701                        String timeInMillisString = readToken(in, sb, '\n');
702                        if (timeInMillisString == null) {
703                            throw new IOException("Failed to find last usage time for package "
704                                                  + packageName);
705                        }
706                        PackageParser.Package pkg = mPackages.get(packageName);
707                        if (pkg == null) {
708                            continue;
709                        }
710                        long timeInMillis;
711                        try {
712                            timeInMillis = Long.parseLong(timeInMillisString.toString());
713                        } catch (NumberFormatException e) {
714                            throw new IOException("Failed to parse " + timeInMillisString
715                                                  + " as a long.", e);
716                        }
717                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
718                    }
719                } catch (FileNotFoundException expected) {
720                    mIsHistoricalPackageUsageAvailable = false;
721                } catch (IOException e) {
722                    Log.w(TAG, "Failed to read package usage times", e);
723                } finally {
724                    IoUtils.closeQuietly(in);
725                }
726            }
727            mLastWritten.set(SystemClock.elapsedRealtime());
728        }
729
730        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
731                throws IOException {
732            sb.setLength(0);
733            while (true) {
734                int ch = in.read();
735                if (ch == -1) {
736                    if (sb.length() == 0) {
737                        return null;
738                    }
739                    throw new IOException("Unexpected EOF");
740                }
741                if (ch == endOfToken) {
742                    return sb.toString();
743                }
744                sb.append((char)ch);
745            }
746        }
747
748        private AtomicFile getFile() {
749            File dataDir = Environment.getDataDirectory();
750            File systemDir = new File(dataDir, "system");
751            File fname = new File(systemDir, "package-usage.list");
752            return new AtomicFile(fname);
753        }
754    }
755
756    class PackageHandler extends Handler {
757        private boolean mBound = false;
758        final ArrayList<HandlerParams> mPendingInstalls =
759            new ArrayList<HandlerParams>();
760
761        private boolean connectToService() {
762            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
763                    " DefaultContainerService");
764            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
765            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
766            if (mContext.bindServiceAsUser(service, mDefContainerConn,
767                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
768                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
769                mBound = true;
770                return true;
771            }
772            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
773            return false;
774        }
775
776        private void disconnectService() {
777            mContainerService = null;
778            mBound = false;
779            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
780            mContext.unbindService(mDefContainerConn);
781            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
782        }
783
784        PackageHandler(Looper looper) {
785            super(looper);
786        }
787
788        public void handleMessage(Message msg) {
789            try {
790                doHandleMessage(msg);
791            } finally {
792                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
793            }
794        }
795
796        void doHandleMessage(Message msg) {
797            switch (msg.what) {
798                case INIT_COPY: {
799                    HandlerParams params = (HandlerParams) msg.obj;
800                    int idx = mPendingInstalls.size();
801                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
802                    // If a bind was already initiated we dont really
803                    // need to do anything. The pending install
804                    // will be processed later on.
805                    if (!mBound) {
806                        // If this is the only one pending we might
807                        // have to bind to the service again.
808                        if (!connectToService()) {
809                            Slog.e(TAG, "Failed to bind to media container service");
810                            params.serviceError();
811                            return;
812                        } else {
813                            // Once we bind to the service, the first
814                            // pending request will be processed.
815                            mPendingInstalls.add(idx, params);
816                        }
817                    } else {
818                        mPendingInstalls.add(idx, params);
819                        // Already bound to the service. Just make
820                        // sure we trigger off processing the first request.
821                        if (idx == 0) {
822                            mHandler.sendEmptyMessage(MCS_BOUND);
823                        }
824                    }
825                    break;
826                }
827                case MCS_BOUND: {
828                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
829                    if (msg.obj != null) {
830                        mContainerService = (IMediaContainerService) msg.obj;
831                    }
832                    if (mContainerService == null) {
833                        // Something seriously wrong. Bail out
834                        Slog.e(TAG, "Cannot bind to media container service");
835                        for (HandlerParams params : mPendingInstalls) {
836                            // Indicate service bind error
837                            params.serviceError();
838                        }
839                        mPendingInstalls.clear();
840                    } else if (mPendingInstalls.size() > 0) {
841                        HandlerParams params = mPendingInstalls.get(0);
842                        if (params != null) {
843                            if (params.startCopy()) {
844                                // We are done...  look for more work or to
845                                // go idle.
846                                if (DEBUG_SD_INSTALL) Log.i(TAG,
847                                        "Checking for more work or unbind...");
848                                // Delete pending install
849                                if (mPendingInstalls.size() > 0) {
850                                    mPendingInstalls.remove(0);
851                                }
852                                if (mPendingInstalls.size() == 0) {
853                                    if (mBound) {
854                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
855                                                "Posting delayed MCS_UNBIND");
856                                        removeMessages(MCS_UNBIND);
857                                        Message ubmsg = obtainMessage(MCS_UNBIND);
858                                        // Unbind after a little delay, to avoid
859                                        // continual thrashing.
860                                        sendMessageDelayed(ubmsg, 10000);
861                                    }
862                                } else {
863                                    // There are more pending requests in queue.
864                                    // Just post MCS_BOUND message to trigger processing
865                                    // of next pending install.
866                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
867                                            "Posting MCS_BOUND for next work");
868                                    mHandler.sendEmptyMessage(MCS_BOUND);
869                                }
870                            }
871                        }
872                    } else {
873                        // Should never happen ideally.
874                        Slog.w(TAG, "Empty queue");
875                    }
876                    break;
877                }
878                case MCS_RECONNECT: {
879                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
880                    if (mPendingInstalls.size() > 0) {
881                        if (mBound) {
882                            disconnectService();
883                        }
884                        if (!connectToService()) {
885                            Slog.e(TAG, "Failed to bind to media container service");
886                            for (HandlerParams params : mPendingInstalls) {
887                                // Indicate service bind error
888                                params.serviceError();
889                            }
890                            mPendingInstalls.clear();
891                        }
892                    }
893                    break;
894                }
895                case MCS_UNBIND: {
896                    // If there is no actual work left, then time to unbind.
897                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
898
899                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
900                        if (mBound) {
901                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
902
903                            disconnectService();
904                        }
905                    } else if (mPendingInstalls.size() > 0) {
906                        // There are more pending requests in queue.
907                        // Just post MCS_BOUND message to trigger processing
908                        // of next pending install.
909                        mHandler.sendEmptyMessage(MCS_BOUND);
910                    }
911
912                    break;
913                }
914                case MCS_GIVE_UP: {
915                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
916                    mPendingInstalls.remove(0);
917                    break;
918                }
919                case SEND_PENDING_BROADCAST: {
920                    String packages[];
921                    ArrayList<String> components[];
922                    int size = 0;
923                    int uids[];
924                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
925                    synchronized (mPackages) {
926                        if (mPendingBroadcasts == null) {
927                            return;
928                        }
929                        size = mPendingBroadcasts.size();
930                        if (size <= 0) {
931                            // Nothing to be done. Just return
932                            return;
933                        }
934                        packages = new String[size];
935                        components = new ArrayList[size];
936                        uids = new int[size];
937                        int i = 0;  // filling out the above arrays
938
939                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
940                            int packageUserId = mPendingBroadcasts.userIdAt(n);
941                            Iterator<Map.Entry<String, ArrayList<String>>> it
942                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
943                                            .entrySet().iterator();
944                            while (it.hasNext() && i < size) {
945                                Map.Entry<String, ArrayList<String>> ent = it.next();
946                                packages[i] = ent.getKey();
947                                components[i] = ent.getValue();
948                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
949                                uids[i] = (ps != null)
950                                        ? UserHandle.getUid(packageUserId, ps.appId)
951                                        : -1;
952                                i++;
953                            }
954                        }
955                        size = i;
956                        mPendingBroadcasts.clear();
957                    }
958                    // Send broadcasts
959                    for (int i = 0; i < size; i++) {
960                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
961                    }
962                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
963                    break;
964                }
965                case START_CLEANING_PACKAGE: {
966                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
967                    final String packageName = (String)msg.obj;
968                    final int userId = msg.arg1;
969                    final boolean andCode = msg.arg2 != 0;
970                    synchronized (mPackages) {
971                        if (userId == UserHandle.USER_ALL) {
972                            int[] users = sUserManager.getUserIds();
973                            for (int user : users) {
974                                mSettings.addPackageToCleanLPw(
975                                        new PackageCleanItem(user, packageName, andCode));
976                            }
977                        } else {
978                            mSettings.addPackageToCleanLPw(
979                                    new PackageCleanItem(userId, packageName, andCode));
980                        }
981                    }
982                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
983                    startCleaningPackages();
984                } break;
985                case POST_INSTALL: {
986                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
987                    PostInstallData data = mRunningInstalls.get(msg.arg1);
988                    mRunningInstalls.delete(msg.arg1);
989                    boolean deleteOld = false;
990
991                    if (data != null) {
992                        InstallArgs args = data.args;
993                        PackageInstalledInfo res = data.res;
994
995                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
996                            res.removedInfo.sendBroadcast(false, true, false);
997                            Bundle extras = new Bundle(1);
998                            extras.putInt(Intent.EXTRA_UID, res.uid);
999                            // Determine the set of users who are adding this
1000                            // package for the first time vs. those who are seeing
1001                            // an update.
1002                            int[] firstUsers;
1003                            int[] updateUsers = new int[0];
1004                            if (res.origUsers == null || res.origUsers.length == 0) {
1005                                firstUsers = res.newUsers;
1006                            } else {
1007                                firstUsers = new int[0];
1008                                for (int i=0; i<res.newUsers.length; i++) {
1009                                    int user = res.newUsers[i];
1010                                    boolean isNew = true;
1011                                    for (int j=0; j<res.origUsers.length; j++) {
1012                                        if (res.origUsers[j] == user) {
1013                                            isNew = false;
1014                                            break;
1015                                        }
1016                                    }
1017                                    if (isNew) {
1018                                        int[] newFirst = new int[firstUsers.length+1];
1019                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1020                                                firstUsers.length);
1021                                        newFirst[firstUsers.length] = user;
1022                                        firstUsers = newFirst;
1023                                    } else {
1024                                        int[] newUpdate = new int[updateUsers.length+1];
1025                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1026                                                updateUsers.length);
1027                                        newUpdate[updateUsers.length] = user;
1028                                        updateUsers = newUpdate;
1029                                    }
1030                                }
1031                            }
1032                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1033                                    res.pkg.applicationInfo.packageName,
1034                                    extras, null, null, firstUsers);
1035                            final boolean update = res.removedInfo.removedPackage != null;
1036                            if (update) {
1037                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1038                            }
1039                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1040                                    res.pkg.applicationInfo.packageName,
1041                                    extras, null, null, updateUsers);
1042                            if (update) {
1043                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1044                                        res.pkg.applicationInfo.packageName,
1045                                        extras, null, null, updateUsers);
1046                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1047                                        null, null,
1048                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1049
1050                                // treat asec-hosted packages like removable media on upgrade
1051                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1052                                    if (DEBUG_INSTALL) {
1053                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1054                                                + " is ASEC-hosted -> AVAILABLE");
1055                                    }
1056                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1057                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1058                                    pkgList.add(res.pkg.applicationInfo.packageName);
1059                                    sendResourcesChangedBroadcast(true, true,
1060                                            pkgList,uidArray, null);
1061                                }
1062                            }
1063                            if (res.removedInfo.args != null) {
1064                                // Remove the replaced package's older resources safely now
1065                                deleteOld = true;
1066                            }
1067
1068                            // Log current value of "unknown sources" setting
1069                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1070                                getUnknownSourcesSettings());
1071                        }
1072                        // Force a gc to clear up things
1073                        Runtime.getRuntime().gc();
1074                        // We delete after a gc for applications  on sdcard.
1075                        if (deleteOld) {
1076                            synchronized (mInstallLock) {
1077                                res.removedInfo.args.doPostDeleteLI(true);
1078                            }
1079                        }
1080                        if (args.observer != null) {
1081                            try {
1082                                args.observer.packageInstalled(res.name, res.returnCode);
1083                            } catch (RemoteException e) {
1084                                Slog.i(TAG, "Observer no longer exists.");
1085                            }
1086                        }
1087                        if (args.observer2 != null) {
1088                            try {
1089                                Bundle extras = extrasForInstallResult(res);
1090                                args.observer2.packageInstalled(res.name, extras, res.returnCode);
1091                            } catch (RemoteException e) {
1092                                Slog.i(TAG, "Observer no longer exists.");
1093                            }
1094                        }
1095                    } else {
1096                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1097                    }
1098                } break;
1099                case UPDATED_MEDIA_STATUS: {
1100                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1101                    boolean reportStatus = msg.arg1 == 1;
1102                    boolean doGc = msg.arg2 == 1;
1103                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1104                    if (doGc) {
1105                        // Force a gc to clear up stale containers.
1106                        Runtime.getRuntime().gc();
1107                    }
1108                    if (msg.obj != null) {
1109                        @SuppressWarnings("unchecked")
1110                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1111                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1112                        // Unload containers
1113                        unloadAllContainers(args);
1114                    }
1115                    if (reportStatus) {
1116                        try {
1117                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1118                            PackageHelper.getMountService().finishMediaUpdate();
1119                        } catch (RemoteException e) {
1120                            Log.e(TAG, "MountService not running?");
1121                        }
1122                    }
1123                } break;
1124                case WRITE_SETTINGS: {
1125                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1126                    synchronized (mPackages) {
1127                        removeMessages(WRITE_SETTINGS);
1128                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1129                        mSettings.writeLPr();
1130                        mDirtyUsers.clear();
1131                    }
1132                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1133                } break;
1134                case WRITE_PACKAGE_RESTRICTIONS: {
1135                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1136                    synchronized (mPackages) {
1137                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1138                        for (int userId : mDirtyUsers) {
1139                            mSettings.writePackageRestrictionsLPr(userId);
1140                        }
1141                        mDirtyUsers.clear();
1142                    }
1143                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1144                } break;
1145                case CHECK_PENDING_VERIFICATION: {
1146                    final int verificationId = msg.arg1;
1147                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1148
1149                    if ((state != null) && !state.timeoutExtended()) {
1150                        final InstallArgs args = state.getInstallArgs();
1151                        final Uri fromUri = Uri.fromFile(args.fromFile);
1152
1153                        Slog.i(TAG, "Verification timed out for " + fromUri);
1154                        mPendingVerification.remove(verificationId);
1155
1156                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1157
1158                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1159                            Slog.i(TAG, "Continuing with installation of " + fromUri);
1160                            state.setVerifierResponse(Binder.getCallingUid(),
1161                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1162                            broadcastPackageVerified(verificationId, fromUri,
1163                                    PackageManager.VERIFICATION_ALLOW,
1164                                    state.getInstallArgs().getUser());
1165                            try {
1166                                ret = args.copyApk(mContainerService, true);
1167                            } catch (RemoteException e) {
1168                                Slog.e(TAG, "Could not contact the ContainerService");
1169                            }
1170                        } else {
1171                            broadcastPackageVerified(verificationId, fromUri,
1172                                    PackageManager.VERIFICATION_REJECT,
1173                                    state.getInstallArgs().getUser());
1174                        }
1175
1176                        processPendingInstall(args, ret);
1177                        mHandler.sendEmptyMessage(MCS_UNBIND);
1178                    }
1179                    break;
1180                }
1181                case PACKAGE_VERIFIED: {
1182                    final int verificationId = msg.arg1;
1183
1184                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1185                    if (state == null) {
1186                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1187                        break;
1188                    }
1189
1190                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1191
1192                    state.setVerifierResponse(response.callerUid, response.code);
1193
1194                    if (state.isVerificationComplete()) {
1195                        mPendingVerification.remove(verificationId);
1196
1197                        final InstallArgs args = state.getInstallArgs();
1198                        final Uri fromUri = Uri.fromFile(args.fromFile);
1199
1200                        int ret;
1201                        if (state.isInstallAllowed()) {
1202                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1203                            broadcastPackageVerified(verificationId, fromUri,
1204                                    response.code, state.getInstallArgs().getUser());
1205                            try {
1206                                ret = args.copyApk(mContainerService, true);
1207                            } catch (RemoteException e) {
1208                                Slog.e(TAG, "Could not contact the ContainerService");
1209                            }
1210                        } else {
1211                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1212                        }
1213
1214                        processPendingInstall(args, ret);
1215
1216                        mHandler.sendEmptyMessage(MCS_UNBIND);
1217                    }
1218
1219                    break;
1220                }
1221            }
1222        }
1223    }
1224
1225    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1226        Bundle extras = null;
1227        switch (res.returnCode) {
1228            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1229                extras = new Bundle();
1230                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1231                        res.origPermission);
1232                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1233                        res.origPackage);
1234                break;
1235            }
1236        }
1237        return extras;
1238    }
1239
1240    void scheduleWriteSettingsLocked() {
1241        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1242            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1243        }
1244    }
1245
1246    void scheduleWritePackageRestrictionsLocked(int userId) {
1247        if (!sUserManager.exists(userId)) return;
1248        mDirtyUsers.add(userId);
1249        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1250            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1251        }
1252    }
1253
1254    public static final PackageManagerService main(Context context, Installer installer,
1255            boolean factoryTest, boolean onlyCore) {
1256        PackageManagerService m = new PackageManagerService(context, installer,
1257                factoryTest, onlyCore);
1258        ServiceManager.addService("package", m);
1259        return m;
1260    }
1261
1262    static String[] splitString(String str, char sep) {
1263        int count = 1;
1264        int i = 0;
1265        while ((i=str.indexOf(sep, i)) >= 0) {
1266            count++;
1267            i++;
1268        }
1269
1270        String[] res = new String[count];
1271        i=0;
1272        count = 0;
1273        int lastI=0;
1274        while ((i=str.indexOf(sep, i)) >= 0) {
1275            res[count] = str.substring(lastI, i);
1276            count++;
1277            i++;
1278            lastI = i;
1279        }
1280        res[count] = str.substring(lastI, str.length());
1281        return res;
1282    }
1283
1284    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1285        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1286                Context.DISPLAY_SERVICE);
1287        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1288    }
1289
1290    public PackageManagerService(Context context, Installer installer,
1291            boolean factoryTest, boolean onlyCore) {
1292        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1293                SystemClock.uptimeMillis());
1294
1295        if (mSdkVersion <= 0) {
1296            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1297        }
1298
1299        mContext = context;
1300        mFactoryTest = factoryTest;
1301        mOnlyCore = onlyCore;
1302        mMetrics = new DisplayMetrics();
1303        mSettings = new Settings(context);
1304        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1305                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1306        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1307                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1308        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1309                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1310        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1311                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1312        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1313                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1314        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1315                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1316
1317        String separateProcesses = SystemProperties.get("debug.separate_processes");
1318        if (separateProcesses != null && separateProcesses.length() > 0) {
1319            if ("*".equals(separateProcesses)) {
1320                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1321                mSeparateProcesses = null;
1322                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1323            } else {
1324                mDefParseFlags = 0;
1325                mSeparateProcesses = separateProcesses.split(",");
1326                Slog.w(TAG, "Running with debug.separate_processes: "
1327                        + separateProcesses);
1328            }
1329        } else {
1330            mDefParseFlags = 0;
1331            mSeparateProcesses = null;
1332        }
1333
1334        mInstaller = installer;
1335
1336        getDefaultDisplayMetrics(context, mMetrics);
1337
1338        SystemConfig systemConfig = SystemConfig.getInstance();
1339        mGlobalGids = systemConfig.getGlobalGids();
1340        mSystemPermissions = systemConfig.getSystemPermissions();
1341        mAvailableFeatures = systemConfig.getAvailableFeatures();
1342
1343        synchronized (mInstallLock) {
1344        // writer
1345        synchronized (mPackages) {
1346            mHandlerThread = new ServiceThread(TAG,
1347                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1348            mHandlerThread.start();
1349            mHandler = new PackageHandler(mHandlerThread.getLooper());
1350            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1351
1352            File dataDir = Environment.getDataDirectory();
1353            mAppDataDir = new File(dataDir, "data");
1354            mAppInstallDir = new File(dataDir, "app");
1355            mAppLibInstallDir = new File(dataDir, "app-lib");
1356            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1357            mUserAppDataDir = new File(dataDir, "user");
1358            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1359            mAppStagingDir = new File(dataDir, "app-staging");
1360
1361            sUserManager = new UserManagerService(context, this,
1362                    mInstallLock, mPackages);
1363
1364            // Propagate permission configuration in to package manager.
1365            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1366                    = systemConfig.getPermissions();
1367            for (int i=0; i<permConfig.size(); i++) {
1368                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1369                BasePermission bp = mSettings.mPermissions.get(perm.name);
1370                if (bp == null) {
1371                    bp = new BasePermission(perm.name, null, BasePermission.TYPE_BUILTIN);
1372                    mSettings.mPermissions.put(perm.name, bp);
1373                }
1374                if (perm.gids != null) {
1375                    bp.gids = appendInts(bp.gids, perm.gids);
1376                }
1377            }
1378
1379            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1380            for (int i=0; i<libConfig.size(); i++) {
1381                mSharedLibraries.put(libConfig.keyAt(i),
1382                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1383            }
1384
1385            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1386
1387            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1388                    mSdkVersion, mOnlyCore);
1389
1390            String customResolverActivity = Resources.getSystem().getString(
1391                    R.string.config_customResolverActivity);
1392            if (TextUtils.isEmpty(customResolverActivity)) {
1393                customResolverActivity = null;
1394            } else {
1395                mCustomResolverComponentName = ComponentName.unflattenFromString(
1396                        customResolverActivity);
1397            }
1398
1399            long startTime = SystemClock.uptimeMillis();
1400
1401            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1402                    startTime);
1403
1404            // Set flag to monitor and not change apk file paths when
1405            // scanning install directories.
1406            int scanMode = SCAN_MONITOR | SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1407
1408            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1409
1410            /**
1411             * Add everything in the in the boot class path to the
1412             * list of process files because dexopt will have been run
1413             * if necessary during zygote startup.
1414             */
1415            String bootClassPath = System.getProperty("java.boot.class.path");
1416            if (bootClassPath != null) {
1417                String[] paths = splitString(bootClassPath, ':');
1418                for (int i=0; i<paths.length; i++) {
1419                    alreadyDexOpted.add(paths[i]);
1420                }
1421            } else {
1422                Slog.w(TAG, "No BOOTCLASSPATH found!");
1423            }
1424
1425            boolean didDexOptLibraryOrTool = false;
1426
1427            final List<String> instructionSets = getAllInstructionSets();
1428
1429            /**
1430             * Ensure all external libraries have had dexopt run on them.
1431             */
1432            if (mSharedLibraries.size() > 0) {
1433                // NOTE: For now, we're compiling these system "shared libraries"
1434                // (and framework jars) into all available architectures. It's possible
1435                // to compile them only when we come across an app that uses them (there's
1436                // already logic for that in scanPackageLI) but that adds some complexity.
1437                for (String instructionSet : instructionSets) {
1438                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1439                        final String lib = libEntry.path;
1440                        if (lib == null) {
1441                            continue;
1442                        }
1443
1444                        try {
1445                            if (DexFile.isDexOptNeededInternal(lib, null, instructionSet, false)) {
1446                                alreadyDexOpted.add(lib);
1447
1448                                // The list of "shared libraries" we have at this point is
1449                                mInstaller.dexopt(lib, Process.SYSTEM_UID, true, instructionSet);
1450                                didDexOptLibraryOrTool = true;
1451                            }
1452                        } catch (FileNotFoundException e) {
1453                            Slog.w(TAG, "Library not found: " + lib);
1454                        } catch (IOException e) {
1455                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1456                                    + e.getMessage());
1457                        }
1458                    }
1459                }
1460            }
1461
1462            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1463
1464            // Gross hack for now: we know this file doesn't contain any
1465            // code, so don't dexopt it to avoid the resulting log spew.
1466            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1467
1468            // Gross hack for now: we know this file is only part of
1469            // the boot class path for art, so don't dexopt it to
1470            // avoid the resulting log spew.
1471            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1472
1473            /**
1474             * And there are a number of commands implemented in Java, which
1475             * we currently need to do the dexopt on so that they can be
1476             * run from a non-root shell.
1477             */
1478            String[] frameworkFiles = frameworkDir.list();
1479            if (frameworkFiles != null) {
1480                // TODO: We could compile these only for the most preferred ABI. We should
1481                // first double check that the dex files for these commands are not referenced
1482                // by other system apps.
1483                for (String instructionSet : instructionSets) {
1484                    for (int i=0; i<frameworkFiles.length; i++) {
1485                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1486                        String path = libPath.getPath();
1487                        // Skip the file if we already did it.
1488                        if (alreadyDexOpted.contains(path)) {
1489                            continue;
1490                        }
1491                        // Skip the file if it is not a type we want to dexopt.
1492                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1493                            continue;
1494                        }
1495                        try {
1496                            if (DexFile.isDexOptNeededInternal(path, null, instructionSet, false)) {
1497                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, instructionSet);
1498                                didDexOptLibraryOrTool = true;
1499                            }
1500                        } catch (FileNotFoundException e) {
1501                            Slog.w(TAG, "Jar not found: " + path);
1502                        } catch (IOException e) {
1503                            Slog.w(TAG, "Exception reading jar: " + path, e);
1504                        }
1505                    }
1506                }
1507            }
1508
1509            if (didDexOptLibraryOrTool) {
1510                // If we dexopted a library or tool, then something on the system has
1511                // changed. Consider this significant, and wipe away all other
1512                // existing dexopt files to ensure we don't leave any dangling around.
1513                //
1514                // TODO: This should be revisited because it isn't as good an indicator
1515                // as it used to be. It used to include the boot classpath but at some point
1516                // DexFile.isDexOptNeeded started returning false for the boot
1517                // class path files in all cases. It is very possible in a
1518                // small maintenance release update that the library and tool
1519                // jars may be unchanged but APK could be removed resulting in
1520                // unused dalvik-cache files.
1521                for (String instructionSet : instructionSets) {
1522                    mInstaller.pruneDexCache(instructionSet);
1523                }
1524
1525                // Additionally, delete all dex files from the root directory
1526                // since there shouldn't be any there anyway, unless we're upgrading
1527                // from an older OS version or a build that contained the "old" style
1528                // flat scheme.
1529                mInstaller.pruneDexCache(".");
1530            }
1531
1532            // Collect vendor overlay packages.
1533            // (Do this before scanning any apps.)
1534            // For security and version matching reason, only consider
1535            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1536            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1537            mVendorOverlayInstallObserver = new AppDirObserver(
1538                    vendorOverlayDir.getPath(), OBSERVER_EVENTS, true, false);
1539            mVendorOverlayInstallObserver.startWatching();
1540            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1541                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode | SCAN_TRUSTED_OVERLAY, 0);
1542
1543            // Find base frameworks (resource packages without code).
1544            mFrameworkInstallObserver = new AppDirObserver(
1545                    frameworkDir.getPath(), OBSERVER_EVENTS, true, false);
1546            mFrameworkInstallObserver.startWatching();
1547            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1548                    | PackageParser.PARSE_IS_SYSTEM_DIR
1549                    | PackageParser.PARSE_IS_PRIVILEGED,
1550                    scanMode | SCAN_NO_DEX, 0);
1551
1552            // Collected privileged system packages.
1553            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1554            mPrivilegedInstallObserver = new AppDirObserver(
1555                    privilegedAppDir.getPath(), OBSERVER_EVENTS, true, true);
1556            mPrivilegedInstallObserver.startWatching();
1557            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1558                    | PackageParser.PARSE_IS_SYSTEM_DIR
1559                    | PackageParser.PARSE_IS_PRIVILEGED, scanMode, 0);
1560
1561            // Collect ordinary system packages.
1562            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1563            mSystemInstallObserver = new AppDirObserver(
1564                    systemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1565            mSystemInstallObserver.startWatching();
1566            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1567                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1568
1569            // Collect all vendor packages.
1570            File vendorAppDir = new File("/vendor/app");
1571            try {
1572                vendorAppDir = vendorAppDir.getCanonicalFile();
1573            } catch (IOException e) {
1574                // failed to look up canonical path, continue with original one
1575            }
1576            mVendorInstallObserver = new AppDirObserver(
1577                    vendorAppDir.getPath(), OBSERVER_EVENTS, true, false);
1578            mVendorInstallObserver.startWatching();
1579            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1580                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1581
1582            // Collect all OEM packages.
1583            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1584            mOemInstallObserver = new AppDirObserver(
1585                    oemAppDir.getPath(), OBSERVER_EVENTS, true, false);
1586            mOemInstallObserver.startWatching();
1587            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1588                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanMode, 0);
1589
1590            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1591            mInstaller.moveFiles();
1592
1593            // Prune any system packages that no longer exist.
1594            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1595            if (!mOnlyCore) {
1596                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1597                while (psit.hasNext()) {
1598                    PackageSetting ps = psit.next();
1599
1600                    /*
1601                     * If this is not a system app, it can't be a
1602                     * disable system app.
1603                     */
1604                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1605                        continue;
1606                    }
1607
1608                    /*
1609                     * If the package is scanned, it's not erased.
1610                     */
1611                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1612                    if (scannedPkg != null) {
1613                        /*
1614                         * If the system app is both scanned and in the
1615                         * disabled packages list, then it must have been
1616                         * added via OTA. Remove it from the currently
1617                         * scanned package so the previously user-installed
1618                         * application can be scanned.
1619                         */
1620                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1621                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1622                                    + "; removing system app");
1623                            removePackageLI(ps, true);
1624                        }
1625
1626                        continue;
1627                    }
1628
1629                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1630                        psit.remove();
1631                        String msg = "System package " + ps.name
1632                                + " no longer exists; wiping its data";
1633                        reportSettingsProblem(Log.WARN, msg);
1634                        removeDataDirsLI(ps.name);
1635                    } else {
1636                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1637                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1638                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1639                        }
1640                    }
1641                }
1642            }
1643
1644            //look for any incomplete package installations
1645            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1646            //clean up list
1647            for(int i = 0; i < deletePkgsList.size(); i++) {
1648                //clean up here
1649                cleanupInstallFailedPackage(deletePkgsList.get(i));
1650            }
1651            //delete tmp files
1652            deleteTempPackageFiles();
1653
1654            // Remove any shared userIDs that have no associated packages
1655            mSettings.pruneSharedUsersLPw();
1656
1657            if (!mOnlyCore) {
1658                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1659                        SystemClock.uptimeMillis());
1660                mAppInstallObserver = new AppDirObserver(
1661                    mAppInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1662                mAppInstallObserver.startWatching();
1663                scanDirLI(mAppInstallDir, 0, scanMode, 0);
1664
1665                mDrmAppInstallObserver = new AppDirObserver(
1666                    mDrmAppPrivateInstallDir.getPath(), OBSERVER_EVENTS, false, false);
1667                mDrmAppInstallObserver.startWatching();
1668                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1669                        scanMode, 0);
1670
1671                /**
1672                 * Remove disable package settings for any updated system
1673                 * apps that were removed via an OTA. If they're not a
1674                 * previously-updated app, remove them completely.
1675                 * Otherwise, just revoke their system-level permissions.
1676                 */
1677                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1678                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1679                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1680
1681                    String msg;
1682                    if (deletedPkg == null) {
1683                        msg = "Updated system package " + deletedAppName
1684                                + " no longer exists; wiping its data";
1685                        removeDataDirsLI(deletedAppName);
1686                    } else {
1687                        msg = "Updated system app + " + deletedAppName
1688                                + " no longer present; removing system privileges for "
1689                                + deletedAppName;
1690
1691                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1692
1693                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1694                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1695                    }
1696                    reportSettingsProblem(Log.WARN, msg);
1697                }
1698            } else {
1699                mAppInstallObserver = null;
1700                mDrmAppInstallObserver = null;
1701            }
1702
1703            // Now that we know all of the shared libraries, update all clients to have
1704            // the correct library paths.
1705            updateAllSharedLibrariesLPw();
1706
1707            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1708                // NOTE: We ignore potential failures here during a system scan (like
1709                // the rest of the commands above) because there's precious little we
1710                // can do about it. A settings error is reported, though.
1711                adjustCpuAbisForSharedUserLPw(setting.packages, null,
1712                        false /* force dexopt */, false /* defer dexopt */);
1713            }
1714
1715            // Now that we know all the packages we are keeping,
1716            // read and update their last usage times.
1717            mPackageUsage.readLP();
1718
1719            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1720                    SystemClock.uptimeMillis());
1721            Slog.i(TAG, "Time to scan packages: "
1722                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1723                    + " seconds");
1724
1725            // If the platform SDK has changed since the last time we booted,
1726            // we need to re-grant app permission to catch any new ones that
1727            // appear.  This is really a hack, and means that apps can in some
1728            // cases get permissions that the user didn't initially explicitly
1729            // allow...  it would be nice to have some better way to handle
1730            // this situation.
1731            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1732                    != mSdkVersion;
1733            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1734                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1735                    + "; regranting permissions for internal storage");
1736            mSettings.mInternalSdkPlatform = mSdkVersion;
1737
1738            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1739                    | (regrantPermissions
1740                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1741                            : 0));
1742
1743            // If this is the first boot, and it is a normal boot, then
1744            // we need to initialize the default preferred apps.
1745            if (!mRestoredSettings && !onlyCore) {
1746                mSettings.readDefaultPreferredAppsLPw(this, 0);
1747            }
1748
1749            // All the changes are done during package scanning.
1750            mSettings.updateInternalDatabaseVersion();
1751
1752            // can downgrade to reader
1753            mSettings.writeLPr();
1754
1755            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1756                    SystemClock.uptimeMillis());
1757
1758
1759            mRequiredVerifierPackage = getRequiredVerifierLPr();
1760        } // synchronized (mPackages)
1761        } // synchronized (mInstallLock)
1762
1763        mInstallerService = new PackageInstallerService(context, this, mAppStagingDir);
1764
1765        // Now after opening every single application zip, make sure they
1766        // are all flushed.  Not really needed, but keeps things nice and
1767        // tidy.
1768        Runtime.getRuntime().gc();
1769    }
1770
1771    @Override
1772    public boolean isFirstBoot() {
1773        return !mRestoredSettings;
1774    }
1775
1776    @Override
1777    public boolean isOnlyCoreApps() {
1778        return mOnlyCore;
1779    }
1780
1781    private String getRequiredVerifierLPr() {
1782        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1783        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1784                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1785
1786        String requiredVerifier = null;
1787
1788        final int N = receivers.size();
1789        for (int i = 0; i < N; i++) {
1790            final ResolveInfo info = receivers.get(i);
1791
1792            if (info.activityInfo == null) {
1793                continue;
1794            }
1795
1796            final String packageName = info.activityInfo.packageName;
1797
1798            final PackageSetting ps = mSettings.mPackages.get(packageName);
1799            if (ps == null) {
1800                continue;
1801            }
1802
1803            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1804            if (!gp.grantedPermissions
1805                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1806                continue;
1807            }
1808
1809            if (requiredVerifier != null) {
1810                throw new RuntimeException("There can be only one required verifier");
1811            }
1812
1813            requiredVerifier = packageName;
1814        }
1815
1816        return requiredVerifier;
1817    }
1818
1819    @Override
1820    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1821            throws RemoteException {
1822        try {
1823            return super.onTransact(code, data, reply, flags);
1824        } catch (RuntimeException e) {
1825            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1826                Slog.wtf(TAG, "Package Manager Crash", e);
1827            }
1828            throw e;
1829        }
1830    }
1831
1832    void cleanupInstallFailedPackage(PackageSetting ps) {
1833        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1834        removeDataDirsLI(ps.name);
1835
1836        // TODO: try cleaning up codePath directory contents first, since it
1837        // might be a cluster
1838
1839        if (ps.codePath != null) {
1840            if (!ps.codePath.delete()) {
1841                Slog.w(TAG, "Unable to remove old code file: " + ps.codePath);
1842            }
1843        }
1844        if (ps.resourcePath != null) {
1845            if (!ps.resourcePath.delete() && !ps.resourcePath.equals(ps.codePath)) {
1846                Slog.w(TAG, "Unable to remove old code file: " + ps.resourcePath);
1847            }
1848        }
1849        mSettings.removePackageLPw(ps.name);
1850    }
1851
1852    static int[] appendInts(int[] cur, int[] add) {
1853        if (add == null) return cur;
1854        if (cur == null) return add;
1855        final int N = add.length;
1856        for (int i=0; i<N; i++) {
1857            cur = appendInt(cur, add[i]);
1858        }
1859        return cur;
1860    }
1861
1862    static int[] removeInts(int[] cur, int[] rem) {
1863        if (rem == null) return cur;
1864        if (cur == null) return cur;
1865        final int N = rem.length;
1866        for (int i=0; i<N; i++) {
1867            cur = removeInt(cur, rem[i]);
1868        }
1869        return cur;
1870    }
1871
1872    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1873        if (!sUserManager.exists(userId)) return null;
1874        final PackageSetting ps = (PackageSetting) p.mExtras;
1875        if (ps == null) {
1876            return null;
1877        }
1878        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1879        final PackageUserState state = ps.readUserState(userId);
1880        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1881                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1882                state, userId);
1883    }
1884
1885    @Override
1886    public boolean isPackageAvailable(String packageName, int userId) {
1887        if (!sUserManager.exists(userId)) return false;
1888        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "is package available");
1889        synchronized (mPackages) {
1890            PackageParser.Package p = mPackages.get(packageName);
1891            if (p != null) {
1892                final PackageSetting ps = (PackageSetting) p.mExtras;
1893                if (ps != null) {
1894                    final PackageUserState state = ps.readUserState(userId);
1895                    if (state != null) {
1896                        return PackageParser.isAvailable(state);
1897                    }
1898                }
1899            }
1900        }
1901        return false;
1902    }
1903
1904    @Override
1905    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1906        if (!sUserManager.exists(userId)) return null;
1907        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package info");
1908        // reader
1909        synchronized (mPackages) {
1910            PackageParser.Package p = mPackages.get(packageName);
1911            if (DEBUG_PACKAGE_INFO)
1912                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1913            if (p != null) {
1914                return generatePackageInfo(p, flags, userId);
1915            }
1916            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1917                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1918            }
1919        }
1920        return null;
1921    }
1922
1923    @Override
1924    public String[] currentToCanonicalPackageNames(String[] names) {
1925        String[] out = new String[names.length];
1926        // reader
1927        synchronized (mPackages) {
1928            for (int i=names.length-1; i>=0; i--) {
1929                PackageSetting ps = mSettings.mPackages.get(names[i]);
1930                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1931            }
1932        }
1933        return out;
1934    }
1935
1936    @Override
1937    public String[] canonicalToCurrentPackageNames(String[] names) {
1938        String[] out = new String[names.length];
1939        // reader
1940        synchronized (mPackages) {
1941            for (int i=names.length-1; i>=0; i--) {
1942                String cur = mSettings.mRenamedPackages.get(names[i]);
1943                out[i] = cur != null ? cur : names[i];
1944            }
1945        }
1946        return out;
1947    }
1948
1949    @Override
1950    public int getPackageUid(String packageName, int userId) {
1951        if (!sUserManager.exists(userId)) return -1;
1952        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get package uid");
1953        // reader
1954        synchronized (mPackages) {
1955            PackageParser.Package p = mPackages.get(packageName);
1956            if(p != null) {
1957                return UserHandle.getUid(userId, p.applicationInfo.uid);
1958            }
1959            PackageSetting ps = mSettings.mPackages.get(packageName);
1960            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1961                return -1;
1962            }
1963            p = ps.pkg;
1964            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1965        }
1966    }
1967
1968    @Override
1969    public int[] getPackageGids(String packageName) {
1970        // reader
1971        synchronized (mPackages) {
1972            PackageParser.Package p = mPackages.get(packageName);
1973            if (DEBUG_PACKAGE_INFO)
1974                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1975            if (p != null) {
1976                final PackageSetting ps = (PackageSetting)p.mExtras;
1977                return ps.getGids();
1978            }
1979        }
1980        // stupid thing to indicate an error.
1981        return new int[0];
1982    }
1983
1984    static final PermissionInfo generatePermissionInfo(
1985            BasePermission bp, int flags) {
1986        if (bp.perm != null) {
1987            return PackageParser.generatePermissionInfo(bp.perm, flags);
1988        }
1989        PermissionInfo pi = new PermissionInfo();
1990        pi.name = bp.name;
1991        pi.packageName = bp.sourcePackage;
1992        pi.nonLocalizedLabel = bp.name;
1993        pi.protectionLevel = bp.protectionLevel;
1994        return pi;
1995    }
1996
1997    @Override
1998    public PermissionInfo getPermissionInfo(String name, int flags) {
1999        // reader
2000        synchronized (mPackages) {
2001            final BasePermission p = mSettings.mPermissions.get(name);
2002            if (p != null) {
2003                return generatePermissionInfo(p, flags);
2004            }
2005            return null;
2006        }
2007    }
2008
2009    @Override
2010    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2011        // reader
2012        synchronized (mPackages) {
2013            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2014            for (BasePermission p : mSettings.mPermissions.values()) {
2015                if (group == null) {
2016                    if (p.perm == null || p.perm.info.group == null) {
2017                        out.add(generatePermissionInfo(p, flags));
2018                    }
2019                } else {
2020                    if (p.perm != null && group.equals(p.perm.info.group)) {
2021                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2022                    }
2023                }
2024            }
2025
2026            if (out.size() > 0) {
2027                return out;
2028            }
2029            return mPermissionGroups.containsKey(group) ? out : null;
2030        }
2031    }
2032
2033    @Override
2034    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2035        // reader
2036        synchronized (mPackages) {
2037            return PackageParser.generatePermissionGroupInfo(
2038                    mPermissionGroups.get(name), flags);
2039        }
2040    }
2041
2042    @Override
2043    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2044        // reader
2045        synchronized (mPackages) {
2046            final int N = mPermissionGroups.size();
2047            ArrayList<PermissionGroupInfo> out
2048                    = new ArrayList<PermissionGroupInfo>(N);
2049            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2050                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2051            }
2052            return out;
2053        }
2054    }
2055
2056    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2057            int userId) {
2058        if (!sUserManager.exists(userId)) return null;
2059        PackageSetting ps = mSettings.mPackages.get(packageName);
2060        if (ps != null) {
2061            if (ps.pkg == null) {
2062                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2063                        flags, userId);
2064                if (pInfo != null) {
2065                    return pInfo.applicationInfo;
2066                }
2067                return null;
2068            }
2069            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2070                    ps.readUserState(userId), userId);
2071        }
2072        return null;
2073    }
2074
2075    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2076            int userId) {
2077        if (!sUserManager.exists(userId)) return null;
2078        PackageSetting ps = mSettings.mPackages.get(packageName);
2079        if (ps != null) {
2080            PackageParser.Package pkg = ps.pkg;
2081            if (pkg == null) {
2082                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2083                    return null;
2084                }
2085                // Only data remains, so we aren't worried about code paths
2086                pkg = new PackageParser.Package(packageName);
2087                pkg.applicationInfo.packageName = packageName;
2088                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2089                pkg.applicationInfo.dataDir =
2090                        getDataPathForPackage(packageName, 0).getPath();
2091                pkg.applicationInfo.cpuAbi = ps.cpuAbiString;
2092            }
2093            return generatePackageInfo(pkg, flags, userId);
2094        }
2095        return null;
2096    }
2097
2098    @Override
2099    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2100        if (!sUserManager.exists(userId)) return null;
2101        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get application info");
2102        // writer
2103        synchronized (mPackages) {
2104            PackageParser.Package p = mPackages.get(packageName);
2105            if (DEBUG_PACKAGE_INFO) Log.v(
2106                    TAG, "getApplicationInfo " + packageName
2107                    + ": " + p);
2108            if (p != null) {
2109                PackageSetting ps = mSettings.mPackages.get(packageName);
2110                if (ps == null) return null;
2111                // Note: isEnabledLP() does not apply here - always return info
2112                return PackageParser.generateApplicationInfo(
2113                        p, flags, ps.readUserState(userId), userId);
2114            }
2115            if ("android".equals(packageName)||"system".equals(packageName)) {
2116                return mAndroidApplication;
2117            }
2118            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2119                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2120            }
2121        }
2122        return null;
2123    }
2124
2125
2126    @Override
2127    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2128        mContext.enforceCallingOrSelfPermission(
2129                android.Manifest.permission.CLEAR_APP_CACHE, null);
2130        // Queue up an async operation since clearing cache may take a little while.
2131        mHandler.post(new Runnable() {
2132            public void run() {
2133                mHandler.removeCallbacks(this);
2134                int retCode = -1;
2135                synchronized (mInstallLock) {
2136                    retCode = mInstaller.freeCache(freeStorageSize);
2137                    if (retCode < 0) {
2138                        Slog.w(TAG, "Couldn't clear application caches");
2139                    }
2140                }
2141                if (observer != null) {
2142                    try {
2143                        observer.onRemoveCompleted(null, (retCode >= 0));
2144                    } catch (RemoteException e) {
2145                        Slog.w(TAG, "RemoveException when invoking call back");
2146                    }
2147                }
2148            }
2149        });
2150    }
2151
2152    @Override
2153    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2154        mContext.enforceCallingOrSelfPermission(
2155                android.Manifest.permission.CLEAR_APP_CACHE, null);
2156        // Queue up an async operation since clearing cache may take a little while.
2157        mHandler.post(new Runnable() {
2158            public void run() {
2159                mHandler.removeCallbacks(this);
2160                int retCode = -1;
2161                synchronized (mInstallLock) {
2162                    retCode = mInstaller.freeCache(freeStorageSize);
2163                    if (retCode < 0) {
2164                        Slog.w(TAG, "Couldn't clear application caches");
2165                    }
2166                }
2167                if(pi != null) {
2168                    try {
2169                        // Callback via pending intent
2170                        int code = (retCode >= 0) ? 1 : 0;
2171                        pi.sendIntent(null, code, null,
2172                                null, null);
2173                    } catch (SendIntentException e1) {
2174                        Slog.i(TAG, "Failed to send pending intent");
2175                    }
2176                }
2177            }
2178        });
2179    }
2180
2181    void freeStorage(long freeStorageSize) throws IOException {
2182        synchronized (mInstallLock) {
2183            if (mInstaller.freeCache(freeStorageSize) < 0) {
2184                throw new IOException("Failed to free enough space");
2185            }
2186        }
2187    }
2188
2189    @Override
2190    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2191        if (!sUserManager.exists(userId)) return null;
2192        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get activity info");
2193        synchronized (mPackages) {
2194            PackageParser.Activity a = mActivities.mActivities.get(component);
2195
2196            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2197            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2198                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2199                if (ps == null) return null;
2200                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2201                        userId);
2202            }
2203            if (mResolveComponentName.equals(component)) {
2204                return mResolveActivity;
2205            }
2206        }
2207        return null;
2208    }
2209
2210    @Override
2211    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2212            String resolvedType) {
2213        synchronized (mPackages) {
2214            PackageParser.Activity a = mActivities.mActivities.get(component);
2215            if (a == null) {
2216                return false;
2217            }
2218            for (int i=0; i<a.intents.size(); i++) {
2219                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2220                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2221                    return true;
2222                }
2223            }
2224            return false;
2225        }
2226    }
2227
2228    @Override
2229    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2230        if (!sUserManager.exists(userId)) return null;
2231        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get receiver info");
2232        synchronized (mPackages) {
2233            PackageParser.Activity a = mReceivers.mActivities.get(component);
2234            if (DEBUG_PACKAGE_INFO) Log.v(
2235                TAG, "getReceiverInfo " + component + ": " + a);
2236            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2237                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2238                if (ps == null) return null;
2239                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2240                        userId);
2241            }
2242        }
2243        return null;
2244    }
2245
2246    @Override
2247    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2248        if (!sUserManager.exists(userId)) return null;
2249        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get service info");
2250        synchronized (mPackages) {
2251            PackageParser.Service s = mServices.mServices.get(component);
2252            if (DEBUG_PACKAGE_INFO) Log.v(
2253                TAG, "getServiceInfo " + component + ": " + s);
2254            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2255                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2256                if (ps == null) return null;
2257                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2258                        userId);
2259            }
2260        }
2261        return null;
2262    }
2263
2264    @Override
2265    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2266        if (!sUserManager.exists(userId)) return null;
2267        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "get provider info");
2268        synchronized (mPackages) {
2269            PackageParser.Provider p = mProviders.mProviders.get(component);
2270            if (DEBUG_PACKAGE_INFO) Log.v(
2271                TAG, "getProviderInfo " + component + ": " + p);
2272            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2273                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2274                if (ps == null) return null;
2275                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2276                        userId);
2277            }
2278        }
2279        return null;
2280    }
2281
2282    @Override
2283    public String[] getSystemSharedLibraryNames() {
2284        Set<String> libSet;
2285        synchronized (mPackages) {
2286            libSet = mSharedLibraries.keySet();
2287            int size = libSet.size();
2288            if (size > 0) {
2289                String[] libs = new String[size];
2290                libSet.toArray(libs);
2291                return libs;
2292            }
2293        }
2294        return null;
2295    }
2296
2297    @Override
2298    public FeatureInfo[] getSystemAvailableFeatures() {
2299        Collection<FeatureInfo> featSet;
2300        synchronized (mPackages) {
2301            featSet = mAvailableFeatures.values();
2302            int size = featSet.size();
2303            if (size > 0) {
2304                FeatureInfo[] features = new FeatureInfo[size+1];
2305                featSet.toArray(features);
2306                FeatureInfo fi = new FeatureInfo();
2307                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2308                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2309                features[size] = fi;
2310                return features;
2311            }
2312        }
2313        return null;
2314    }
2315
2316    @Override
2317    public boolean hasSystemFeature(String name) {
2318        synchronized (mPackages) {
2319            return mAvailableFeatures.containsKey(name);
2320        }
2321    }
2322
2323    private void checkValidCaller(int uid, int userId) {
2324        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2325            return;
2326
2327        throw new SecurityException("Caller uid=" + uid
2328                + " is not privileged to communicate with user=" + userId);
2329    }
2330
2331    @Override
2332    public int checkPermission(String permName, String pkgName) {
2333        synchronized (mPackages) {
2334            PackageParser.Package p = mPackages.get(pkgName);
2335            if (p != null && p.mExtras != null) {
2336                PackageSetting ps = (PackageSetting)p.mExtras;
2337                if (ps.sharedUser != null) {
2338                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2339                        return PackageManager.PERMISSION_GRANTED;
2340                    }
2341                } else if (ps.grantedPermissions.contains(permName)) {
2342                    return PackageManager.PERMISSION_GRANTED;
2343                }
2344            }
2345        }
2346        return PackageManager.PERMISSION_DENIED;
2347    }
2348
2349    @Override
2350    public int checkUidPermission(String permName, int uid) {
2351        synchronized (mPackages) {
2352            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2353            if (obj != null) {
2354                GrantedPermissions gp = (GrantedPermissions)obj;
2355                if (gp.grantedPermissions.contains(permName)) {
2356                    return PackageManager.PERMISSION_GRANTED;
2357                }
2358            } else {
2359                HashSet<String> perms = mSystemPermissions.get(uid);
2360                if (perms != null && perms.contains(permName)) {
2361                    return PackageManager.PERMISSION_GRANTED;
2362                }
2363            }
2364        }
2365        return PackageManager.PERMISSION_DENIED;
2366    }
2367
2368    /**
2369     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2370     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2371     * @param message the message to log on security exception
2372     */
2373    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2374            String message) {
2375        if (userId < 0) {
2376            throw new IllegalArgumentException("Invalid userId " + userId);
2377        }
2378        if (userId == UserHandle.getUserId(callingUid)) return;
2379        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2380            if (requireFullPermission) {
2381                mContext.enforceCallingOrSelfPermission(
2382                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2383            } else {
2384                try {
2385                    mContext.enforceCallingOrSelfPermission(
2386                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2387                } catch (SecurityException se) {
2388                    mContext.enforceCallingOrSelfPermission(
2389                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2390                }
2391            }
2392        }
2393    }
2394
2395    private BasePermission findPermissionTreeLP(String permName) {
2396        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2397            if (permName.startsWith(bp.name) &&
2398                    permName.length() > bp.name.length() &&
2399                    permName.charAt(bp.name.length()) == '.') {
2400                return bp;
2401            }
2402        }
2403        return null;
2404    }
2405
2406    private BasePermission checkPermissionTreeLP(String permName) {
2407        if (permName != null) {
2408            BasePermission bp = findPermissionTreeLP(permName);
2409            if (bp != null) {
2410                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2411                    return bp;
2412                }
2413                throw new SecurityException("Calling uid "
2414                        + Binder.getCallingUid()
2415                        + " is not allowed to add to permission tree "
2416                        + bp.name + " owned by uid " + bp.uid);
2417            }
2418        }
2419        throw new SecurityException("No permission tree found for " + permName);
2420    }
2421
2422    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2423        if (s1 == null) {
2424            return s2 == null;
2425        }
2426        if (s2 == null) {
2427            return false;
2428        }
2429        if (s1.getClass() != s2.getClass()) {
2430            return false;
2431        }
2432        return s1.equals(s2);
2433    }
2434
2435    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2436        if (pi1.icon != pi2.icon) return false;
2437        if (pi1.logo != pi2.logo) return false;
2438        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2439        if (!compareStrings(pi1.name, pi2.name)) return false;
2440        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2441        // We'll take care of setting this one.
2442        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2443        // These are not currently stored in settings.
2444        //if (!compareStrings(pi1.group, pi2.group)) return false;
2445        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2446        //if (pi1.labelRes != pi2.labelRes) return false;
2447        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2448        return true;
2449    }
2450
2451    int permissionInfoFootprint(PermissionInfo info) {
2452        int size = info.name.length();
2453        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2454        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2455        return size;
2456    }
2457
2458    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2459        int size = 0;
2460        for (BasePermission perm : mSettings.mPermissions.values()) {
2461            if (perm.uid == tree.uid) {
2462                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2463            }
2464        }
2465        return size;
2466    }
2467
2468    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2469        // We calculate the max size of permissions defined by this uid and throw
2470        // if that plus the size of 'info' would exceed our stated maximum.
2471        if (tree.uid != Process.SYSTEM_UID) {
2472            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2473            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2474                throw new SecurityException("Permission tree size cap exceeded");
2475            }
2476        }
2477    }
2478
2479    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2480        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2481            throw new SecurityException("Label must be specified in permission");
2482        }
2483        BasePermission tree = checkPermissionTreeLP(info.name);
2484        BasePermission bp = mSettings.mPermissions.get(info.name);
2485        boolean added = bp == null;
2486        boolean changed = true;
2487        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2488        if (added) {
2489            enforcePermissionCapLocked(info, tree);
2490            bp = new BasePermission(info.name, tree.sourcePackage,
2491                    BasePermission.TYPE_DYNAMIC);
2492        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2493            throw new SecurityException(
2494                    "Not allowed to modify non-dynamic permission "
2495                    + info.name);
2496        } else {
2497            if (bp.protectionLevel == fixedLevel
2498                    && bp.perm.owner.equals(tree.perm.owner)
2499                    && bp.uid == tree.uid
2500                    && comparePermissionInfos(bp.perm.info, info)) {
2501                changed = false;
2502            }
2503        }
2504        bp.protectionLevel = fixedLevel;
2505        info = new PermissionInfo(info);
2506        info.protectionLevel = fixedLevel;
2507        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2508        bp.perm.info.packageName = tree.perm.info.packageName;
2509        bp.uid = tree.uid;
2510        if (added) {
2511            mSettings.mPermissions.put(info.name, bp);
2512        }
2513        if (changed) {
2514            if (!async) {
2515                mSettings.writeLPr();
2516            } else {
2517                scheduleWriteSettingsLocked();
2518            }
2519        }
2520        return added;
2521    }
2522
2523    @Override
2524    public boolean addPermission(PermissionInfo info) {
2525        synchronized (mPackages) {
2526            return addPermissionLocked(info, false);
2527        }
2528    }
2529
2530    @Override
2531    public boolean addPermissionAsync(PermissionInfo info) {
2532        synchronized (mPackages) {
2533            return addPermissionLocked(info, true);
2534        }
2535    }
2536
2537    @Override
2538    public void removePermission(String name) {
2539        synchronized (mPackages) {
2540            checkPermissionTreeLP(name);
2541            BasePermission bp = mSettings.mPermissions.get(name);
2542            if (bp != null) {
2543                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2544                    throw new SecurityException(
2545                            "Not allowed to modify non-dynamic permission "
2546                            + name);
2547                }
2548                mSettings.mPermissions.remove(name);
2549                mSettings.writeLPr();
2550            }
2551        }
2552    }
2553
2554    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2555        int index = pkg.requestedPermissions.indexOf(bp.name);
2556        if (index == -1) {
2557            throw new SecurityException("Package " + pkg.packageName
2558                    + " has not requested permission " + bp.name);
2559        }
2560        boolean isNormal =
2561                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2562                        == PermissionInfo.PROTECTION_NORMAL);
2563        boolean isDangerous =
2564                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2565                        == PermissionInfo.PROTECTION_DANGEROUS);
2566        boolean isDevelopment =
2567                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2568
2569        if (!isNormal && !isDangerous && !isDevelopment) {
2570            throw new SecurityException("Permission " + bp.name
2571                    + " is not a changeable permission type");
2572        }
2573
2574        if (isNormal || isDangerous) {
2575            if (pkg.requestedPermissionsRequired.get(index)) {
2576                throw new SecurityException("Can't change " + bp.name
2577                        + ". It is required by the application");
2578            }
2579        }
2580    }
2581
2582    @Override
2583    public void grantPermission(String packageName, String permissionName) {
2584        mContext.enforceCallingOrSelfPermission(
2585                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2586        synchronized (mPackages) {
2587            final PackageParser.Package pkg = mPackages.get(packageName);
2588            if (pkg == null) {
2589                throw new IllegalArgumentException("Unknown package: " + packageName);
2590            }
2591            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2592            if (bp == null) {
2593                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2594            }
2595
2596            checkGrantRevokePermissions(pkg, bp);
2597
2598            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2599            if (ps == null) {
2600                return;
2601            }
2602            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2603            if (gp.grantedPermissions.add(permissionName)) {
2604                if (ps.haveGids) {
2605                    gp.gids = appendInts(gp.gids, bp.gids);
2606                }
2607                mSettings.writeLPr();
2608            }
2609        }
2610    }
2611
2612    @Override
2613    public void revokePermission(String packageName, String permissionName) {
2614        int changedAppId = -1;
2615
2616        synchronized (mPackages) {
2617            final PackageParser.Package pkg = mPackages.get(packageName);
2618            if (pkg == null) {
2619                throw new IllegalArgumentException("Unknown package: " + packageName);
2620            }
2621            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2622                mContext.enforceCallingOrSelfPermission(
2623                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2624            }
2625            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2626            if (bp == null) {
2627                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2628            }
2629
2630            checkGrantRevokePermissions(pkg, bp);
2631
2632            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2633            if (ps == null) {
2634                return;
2635            }
2636            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2637            if (gp.grantedPermissions.remove(permissionName)) {
2638                gp.grantedPermissions.remove(permissionName);
2639                if (ps.haveGids) {
2640                    gp.gids = removeInts(gp.gids, bp.gids);
2641                }
2642                mSettings.writeLPr();
2643                changedAppId = ps.appId;
2644            }
2645        }
2646
2647        if (changedAppId >= 0) {
2648            // We changed the perm on someone, kill its processes.
2649            IActivityManager am = ActivityManagerNative.getDefault();
2650            if (am != null) {
2651                final int callingUserId = UserHandle.getCallingUserId();
2652                final long ident = Binder.clearCallingIdentity();
2653                try {
2654                    //XXX we should only revoke for the calling user's app permissions,
2655                    // but for now we impact all users.
2656                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2657                    //        "revoke " + permissionName);
2658                    int[] users = sUserManager.getUserIds();
2659                    for (int user : users) {
2660                        am.killUid(UserHandle.getUid(user, changedAppId),
2661                                "revoke " + permissionName);
2662                    }
2663                } catch (RemoteException e) {
2664                } finally {
2665                    Binder.restoreCallingIdentity(ident);
2666                }
2667            }
2668        }
2669    }
2670
2671    @Override
2672    public boolean isProtectedBroadcast(String actionName) {
2673        synchronized (mPackages) {
2674            return mProtectedBroadcasts.contains(actionName);
2675        }
2676    }
2677
2678    @Override
2679    public int checkSignatures(String pkg1, String pkg2) {
2680        synchronized (mPackages) {
2681            final PackageParser.Package p1 = mPackages.get(pkg1);
2682            final PackageParser.Package p2 = mPackages.get(pkg2);
2683            if (p1 == null || p1.mExtras == null
2684                    || p2 == null || p2.mExtras == null) {
2685                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2686            }
2687            return compareSignatures(p1.mSignatures, p2.mSignatures);
2688        }
2689    }
2690
2691    @Override
2692    public int checkUidSignatures(int uid1, int uid2) {
2693        // Map to base uids.
2694        uid1 = UserHandle.getAppId(uid1);
2695        uid2 = UserHandle.getAppId(uid2);
2696        // reader
2697        synchronized (mPackages) {
2698            Signature[] s1;
2699            Signature[] s2;
2700            Object obj = mSettings.getUserIdLPr(uid1);
2701            if (obj != null) {
2702                if (obj instanceof SharedUserSetting) {
2703                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2704                } else if (obj instanceof PackageSetting) {
2705                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2706                } else {
2707                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2708                }
2709            } else {
2710                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2711            }
2712            obj = mSettings.getUserIdLPr(uid2);
2713            if (obj != null) {
2714                if (obj instanceof SharedUserSetting) {
2715                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2716                } else if (obj instanceof PackageSetting) {
2717                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2718                } else {
2719                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2720                }
2721            } else {
2722                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2723            }
2724            return compareSignatures(s1, s2);
2725        }
2726    }
2727
2728    /**
2729     * Compares two sets of signatures. Returns:
2730     * <br />
2731     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2732     * <br />
2733     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2734     * <br />
2735     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2736     * <br />
2737     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2738     * <br />
2739     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2740     */
2741    static int compareSignatures(Signature[] s1, Signature[] s2) {
2742        if (s1 == null) {
2743            return s2 == null
2744                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2745                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2746        }
2747
2748        if (s2 == null) {
2749            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2750        }
2751
2752        if (s1.length != s2.length) {
2753            return PackageManager.SIGNATURE_NO_MATCH;
2754        }
2755
2756        // Since both signature sets are of size 1, we can compare without HashSets.
2757        if (s1.length == 1) {
2758            return s1[0].equals(s2[0]) ?
2759                    PackageManager.SIGNATURE_MATCH :
2760                    PackageManager.SIGNATURE_NO_MATCH;
2761        }
2762
2763        HashSet<Signature> set1 = new HashSet<Signature>();
2764        for (Signature sig : s1) {
2765            set1.add(sig);
2766        }
2767        HashSet<Signature> set2 = new HashSet<Signature>();
2768        for (Signature sig : s2) {
2769            set2.add(sig);
2770        }
2771        // Make sure s2 contains all signatures in s1.
2772        if (set1.equals(set2)) {
2773            return PackageManager.SIGNATURE_MATCH;
2774        }
2775        return PackageManager.SIGNATURE_NO_MATCH;
2776    }
2777
2778    /**
2779     * If the database version for this type of package (internal storage or
2780     * external storage) is less than the version where package signatures
2781     * were updated, return true.
2782     */
2783    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2784        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2785                DatabaseVersion.SIGNATURE_END_ENTITY))
2786                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2787                        DatabaseVersion.SIGNATURE_END_ENTITY));
2788    }
2789
2790    /**
2791     * Used for backward compatibility to make sure any packages with
2792     * certificate chains get upgraded to the new style. {@code existingSigs}
2793     * will be in the old format (since they were stored on disk from before the
2794     * system upgrade) and {@code scannedSigs} will be in the newer format.
2795     */
2796    private int compareSignaturesCompat(PackageSignatures existingSigs,
2797            PackageParser.Package scannedPkg) {
2798        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2799            return PackageManager.SIGNATURE_NO_MATCH;
2800        }
2801
2802        HashSet<Signature> existingSet = new HashSet<Signature>();
2803        for (Signature sig : existingSigs.mSignatures) {
2804            existingSet.add(sig);
2805        }
2806        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2807        for (Signature sig : scannedPkg.mSignatures) {
2808            try {
2809                Signature[] chainSignatures = sig.getChainSignatures();
2810                for (Signature chainSig : chainSignatures) {
2811                    scannedCompatSet.add(chainSig);
2812                }
2813            } catch (CertificateEncodingException e) {
2814                scannedCompatSet.add(sig);
2815            }
2816        }
2817        /*
2818         * Make sure the expanded scanned set contains all signatures in the
2819         * existing one.
2820         */
2821        if (scannedCompatSet.equals(existingSet)) {
2822            // Migrate the old signatures to the new scheme.
2823            existingSigs.assignSignatures(scannedPkg.mSignatures);
2824            // The new KeySets will be re-added later in the scanning process.
2825            mSettings.mKeySetManagerService.removeAppKeySetData(scannedPkg.packageName);
2826            return PackageManager.SIGNATURE_MATCH;
2827        }
2828        return PackageManager.SIGNATURE_NO_MATCH;
2829    }
2830
2831    @Override
2832    public String[] getPackagesForUid(int uid) {
2833        uid = UserHandle.getAppId(uid);
2834        // reader
2835        synchronized (mPackages) {
2836            Object obj = mSettings.getUserIdLPr(uid);
2837            if (obj instanceof SharedUserSetting) {
2838                final SharedUserSetting sus = (SharedUserSetting) obj;
2839                final int N = sus.packages.size();
2840                final String[] res = new String[N];
2841                final Iterator<PackageSetting> it = sus.packages.iterator();
2842                int i = 0;
2843                while (it.hasNext()) {
2844                    res[i++] = it.next().name;
2845                }
2846                return res;
2847            } else if (obj instanceof PackageSetting) {
2848                final PackageSetting ps = (PackageSetting) obj;
2849                return new String[] { ps.name };
2850            }
2851        }
2852        return null;
2853    }
2854
2855    @Override
2856    public String getNameForUid(int uid) {
2857        // reader
2858        synchronized (mPackages) {
2859            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2860            if (obj instanceof SharedUserSetting) {
2861                final SharedUserSetting sus = (SharedUserSetting) obj;
2862                return sus.name + ":" + sus.userId;
2863            } else if (obj instanceof PackageSetting) {
2864                final PackageSetting ps = (PackageSetting) obj;
2865                return ps.name;
2866            }
2867        }
2868        return null;
2869    }
2870
2871    @Override
2872    public int getUidForSharedUser(String sharedUserName) {
2873        if(sharedUserName == null) {
2874            return -1;
2875        }
2876        // reader
2877        synchronized (mPackages) {
2878            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2879            if (suid == null) {
2880                return -1;
2881            }
2882            return suid.userId;
2883        }
2884    }
2885
2886    @Override
2887    public int getFlagsForUid(int uid) {
2888        synchronized (mPackages) {
2889            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2890            if (obj instanceof SharedUserSetting) {
2891                final SharedUserSetting sus = (SharedUserSetting) obj;
2892                return sus.pkgFlags;
2893            } else if (obj instanceof PackageSetting) {
2894                final PackageSetting ps = (PackageSetting) obj;
2895                return ps.pkgFlags;
2896            }
2897        }
2898        return 0;
2899    }
2900
2901    @Override
2902    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2903            int flags, int userId) {
2904        if (!sUserManager.exists(userId)) return null;
2905        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "resolve intent");
2906        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2907        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2908    }
2909
2910    @Override
2911    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2912            IntentFilter filter, int match, ComponentName activity) {
2913        final int userId = UserHandle.getCallingUserId();
2914        if (DEBUG_PREFERRED) {
2915            Log.v(TAG, "setLastChosenActivity intent=" + intent
2916                + " resolvedType=" + resolvedType
2917                + " flags=" + flags
2918                + " filter=" + filter
2919                + " match=" + match
2920                + " activity=" + activity);
2921            filter.dump(new PrintStreamPrinter(System.out), "    ");
2922        }
2923        intent.setComponent(null);
2924        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2925        // Find any earlier preferred or last chosen entries and nuke them
2926        findPreferredActivity(intent, resolvedType,
2927                flags, query, 0, false, true, false, userId);
2928        // Add the new activity as the last chosen for this filter
2929        addPreferredActivityInternal(filter, match, null, activity, false, userId);
2930    }
2931
2932    @Override
2933    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2934        final int userId = UserHandle.getCallingUserId();
2935        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2936        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2937        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2938                false, false, false, userId);
2939    }
2940
2941    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2942            int flags, List<ResolveInfo> query, int userId) {
2943        if (query != null) {
2944            final int N = query.size();
2945            if (N == 1) {
2946                return query.get(0);
2947            } else if (N > 1) {
2948                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2949                // If there is more than one activity with the same priority,
2950                // then let the user decide between them.
2951                ResolveInfo r0 = query.get(0);
2952                ResolveInfo r1 = query.get(1);
2953                if (DEBUG_INTENT_MATCHING || debug) {
2954                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2955                            + r1.activityInfo.name + "=" + r1.priority);
2956                }
2957                // If the first activity has a higher priority, or a different
2958                // default, then it is always desireable to pick it.
2959                if (r0.priority != r1.priority
2960                        || r0.preferredOrder != r1.preferredOrder
2961                        || r0.isDefault != r1.isDefault) {
2962                    return query.get(0);
2963                }
2964                // If we have saved a preference for a preferred activity for
2965                // this Intent, use that.
2966                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2967                        flags, query, r0.priority, true, false, debug, userId);
2968                if (ri != null) {
2969                    return ri;
2970                }
2971                if (userId != 0) {
2972                    ri = new ResolveInfo(mResolveInfo);
2973                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2974                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2975                            ri.activityInfo.applicationInfo);
2976                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2977                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2978                    return ri;
2979                }
2980                return mResolveInfo;
2981            }
2982        }
2983        return null;
2984    }
2985
2986    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2987            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2988        final int N = query.size();
2989        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2990                .get(userId);
2991        // Get the list of persistent preferred activities that handle the intent
2992        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2993        List<PersistentPreferredActivity> pprefs = ppir != null
2994                ? ppir.queryIntent(intent, resolvedType,
2995                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2996                : null;
2997        if (pprefs != null && pprefs.size() > 0) {
2998            final int M = pprefs.size();
2999            for (int i=0; i<M; i++) {
3000                final PersistentPreferredActivity ppa = pprefs.get(i);
3001                if (DEBUG_PREFERRED || debug) {
3002                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3003                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3004                            + "\n  component=" + ppa.mComponent);
3005                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3006                }
3007                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3008                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3009                if (DEBUG_PREFERRED || debug) {
3010                    Slog.v(TAG, "Found persistent preferred activity:");
3011                    if (ai != null) {
3012                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3013                    } else {
3014                        Slog.v(TAG, "  null");
3015                    }
3016                }
3017                if (ai == null) {
3018                    // This previously registered persistent preferred activity
3019                    // component is no longer known. Ignore it and do NOT remove it.
3020                    continue;
3021                }
3022                for (int j=0; j<N; j++) {
3023                    final ResolveInfo ri = query.get(j);
3024                    if (!ri.activityInfo.applicationInfo.packageName
3025                            .equals(ai.applicationInfo.packageName)) {
3026                        continue;
3027                    }
3028                    if (!ri.activityInfo.name.equals(ai.name)) {
3029                        continue;
3030                    }
3031                    //  Found a persistent preference that can handle the intent.
3032                    if (DEBUG_PREFERRED || debug) {
3033                        Slog.v(TAG, "Returning persistent preferred activity: " +
3034                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3035                    }
3036                    return ri;
3037                }
3038            }
3039        }
3040        return null;
3041    }
3042
3043    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3044            List<ResolveInfo> query, int priority, boolean always,
3045            boolean removeMatches, boolean debug, int userId) {
3046        if (!sUserManager.exists(userId)) return null;
3047        // writer
3048        synchronized (mPackages) {
3049            if (intent.getSelector() != null) {
3050                intent = intent.getSelector();
3051            }
3052            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3053
3054            // Try to find a matching persistent preferred activity.
3055            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3056                    debug, userId);
3057
3058            // If a persistent preferred activity matched, use it.
3059            if (pri != null) {
3060                return pri;
3061            }
3062
3063            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3064            // Get the list of preferred activities that handle the intent
3065            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3066            List<PreferredActivity> prefs = pir != null
3067                    ? pir.queryIntent(intent, resolvedType,
3068                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3069                    : null;
3070            if (prefs != null && prefs.size() > 0) {
3071                // First figure out how good the original match set is.
3072                // We will only allow preferred activities that came
3073                // from the same match quality.
3074                int match = 0;
3075
3076                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3077
3078                final int N = query.size();
3079                for (int j=0; j<N; j++) {
3080                    final ResolveInfo ri = query.get(j);
3081                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3082                            + ": 0x" + Integer.toHexString(match));
3083                    if (ri.match > match) {
3084                        match = ri.match;
3085                    }
3086                }
3087
3088                if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3089                        + Integer.toHexString(match));
3090
3091                match &= IntentFilter.MATCH_CATEGORY_MASK;
3092                final int M = prefs.size();
3093                for (int i=0; i<M; i++) {
3094                    final PreferredActivity pa = prefs.get(i);
3095                    if (DEBUG_PREFERRED || debug) {
3096                        Slog.v(TAG, "Checking PreferredActivity ds="
3097                                + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3098                                + "\n  component=" + pa.mPref.mComponent);
3099                        pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3100                    }
3101                    if (pa.mPref.mMatch != match) {
3102                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3103                                + Integer.toHexString(pa.mPref.mMatch));
3104                        continue;
3105                    }
3106                    // If it's not an "always" type preferred activity and that's what we're
3107                    // looking for, skip it.
3108                    if (always && !pa.mPref.mAlways) {
3109                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3110                        continue;
3111                    }
3112                    final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3113                            flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3114                    if (DEBUG_PREFERRED || debug) {
3115                        Slog.v(TAG, "Found preferred activity:");
3116                        if (ai != null) {
3117                            ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3118                        } else {
3119                            Slog.v(TAG, "  null");
3120                        }
3121                    }
3122                    if (ai == null) {
3123                        // This previously registered preferred activity
3124                        // component is no longer known.  Most likely an update
3125                        // to the app was installed and in the new version this
3126                        // component no longer exists.  Clean it up by removing
3127                        // it from the preferred activities list, and skip it.
3128                        Slog.w(TAG, "Removing dangling preferred activity: "
3129                                + pa.mPref.mComponent);
3130                        pir.removeFilter(pa);
3131                        continue;
3132                    }
3133                    for (int j=0; j<N; j++) {
3134                        final ResolveInfo ri = query.get(j);
3135                        if (!ri.activityInfo.applicationInfo.packageName
3136                                .equals(ai.applicationInfo.packageName)) {
3137                            continue;
3138                        }
3139                        if (!ri.activityInfo.name.equals(ai.name)) {
3140                            continue;
3141                        }
3142
3143                        if (removeMatches) {
3144                            pir.removeFilter(pa);
3145                            if (DEBUG_PREFERRED) {
3146                                Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3147                            }
3148                            break;
3149                        }
3150
3151                        // Okay we found a previously set preferred or last chosen app.
3152                        // If the result set is different from when this
3153                        // was created, we need to clear it and re-ask the
3154                        // user their preference, if we're looking for an "always" type entry.
3155                        if (always && !pa.mPref.sameSet(query, priority)) {
3156                            Slog.i(TAG, "Result set changed, dropping preferred activity for "
3157                                    + intent + " type " + resolvedType);
3158                            if (DEBUG_PREFERRED) {
3159                                Slog.v(TAG, "Removing preferred activity since set changed "
3160                                        + pa.mPref.mComponent);
3161                            }
3162                            pir.removeFilter(pa);
3163                            // Re-add the filter as a "last chosen" entry (!always)
3164                            PreferredActivity lastChosen = new PreferredActivity(
3165                                    pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3166                            pir.addFilter(lastChosen);
3167                            mSettings.writePackageRestrictionsLPr(userId);
3168                            return null;
3169                        }
3170
3171                        // Yay! Either the set matched or we're looking for the last chosen
3172                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3173                                + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3174                        mSettings.writePackageRestrictionsLPr(userId);
3175                        return ri;
3176                    }
3177                }
3178            }
3179            mSettings.writePackageRestrictionsLPr(userId);
3180        }
3181        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3182        return null;
3183    }
3184
3185    /*
3186     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3187     */
3188    @Override
3189    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3190            int targetUserId) {
3191        mContext.enforceCallingOrSelfPermission(
3192                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3193        List<CrossProfileIntentFilter> matches =
3194                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3195        if (matches != null) {
3196            int size = matches.size();
3197            for (int i = 0; i < size; i++) {
3198                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3199            }
3200        }
3201
3202        ArrayList<String> packageNames = null;
3203        SparseArray<ArrayList<String>> fromSource =
3204                mSettings.mCrossProfilePackageInfo.get(sourceUserId);
3205        if (fromSource != null) {
3206            packageNames = fromSource.get(targetUserId);
3207        }
3208        if (packageNames.contains(intent.getPackage())) {
3209            return true;
3210        }
3211        // We need the package name, so we try to resolve with the loosest flags possible
3212        List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3213                intent, resolvedType, PackageManager.GET_UNINSTALLED_PACKAGES, targetUserId);
3214        int count = resolveInfos.size();
3215        for (int i = 0; i < count; i++) {
3216            ResolveInfo resolveInfo = resolveInfos.get(i);
3217            if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3218                return true;
3219            }
3220        }
3221        return false;
3222    }
3223
3224    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3225            String resolvedType, int userId) {
3226        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3227        if (resolver != null) {
3228            return resolver.queryIntent(intent, resolvedType, false, userId);
3229        }
3230        return null;
3231    }
3232
3233    @Override
3234    public List<ResolveInfo> queryIntentActivities(Intent intent,
3235            String resolvedType, int flags, int userId) {
3236        if (!sUserManager.exists(userId)) return Collections.emptyList();
3237        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, "query intent activities");
3238        ComponentName comp = intent.getComponent();
3239        if (comp == null) {
3240            if (intent.getSelector() != null) {
3241                intent = intent.getSelector();
3242                comp = intent.getComponent();
3243            }
3244        }
3245
3246        if (comp != null) {
3247            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3248            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3249            if (ai != null) {
3250                final ResolveInfo ri = new ResolveInfo();
3251                ri.activityInfo = ai;
3252                list.add(ri);
3253            }
3254            return list;
3255        }
3256
3257        // reader
3258        synchronized (mPackages) {
3259            final String pkgName = intent.getPackage();
3260            boolean queryCrossProfile = (flags & PackageManager.NO_CROSS_PROFILE) == 0;
3261            if (pkgName == null) {
3262                ResolveInfo resolveInfo = null;
3263                if (queryCrossProfile) {
3264                    // Check if the intent needs to be forwarded to another user for this package
3265                    ArrayList<ResolveInfo> crossProfileResult =
3266                            queryIntentActivitiesCrossProfilePackage(
3267                                    intent, resolvedType, flags, userId);
3268                    if (!crossProfileResult.isEmpty()) {
3269                        // Skip the current profile
3270                        return crossProfileResult;
3271                    }
3272                    List<CrossProfileIntentFilter> matchingFilters =
3273                            getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3274                    // Check for results that need to skip the current profile.
3275                    resolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent,
3276                            resolvedType, flags, userId);
3277                    if (resolveInfo != null) {
3278                        List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3279                        result.add(resolveInfo);
3280                        return result;
3281                    }
3282                    // Check for cross profile results.
3283                    resolveInfo = queryCrossProfileIntents(
3284                            matchingFilters, intent, resolvedType, flags, userId);
3285                }
3286                // Check for results in the current profile.
3287                List<ResolveInfo> result = mActivities.queryIntent(
3288                        intent, resolvedType, flags, userId);
3289                if (resolveInfo != null) {
3290                    result.add(resolveInfo);
3291                }
3292                return result;
3293            }
3294            final PackageParser.Package pkg = mPackages.get(pkgName);
3295            if (pkg != null) {
3296                if (queryCrossProfile) {
3297                    ArrayList<ResolveInfo> crossProfileResult =
3298                            queryIntentActivitiesCrossProfilePackage(
3299                                    intent, resolvedType, flags, userId, pkg, pkgName);
3300                    if (!crossProfileResult.isEmpty()) {
3301                        // Skip the current profile
3302                        return crossProfileResult;
3303                    }
3304                }
3305                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3306                        pkg.activities, userId);
3307            }
3308            return new ArrayList<ResolveInfo>();
3309        }
3310    }
3311
3312    private ResolveInfo querySkipCurrentProfileIntents(
3313            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3314            int flags, int sourceUserId) {
3315        if (matchingFilters != null) {
3316            int size = matchingFilters.size();
3317            for (int i = 0; i < size; i ++) {
3318                CrossProfileIntentFilter filter = matchingFilters.get(i);
3319                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3320                    // Checking if there are activities in the target user that can handle the
3321                    // intent.
3322                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3323                            flags, sourceUserId);
3324                    if (resolveInfo != null) {
3325                        return resolveInfo;
3326                    }
3327                }
3328            }
3329        }
3330        return null;
3331    }
3332
3333    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3334            Intent intent, String resolvedType, int flags, int userId) {
3335        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3336        SparseArray<ArrayList<String>> sourceForwardingInfo =
3337                mSettings.mCrossProfilePackageInfo.get(userId);
3338        if (sourceForwardingInfo != null) {
3339            int NI = sourceForwardingInfo.size();
3340            for (int i = 0; i < NI; i++) {
3341                int targetUserId = sourceForwardingInfo.keyAt(i);
3342                ArrayList<String> packageNames = sourceForwardingInfo.valueAt(i);
3343                List<ResolveInfo> resolveInfos = mActivities.queryIntent(
3344                        intent, resolvedType, flags, targetUserId);
3345                int NJ = resolveInfos.size();
3346                for (int j = 0; j < NJ; j++) {
3347                    ResolveInfo resolveInfo = resolveInfos.get(j);
3348                    if (packageNames.contains(resolveInfo.activityInfo.packageName)) {
3349                        matchingResolveInfos.add(createForwardingResolveInfo(
3350                                resolveInfo.filter, userId, targetUserId));
3351                    }
3352                }
3353            }
3354        }
3355        return matchingResolveInfos;
3356    }
3357
3358    private ArrayList<ResolveInfo> queryIntentActivitiesCrossProfilePackage(
3359            Intent intent, String resolvedType, int flags, int userId, PackageParser.Package pkg,
3360            String packageName) {
3361        ArrayList<ResolveInfo> matchingResolveInfos = new ArrayList<ResolveInfo>();
3362        SparseArray<ArrayList<String>> sourceForwardingInfo =
3363                mSettings.mCrossProfilePackageInfo.get(userId);
3364        if (sourceForwardingInfo != null) {
3365            int NI = sourceForwardingInfo.size();
3366            for (int i = 0; i < NI; i++) {
3367                int targetUserId = sourceForwardingInfo.keyAt(i);
3368                if (sourceForwardingInfo.valueAt(i).contains(packageName)) {
3369                    List<ResolveInfo> resolveInfos = mActivities.queryIntentForPackage(
3370                            intent, resolvedType, flags, pkg.activities, targetUserId);
3371                    int NJ = resolveInfos.size();
3372                    for (int j = 0; j < NJ; j++) {
3373                        ResolveInfo resolveInfo = resolveInfos.get(j);
3374                        matchingResolveInfos.add(createForwardingResolveInfo(
3375                                resolveInfo.filter, userId, targetUserId));
3376                    }
3377                }
3378            }
3379        }
3380        return matchingResolveInfos;
3381    }
3382
3383    // Return matching ResolveInfo if any for skip current profile intent filters.
3384    private ResolveInfo queryCrossProfileIntents(
3385            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3386            int flags, int sourceUserId) {
3387        if (matchingFilters != null) {
3388            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3389            // match the same intent. For performance reasons, it is better not to
3390            // run queryIntent twice for the same userId
3391            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3392            int size = matchingFilters.size();
3393            for (int i = 0; i < size; i++) {
3394                CrossProfileIntentFilter filter = matchingFilters.get(i);
3395                int targetUserId = filter.getTargetUserId();
3396                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3397                        && !alreadyTriedUserIds.get(targetUserId)) {
3398                    // Checking if there are activities in the target user that can handle the
3399                    // intent.
3400                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3401                            flags, sourceUserId);
3402                    if (resolveInfo != null) return resolveInfo;
3403                    alreadyTriedUserIds.put(targetUserId, true);
3404                }
3405            }
3406        }
3407        return null;
3408    }
3409
3410    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3411            String resolvedType, int flags, int sourceUserId) {
3412        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3413                resolvedType, flags, filter.getTargetUserId());
3414        if (resultTargetUser != null) {
3415            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3416        }
3417        return null;
3418    }
3419
3420    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3421            int sourceUserId, int targetUserId) {
3422        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3423        String className;
3424        if (targetUserId == UserHandle.USER_OWNER) {
3425            className = FORWARD_INTENT_TO_USER_OWNER;
3426        } else {
3427            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3428        }
3429        ComponentName forwardingActivityComponentName = new ComponentName(
3430                mAndroidApplication.packageName, className);
3431        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3432                sourceUserId);
3433        if (targetUserId == UserHandle.USER_OWNER) {
3434            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3435            forwardingResolveInfo.noResourceId = true;
3436        }
3437        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3438        forwardingResolveInfo.priority = 0;
3439        forwardingResolveInfo.preferredOrder = 0;
3440        forwardingResolveInfo.match = 0;
3441        forwardingResolveInfo.isDefault = true;
3442        forwardingResolveInfo.filter = filter;
3443        forwardingResolveInfo.targetUserId = targetUserId;
3444        return forwardingResolveInfo;
3445    }
3446
3447    @Override
3448    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3449            Intent[] specifics, String[] specificTypes, Intent intent,
3450            String resolvedType, int flags, int userId) {
3451        if (!sUserManager.exists(userId)) return Collections.emptyList();
3452        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3453                "query intent activity options");
3454        final String resultsAction = intent.getAction();
3455
3456        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3457                | PackageManager.GET_RESOLVED_FILTER, userId);
3458
3459        if (DEBUG_INTENT_MATCHING) {
3460            Log.v(TAG, "Query " + intent + ": " + results);
3461        }
3462
3463        int specificsPos = 0;
3464        int N;
3465
3466        // todo: note that the algorithm used here is O(N^2).  This
3467        // isn't a problem in our current environment, but if we start running
3468        // into situations where we have more than 5 or 10 matches then this
3469        // should probably be changed to something smarter...
3470
3471        // First we go through and resolve each of the specific items
3472        // that were supplied, taking care of removing any corresponding
3473        // duplicate items in the generic resolve list.
3474        if (specifics != null) {
3475            for (int i=0; i<specifics.length; i++) {
3476                final Intent sintent = specifics[i];
3477                if (sintent == null) {
3478                    continue;
3479                }
3480
3481                if (DEBUG_INTENT_MATCHING) {
3482                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3483                }
3484
3485                String action = sintent.getAction();
3486                if (resultsAction != null && resultsAction.equals(action)) {
3487                    // If this action was explicitly requested, then don't
3488                    // remove things that have it.
3489                    action = null;
3490                }
3491
3492                ResolveInfo ri = null;
3493                ActivityInfo ai = null;
3494
3495                ComponentName comp = sintent.getComponent();
3496                if (comp == null) {
3497                    ri = resolveIntent(
3498                        sintent,
3499                        specificTypes != null ? specificTypes[i] : null,
3500                            flags, userId);
3501                    if (ri == null) {
3502                        continue;
3503                    }
3504                    if (ri == mResolveInfo) {
3505                        // ACK!  Must do something better with this.
3506                    }
3507                    ai = ri.activityInfo;
3508                    comp = new ComponentName(ai.applicationInfo.packageName,
3509                            ai.name);
3510                } else {
3511                    ai = getActivityInfo(comp, flags, userId);
3512                    if (ai == null) {
3513                        continue;
3514                    }
3515                }
3516
3517                // Look for any generic query activities that are duplicates
3518                // of this specific one, and remove them from the results.
3519                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3520                N = results.size();
3521                int j;
3522                for (j=specificsPos; j<N; j++) {
3523                    ResolveInfo sri = results.get(j);
3524                    if ((sri.activityInfo.name.equals(comp.getClassName())
3525                            && sri.activityInfo.applicationInfo.packageName.equals(
3526                                    comp.getPackageName()))
3527                        || (action != null && sri.filter.matchAction(action))) {
3528                        results.remove(j);
3529                        if (DEBUG_INTENT_MATCHING) Log.v(
3530                            TAG, "Removing duplicate item from " + j
3531                            + " due to specific " + specificsPos);
3532                        if (ri == null) {
3533                            ri = sri;
3534                        }
3535                        j--;
3536                        N--;
3537                    }
3538                }
3539
3540                // Add this specific item to its proper place.
3541                if (ri == null) {
3542                    ri = new ResolveInfo();
3543                    ri.activityInfo = ai;
3544                }
3545                results.add(specificsPos, ri);
3546                ri.specificIndex = i;
3547                specificsPos++;
3548            }
3549        }
3550
3551        // Now we go through the remaining generic results and remove any
3552        // duplicate actions that are found here.
3553        N = results.size();
3554        for (int i=specificsPos; i<N-1; i++) {
3555            final ResolveInfo rii = results.get(i);
3556            if (rii.filter == null) {
3557                continue;
3558            }
3559
3560            // Iterate over all of the actions of this result's intent
3561            // filter...  typically this should be just one.
3562            final Iterator<String> it = rii.filter.actionsIterator();
3563            if (it == null) {
3564                continue;
3565            }
3566            while (it.hasNext()) {
3567                final String action = it.next();
3568                if (resultsAction != null && resultsAction.equals(action)) {
3569                    // If this action was explicitly requested, then don't
3570                    // remove things that have it.
3571                    continue;
3572                }
3573                for (int j=i+1; j<N; j++) {
3574                    final ResolveInfo rij = results.get(j);
3575                    if (rij.filter != null && rij.filter.hasAction(action)) {
3576                        results.remove(j);
3577                        if (DEBUG_INTENT_MATCHING) Log.v(
3578                            TAG, "Removing duplicate item from " + j
3579                            + " due to action " + action + " at " + i);
3580                        j--;
3581                        N--;
3582                    }
3583                }
3584            }
3585
3586            // If the caller didn't request filter information, drop it now
3587            // so we don't have to marshall/unmarshall it.
3588            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3589                rii.filter = null;
3590            }
3591        }
3592
3593        // Filter out the caller activity if so requested.
3594        if (caller != null) {
3595            N = results.size();
3596            for (int i=0; i<N; i++) {
3597                ActivityInfo ainfo = results.get(i).activityInfo;
3598                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3599                        && caller.getClassName().equals(ainfo.name)) {
3600                    results.remove(i);
3601                    break;
3602                }
3603            }
3604        }
3605
3606        // If the caller didn't request filter information,
3607        // drop them now so we don't have to
3608        // marshall/unmarshall it.
3609        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3610            N = results.size();
3611            for (int i=0; i<N; i++) {
3612                results.get(i).filter = null;
3613            }
3614        }
3615
3616        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3617        return results;
3618    }
3619
3620    @Override
3621    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3622            int userId) {
3623        if (!sUserManager.exists(userId)) return Collections.emptyList();
3624        ComponentName comp = intent.getComponent();
3625        if (comp == null) {
3626            if (intent.getSelector() != null) {
3627                intent = intent.getSelector();
3628                comp = intent.getComponent();
3629            }
3630        }
3631        if (comp != null) {
3632            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3633            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3634            if (ai != null) {
3635                ResolveInfo ri = new ResolveInfo();
3636                ri.activityInfo = ai;
3637                list.add(ri);
3638            }
3639            return list;
3640        }
3641
3642        // reader
3643        synchronized (mPackages) {
3644            String pkgName = intent.getPackage();
3645            if (pkgName == null) {
3646                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3647            }
3648            final PackageParser.Package pkg = mPackages.get(pkgName);
3649            if (pkg != null) {
3650                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3651                        userId);
3652            }
3653            return null;
3654        }
3655    }
3656
3657    @Override
3658    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3659        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3660        if (!sUserManager.exists(userId)) return null;
3661        if (query != null) {
3662            if (query.size() >= 1) {
3663                // If there is more than one service with the same priority,
3664                // just arbitrarily pick the first one.
3665                return query.get(0);
3666            }
3667        }
3668        return null;
3669    }
3670
3671    @Override
3672    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3673            int userId) {
3674        if (!sUserManager.exists(userId)) return Collections.emptyList();
3675        ComponentName comp = intent.getComponent();
3676        if (comp == null) {
3677            if (intent.getSelector() != null) {
3678                intent = intent.getSelector();
3679                comp = intent.getComponent();
3680            }
3681        }
3682        if (comp != null) {
3683            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3684            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3685            if (si != null) {
3686                final ResolveInfo ri = new ResolveInfo();
3687                ri.serviceInfo = si;
3688                list.add(ri);
3689            }
3690            return list;
3691        }
3692
3693        // reader
3694        synchronized (mPackages) {
3695            String pkgName = intent.getPackage();
3696            if (pkgName == null) {
3697                return mServices.queryIntent(intent, resolvedType, flags, userId);
3698            }
3699            final PackageParser.Package pkg = mPackages.get(pkgName);
3700            if (pkg != null) {
3701                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3702                        userId);
3703            }
3704            return null;
3705        }
3706    }
3707
3708    @Override
3709    public List<ResolveInfo> queryIntentContentProviders(
3710            Intent intent, String resolvedType, int flags, int userId) {
3711        if (!sUserManager.exists(userId)) return Collections.emptyList();
3712        ComponentName comp = intent.getComponent();
3713        if (comp == null) {
3714            if (intent.getSelector() != null) {
3715                intent = intent.getSelector();
3716                comp = intent.getComponent();
3717            }
3718        }
3719        if (comp != null) {
3720            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3721            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3722            if (pi != null) {
3723                final ResolveInfo ri = new ResolveInfo();
3724                ri.providerInfo = pi;
3725                list.add(ri);
3726            }
3727            return list;
3728        }
3729
3730        // reader
3731        synchronized (mPackages) {
3732            String pkgName = intent.getPackage();
3733            if (pkgName == null) {
3734                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3735            }
3736            final PackageParser.Package pkg = mPackages.get(pkgName);
3737            if (pkg != null) {
3738                return mProviders.queryIntentForPackage(
3739                        intent, resolvedType, flags, pkg.providers, userId);
3740            }
3741            return null;
3742        }
3743    }
3744
3745    @Override
3746    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3747        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3748
3749        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "get installed packages");
3750
3751        // writer
3752        synchronized (mPackages) {
3753            ArrayList<PackageInfo> list;
3754            if (listUninstalled) {
3755                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3756                for (PackageSetting ps : mSettings.mPackages.values()) {
3757                    PackageInfo pi;
3758                    if (ps.pkg != null) {
3759                        pi = generatePackageInfo(ps.pkg, flags, userId);
3760                    } else {
3761                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3762                    }
3763                    if (pi != null) {
3764                        list.add(pi);
3765                    }
3766                }
3767            } else {
3768                list = new ArrayList<PackageInfo>(mPackages.size());
3769                for (PackageParser.Package p : mPackages.values()) {
3770                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3771                    if (pi != null) {
3772                        list.add(pi);
3773                    }
3774                }
3775            }
3776
3777            return new ParceledListSlice<PackageInfo>(list);
3778        }
3779    }
3780
3781    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3782            String[] permissions, boolean[] tmp, int flags, int userId) {
3783        int numMatch = 0;
3784        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3785        for (int i=0; i<permissions.length; i++) {
3786            if (gp.grantedPermissions.contains(permissions[i])) {
3787                tmp[i] = true;
3788                numMatch++;
3789            } else {
3790                tmp[i] = false;
3791            }
3792        }
3793        if (numMatch == 0) {
3794            return;
3795        }
3796        PackageInfo pi;
3797        if (ps.pkg != null) {
3798            pi = generatePackageInfo(ps.pkg, flags, userId);
3799        } else {
3800            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3801        }
3802        if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3803            if (numMatch == permissions.length) {
3804                pi.requestedPermissions = permissions;
3805            } else {
3806                pi.requestedPermissions = new String[numMatch];
3807                numMatch = 0;
3808                for (int i=0; i<permissions.length; i++) {
3809                    if (tmp[i]) {
3810                        pi.requestedPermissions[numMatch] = permissions[i];
3811                        numMatch++;
3812                    }
3813                }
3814            }
3815        }
3816        list.add(pi);
3817    }
3818
3819    @Override
3820    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3821            String[] permissions, int flags, int userId) {
3822        if (!sUserManager.exists(userId)) return null;
3823        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3824
3825        // writer
3826        synchronized (mPackages) {
3827            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3828            boolean[] tmpBools = new boolean[permissions.length];
3829            if (listUninstalled) {
3830                for (PackageSetting ps : mSettings.mPackages.values()) {
3831                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3832                }
3833            } else {
3834                for (PackageParser.Package pkg : mPackages.values()) {
3835                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3836                    if (ps != null) {
3837                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3838                                userId);
3839                    }
3840                }
3841            }
3842
3843            return new ParceledListSlice<PackageInfo>(list);
3844        }
3845    }
3846
3847    @Override
3848    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3849        if (!sUserManager.exists(userId)) return null;
3850        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3851
3852        // writer
3853        synchronized (mPackages) {
3854            ArrayList<ApplicationInfo> list;
3855            if (listUninstalled) {
3856                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3857                for (PackageSetting ps : mSettings.mPackages.values()) {
3858                    ApplicationInfo ai;
3859                    if (ps.pkg != null) {
3860                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3861                                ps.readUserState(userId), userId);
3862                    } else {
3863                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3864                    }
3865                    if (ai != null) {
3866                        list.add(ai);
3867                    }
3868                }
3869            } else {
3870                list = new ArrayList<ApplicationInfo>(mPackages.size());
3871                for (PackageParser.Package p : mPackages.values()) {
3872                    if (p.mExtras != null) {
3873                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3874                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3875                        if (ai != null) {
3876                            list.add(ai);
3877                        }
3878                    }
3879                }
3880            }
3881
3882            return new ParceledListSlice<ApplicationInfo>(list);
3883        }
3884    }
3885
3886    public List<ApplicationInfo> getPersistentApplications(int flags) {
3887        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3888
3889        // reader
3890        synchronized (mPackages) {
3891            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3892            final int userId = UserHandle.getCallingUserId();
3893            while (i.hasNext()) {
3894                final PackageParser.Package p = i.next();
3895                if (p.applicationInfo != null
3896                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3897                        && (!mSafeMode || isSystemApp(p))) {
3898                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3899                    if (ps != null) {
3900                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3901                                ps.readUserState(userId), userId);
3902                        if (ai != null) {
3903                            finalList.add(ai);
3904                        }
3905                    }
3906                }
3907            }
3908        }
3909
3910        return finalList;
3911    }
3912
3913    @Override
3914    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3915        if (!sUserManager.exists(userId)) return null;
3916        // reader
3917        synchronized (mPackages) {
3918            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3919            PackageSetting ps = provider != null
3920                    ? mSettings.mPackages.get(provider.owner.packageName)
3921                    : null;
3922            return ps != null
3923                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3924                    && (!mSafeMode || (provider.info.applicationInfo.flags
3925                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3926                    ? PackageParser.generateProviderInfo(provider, flags,
3927                            ps.readUserState(userId), userId)
3928                    : null;
3929        }
3930    }
3931
3932    /**
3933     * @deprecated
3934     */
3935    @Deprecated
3936    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3937        // reader
3938        synchronized (mPackages) {
3939            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3940                    .entrySet().iterator();
3941            final int userId = UserHandle.getCallingUserId();
3942            while (i.hasNext()) {
3943                Map.Entry<String, PackageParser.Provider> entry = i.next();
3944                PackageParser.Provider p = entry.getValue();
3945                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3946
3947                if (ps != null && p.syncable
3948                        && (!mSafeMode || (p.info.applicationInfo.flags
3949                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3950                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3951                            ps.readUserState(userId), userId);
3952                    if (info != null) {
3953                        outNames.add(entry.getKey());
3954                        outInfo.add(info);
3955                    }
3956                }
3957            }
3958        }
3959    }
3960
3961    @Override
3962    public List<ProviderInfo> queryContentProviders(String processName,
3963            int uid, int flags) {
3964        ArrayList<ProviderInfo> finalList = null;
3965        // reader
3966        synchronized (mPackages) {
3967            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3968            final int userId = processName != null ?
3969                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3970            while (i.hasNext()) {
3971                final PackageParser.Provider p = i.next();
3972                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3973                if (ps != null && p.info.authority != null
3974                        && (processName == null
3975                                || (p.info.processName.equals(processName)
3976                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3977                        && mSettings.isEnabledLPr(p.info, flags, userId)
3978                        && (!mSafeMode
3979                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3980                    if (finalList == null) {
3981                        finalList = new ArrayList<ProviderInfo>(3);
3982                    }
3983                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3984                            ps.readUserState(userId), userId);
3985                    if (info != null) {
3986                        finalList.add(info);
3987                    }
3988                }
3989            }
3990        }
3991
3992        if (finalList != null) {
3993            Collections.sort(finalList, mProviderInitOrderSorter);
3994        }
3995
3996        return finalList;
3997    }
3998
3999    @Override
4000    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4001            int flags) {
4002        // reader
4003        synchronized (mPackages) {
4004            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4005            return PackageParser.generateInstrumentationInfo(i, flags);
4006        }
4007    }
4008
4009    @Override
4010    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4011            int flags) {
4012        ArrayList<InstrumentationInfo> finalList =
4013            new ArrayList<InstrumentationInfo>();
4014
4015        // reader
4016        synchronized (mPackages) {
4017            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4018            while (i.hasNext()) {
4019                final PackageParser.Instrumentation p = i.next();
4020                if (targetPackage == null
4021                        || targetPackage.equals(p.info.targetPackage)) {
4022                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4023                            flags);
4024                    if (ii != null) {
4025                        finalList.add(ii);
4026                    }
4027                }
4028            }
4029        }
4030
4031        return finalList;
4032    }
4033
4034    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4035        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4036        if (overlays == null) {
4037            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4038            return;
4039        }
4040        for (PackageParser.Package opkg : overlays.values()) {
4041            // Not much to do if idmap fails: we already logged the error
4042            // and we certainly don't want to abort installation of pkg simply
4043            // because an overlay didn't fit properly. For these reasons,
4044            // ignore the return value of createIdmapForPackagePairLI.
4045            createIdmapForPackagePairLI(pkg, opkg);
4046        }
4047    }
4048
4049    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4050            PackageParser.Package opkg) {
4051        if (!opkg.mTrustedOverlay) {
4052            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4053                    opkg.baseCodePath + ": overlay not trusted");
4054            return false;
4055        }
4056        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4057        if (overlaySet == null) {
4058            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4059                    opkg.baseCodePath + " but target package has no known overlays");
4060            return false;
4061        }
4062        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4063        // TODO: generate idmap for split APKs
4064        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4065            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4066                    + opkg.baseCodePath);
4067            return false;
4068        }
4069        PackageParser.Package[] overlayArray =
4070            overlaySet.values().toArray(new PackageParser.Package[0]);
4071        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4072            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4073                return p1.mOverlayPriority - p2.mOverlayPriority;
4074            }
4075        };
4076        Arrays.sort(overlayArray, cmp);
4077
4078        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4079        int i = 0;
4080        for (PackageParser.Package p : overlayArray) {
4081            pkg.applicationInfo.resourceDirs[i++] = p.applicationInfo.sourceDir;
4082        }
4083        return true;
4084    }
4085
4086    private void scanDirLI(File dir, int flags, int scanMode, long currentTime) {
4087        final File[] files = dir.listFiles();
4088        if (ArrayUtils.isEmpty(files)) {
4089            Log.d(TAG, "No files in app dir " + dir);
4090            return;
4091        }
4092
4093        if (DEBUG_PACKAGE_SCANNING) {
4094            Log.d(TAG, "Scanning app dir " + dir + " scanMode=" + scanMode
4095                    + " flags=0x" + Integer.toHexString(flags));
4096        }
4097
4098        for (File file : files) {
4099            if (!isApkFile(file)) {
4100                // Ignore entries which are not apk's
4101                continue;
4102            }
4103            PackageParser.Package pkg = scanPackageLI(file,
4104                    flags|PackageParser.PARSE_MUST_BE_APK, scanMode, currentTime, null, null);
4105            // Don't mess around with apps in system partition.
4106            if (pkg == null && (flags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4107                    mLastScanError == PackageManager.INSTALL_FAILED_INVALID_APK) {
4108                // Delete the apk
4109                Slog.w(TAG, "Cleaning up failed install of " + file);
4110                file.delete();
4111            }
4112        }
4113    }
4114
4115    private static File getSettingsProblemFile() {
4116        File dataDir = Environment.getDataDirectory();
4117        File systemDir = new File(dataDir, "system");
4118        File fname = new File(systemDir, "uiderrors.txt");
4119        return fname;
4120    }
4121
4122    static void reportSettingsProblem(int priority, String msg) {
4123        try {
4124            File fname = getSettingsProblemFile();
4125            FileOutputStream out = new FileOutputStream(fname, true);
4126            PrintWriter pw = new FastPrintWriter(out);
4127            SimpleDateFormat formatter = new SimpleDateFormat();
4128            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4129            pw.println(dateString + ": " + msg);
4130            pw.close();
4131            FileUtils.setPermissions(
4132                    fname.toString(),
4133                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4134                    -1, -1);
4135        } catch (java.io.IOException e) {
4136        }
4137        Slog.println(priority, TAG, msg);
4138    }
4139
4140    private boolean collectCertificatesLI(PackageParser pp, PackageSetting ps,
4141            PackageParser.Package pkg, File srcFile, int parseFlags) {
4142        if (ps != null
4143                && ps.codePath.equals(srcFile)
4144                && ps.timeStamp == srcFile.lastModified()
4145                && !isCompatSignatureUpdateNeeded(pkg)) {
4146            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4147            if (ps.signatures.mSignatures != null
4148                    && ps.signatures.mSignatures.length != 0
4149                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4150                // Optimization: reuse the existing cached certificates
4151                // if the package appears to be unchanged.
4152                pkg.mSignatures = ps.signatures.mSignatures;
4153                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4154                pkg.mSigningKeys = ksms.getPublicKeysFromKeySet(mSigningKeySetId);
4155                return true;
4156            }
4157
4158            Slog.w(TAG, "PackageSetting for " + ps.name + " is missing signatures.  Collecting certs again to recover them.");
4159        } else {
4160            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4161        }
4162
4163        try {
4164            pp.collectCertificates(pkg, parseFlags);
4165            pp.collectManifestDigest(pkg);
4166        } catch (PackageParserException e) {
4167            mLastScanError = e.error;
4168            return false;
4169        }
4170        return true;
4171    }
4172
4173    /*
4174     *  Scan a package and return the newly parsed package.
4175     *  Returns null in case of errors and the error code is stored in mLastScanError
4176     */
4177    private PackageParser.Package scanPackageLI(File scanFile,
4178            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
4179        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
4180        String scanPath = scanFile.getPath();
4181        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanPath);
4182        parseFlags |= mDefParseFlags;
4183        PackageParser pp = new PackageParser();
4184        pp.setSeparateProcesses(mSeparateProcesses);
4185        pp.setOnlyCoreApps(mOnlyCore);
4186        pp.setDisplayMetrics(mMetrics);
4187
4188        if ((scanMode & SCAN_TRUSTED_OVERLAY) != 0) {
4189            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4190        }
4191
4192        final PackageParser.Package pkg;
4193        try {
4194            pkg = pp.parseMonolithicPackage(scanFile, parseFlags);
4195        } catch (PackageParserException e) {
4196            mLastScanError = e.error;
4197            return null;
4198        }
4199
4200        PackageSetting ps = null;
4201        PackageSetting updatedPkg;
4202        // reader
4203        synchronized (mPackages) {
4204            // Look to see if we already know about this package.
4205            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4206            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4207                // This package has been renamed to its original name.  Let's
4208                // use that.
4209                ps = mSettings.peekPackageLPr(oldName);
4210            }
4211            // If there was no original package, see one for the real package name.
4212            if (ps == null) {
4213                ps = mSettings.peekPackageLPr(pkg.packageName);
4214            }
4215            // Check to see if this package could be hiding/updating a system
4216            // package.  Must look for it either under the original or real
4217            // package name depending on our state.
4218            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4219            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4220        }
4221        boolean updatedPkgBetter = false;
4222        // First check if this is a system package that may involve an update
4223        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4224            if (ps != null && !ps.codePath.equals(scanFile)) {
4225                // The path has changed from what was last scanned...  check the
4226                // version of the new path against what we have stored to determine
4227                // what to do.
4228                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4229                if (pkg.mVersionCode < ps.versionCode) {
4230                    // The system package has been updated and the code path does not match
4231                    // Ignore entry. Skip it.
4232                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4233                            + " ignored: updated version " + ps.versionCode
4234                            + " better than this " + pkg.mVersionCode);
4235                    if (!updatedPkg.codePath.equals(scanFile)) {
4236                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4237                                + ps.name + " changing from " + updatedPkg.codePathString
4238                                + " to " + scanFile);
4239                        updatedPkg.codePath = scanFile;
4240                        updatedPkg.codePathString = scanFile.toString();
4241                        // This is the point at which we know that the system-disk APK
4242                        // for this package has moved during a reboot (e.g. due to an OTA),
4243                        // so we need to reevaluate it for privilege policy.
4244                        if (locationIsPrivileged(scanFile)) {
4245                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4246                        }
4247                    }
4248                    updatedPkg.pkg = pkg;
4249                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4250                    return null;
4251                } else {
4252                    // The current app on the system partition is better than
4253                    // what we have updated to on the data partition; switch
4254                    // back to the system partition version.
4255                    // At this point, its safely assumed that package installation for
4256                    // apps in system partition will go through. If not there won't be a working
4257                    // version of the app
4258                    // writer
4259                    synchronized (mPackages) {
4260                        // Just remove the loaded entries from package lists.
4261                        mPackages.remove(ps.name);
4262                    }
4263                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4264                            + "reverting from " + ps.codePathString
4265                            + ": new version " + pkg.mVersionCode
4266                            + " better than installed " + ps.versionCode);
4267
4268                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4269                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4270                            getAppInstructionSetFromSettings(ps));
4271                    synchronized (mInstallLock) {
4272                        args.cleanUpResourcesLI();
4273                    }
4274                    synchronized (mPackages) {
4275                        mSettings.enableSystemPackageLPw(ps.name);
4276                    }
4277                    updatedPkgBetter = true;
4278                }
4279            }
4280        }
4281
4282        if (updatedPkg != null) {
4283            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4284            // initially
4285            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4286
4287            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4288            // flag set initially
4289            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4290                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4291            }
4292        }
4293        // Verify certificates against what was last scanned
4294        if (!collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags)) {
4295            Slog.w(TAG, "Failed verifying certificates for package:" + pkg.packageName);
4296            return null;
4297        }
4298
4299        /*
4300         * A new system app appeared, but we already had a non-system one of the
4301         * same name installed earlier.
4302         */
4303        boolean shouldHideSystemApp = false;
4304        if (updatedPkg == null && ps != null
4305                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4306            /*
4307             * Check to make sure the signatures match first. If they don't,
4308             * wipe the installed application and its data.
4309             */
4310            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4311                    != PackageManager.SIGNATURE_MATCH) {
4312                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4313                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4314                ps = null;
4315            } else {
4316                /*
4317                 * If the newly-added system app is an older version than the
4318                 * already installed version, hide it. It will be scanned later
4319                 * and re-added like an update.
4320                 */
4321                if (pkg.mVersionCode < ps.versionCode) {
4322                    shouldHideSystemApp = true;
4323                } else {
4324                    /*
4325                     * The newly found system app is a newer version that the
4326                     * one previously installed. Simply remove the
4327                     * already-installed application and replace it with our own
4328                     * while keeping the application data.
4329                     */
4330                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4331                            + ps.codePathString + ": new version " + pkg.mVersionCode
4332                            + " better than installed " + ps.versionCode);
4333                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4334                            ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
4335                            getAppInstructionSetFromSettings(ps));
4336                    synchronized (mInstallLock) {
4337                        args.cleanUpResourcesLI();
4338                    }
4339                }
4340            }
4341        }
4342
4343        // The apk is forward locked (not public) if its code and resources
4344        // are kept in different files. (except for app in either system or
4345        // vendor path).
4346        // TODO grab this value from PackageSettings
4347        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4348            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4349                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4350            }
4351        }
4352
4353        final String baseCodePath = pkg.baseCodePath;
4354        final String[] splitCodePaths = pkg.splitCodePaths;
4355
4356        // TODO: extend to support forward-locked splits
4357        String baseResPath = null;
4358        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4359            if (ps != null && ps.resourcePathString != null) {
4360                baseResPath = ps.resourcePathString;
4361            } else {
4362                // Should not happen at all. Just log an error.
4363                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4364            }
4365        } else {
4366            baseResPath = pkg.baseCodePath;
4367        }
4368
4369        // Set application objects path explicitly.
4370        pkg.applicationInfo.sourceDir = baseCodePath;
4371        pkg.applicationInfo.publicSourceDir = baseResPath;
4372        pkg.applicationInfo.splitSourceDirs = splitCodePaths;
4373        pkg.applicationInfo.splitPublicSourceDirs = splitCodePaths;
4374
4375        // Note that we invoke the following method only if we are about to unpack an application
4376        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanMode
4377                | SCAN_UPDATE_SIGNATURE, currentTime, user, abiOverride);
4378
4379        /*
4380         * If the system app should be overridden by a previously installed
4381         * data, hide the system app now and let the /data/app scan pick it up
4382         * again.
4383         */
4384        if (shouldHideSystemApp) {
4385            synchronized (mPackages) {
4386                /*
4387                 * We have to grant systems permissions before we hide, because
4388                 * grantPermissions will assume the package update is trying to
4389                 * expand its permissions.
4390                 */
4391                grantPermissionsLPw(pkg, true);
4392                mSettings.disableSystemPackageLPw(pkg.packageName);
4393            }
4394        }
4395
4396        return scannedPkg;
4397    }
4398
4399    private static String fixProcessName(String defProcessName,
4400            String processName, int uid) {
4401        if (processName == null) {
4402            return defProcessName;
4403        }
4404        return processName;
4405    }
4406
4407    private boolean verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) {
4408        if (pkgSetting.signatures.mSignatures != null) {
4409            // Already existing package. Make sure signatures match
4410            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4411                    == PackageManager.SIGNATURE_MATCH;
4412            if (!match) {
4413                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4414                        == PackageManager.SIGNATURE_MATCH;
4415            }
4416            if (!match) {
4417                Slog.e(TAG, "Package " + pkg.packageName
4418                        + " signatures do not match the previously installed version; ignoring!");
4419                mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
4420                return false;
4421            }
4422        }
4423
4424        // Check for shared user signatures
4425        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4426            // Already existing package. Make sure signatures match
4427            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4428                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4429            if (!match) {
4430                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4431                        == PackageManager.SIGNATURE_MATCH;
4432            }
4433            if (!match) {
4434                Slog.e(TAG, "Package " + pkg.packageName
4435                        + " has no signatures that match those in shared user "
4436                        + pkgSetting.sharedUser.name + "; ignoring!");
4437                mLastScanError = PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
4438                return false;
4439            }
4440        }
4441        return true;
4442    }
4443
4444    /**
4445     * Enforces that only the system UID or root's UID can call a method exposed
4446     * via Binder.
4447     *
4448     * @param message used as message if SecurityException is thrown
4449     * @throws SecurityException if the caller is not system or root
4450     */
4451    private static final void enforceSystemOrRoot(String message) {
4452        final int uid = Binder.getCallingUid();
4453        if (uid != Process.SYSTEM_UID && uid != 0) {
4454            throw new SecurityException(message);
4455        }
4456    }
4457
4458    @Override
4459    public void performBootDexOpt() {
4460        enforceSystemOrRoot("Only the system can request dexopt be performed");
4461
4462        final HashSet<PackageParser.Package> pkgs;
4463        synchronized (mPackages) {
4464            pkgs = mDeferredDexOpt;
4465            mDeferredDexOpt = null;
4466        }
4467
4468        if (pkgs != null) {
4469            // Filter out packages that aren't recently used.
4470            //
4471            // The exception is first boot of a non-eng device, which
4472            // should do a full dexopt.
4473            boolean eng = "eng".equals(SystemProperties.get("ro.build.type"));
4474            if (eng || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4475                // TODO: add a property to control this?
4476                long dexOptLRUThresholdInMinutes;
4477                if (eng) {
4478                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4479                } else {
4480                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4481                }
4482                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4483
4484                int total = pkgs.size();
4485                int skipped = 0;
4486                long now = System.currentTimeMillis();
4487                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4488                    PackageParser.Package pkg = i.next();
4489                    long then = pkg.mLastPackageUsageTimeInMills;
4490                    if (then + dexOptLRUThresholdInMills < now) {
4491                        if (DEBUG_DEXOPT) {
4492                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4493                                  ((then == 0) ? "never" : new Date(then)));
4494                        }
4495                        i.remove();
4496                        skipped++;
4497                    }
4498                }
4499                if (DEBUG_DEXOPT) {
4500                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4501                }
4502            }
4503
4504            int i = 0;
4505            for (PackageParser.Package pkg : pkgs) {
4506                i++;
4507                if (DEBUG_DEXOPT) {
4508                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4509                          + ": " + pkg.packageName);
4510                }
4511                if (!isFirstBoot()) {
4512                    try {
4513                        ActivityManagerNative.getDefault().showBootMessage(
4514                                mContext.getResources().getString(
4515                                        R.string.android_upgrading_apk,
4516                                        i, pkgs.size()), true);
4517                    } catch (RemoteException e) {
4518                    }
4519                }
4520                PackageParser.Package p = pkg;
4521                synchronized (mInstallLock) {
4522                    if (p.mDexOptNeeded) {
4523                        performDexOptLI(p, false /* force dex */, false /* defer */,
4524                                true /* include dependencies */);
4525                    }
4526                }
4527            }
4528        }
4529    }
4530
4531    @Override
4532    public boolean performDexOpt(String packageName) {
4533        enforceSystemOrRoot("Only the system can request dexopt be performed");
4534        return performDexOpt(packageName, true);
4535    }
4536
4537    public boolean performDexOpt(String packageName, boolean updateUsage) {
4538
4539        PackageParser.Package p;
4540        synchronized (mPackages) {
4541            p = mPackages.get(packageName);
4542            if (p == null) {
4543                return false;
4544            }
4545            if (updateUsage) {
4546                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4547            }
4548            mPackageUsage.write(false);
4549            if (!p.mDexOptNeeded) {
4550                return false;
4551            }
4552        }
4553
4554        synchronized (mInstallLock) {
4555            return performDexOptLI(p, false /* force dex */, false /* defer */,
4556                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4557        }
4558    }
4559
4560    public HashSet<String> getPackagesThatNeedDexOpt() {
4561        HashSet<String> pkgs = null;
4562        synchronized (mPackages) {
4563            for (PackageParser.Package p : mPackages.values()) {
4564                if (DEBUG_DEXOPT) {
4565                    Log.i(TAG, p.packageName + " mDexOptNeeded=" + p.mDexOptNeeded);
4566                }
4567                if (!p.mDexOptNeeded) {
4568                    continue;
4569                }
4570                if (pkgs == null) {
4571                    pkgs = new HashSet<String>();
4572                }
4573                pkgs.add(p.packageName);
4574            }
4575        }
4576        return pkgs;
4577    }
4578
4579    public void shutdown() {
4580        mPackageUsage.write(true);
4581    }
4582
4583    private void performDexOptLibsLI(ArrayList<String> libs, String instructionSet,
4584             boolean forceDex, boolean defer, HashSet<String> done) {
4585        for (int i=0; i<libs.size(); i++) {
4586            PackageParser.Package libPkg;
4587            String libName;
4588            synchronized (mPackages) {
4589                libName = libs.get(i);
4590                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4591                if (lib != null && lib.apk != null) {
4592                    libPkg = mPackages.get(lib.apk);
4593                } else {
4594                    libPkg = null;
4595                }
4596            }
4597            if (libPkg != null && !done.contains(libName)) {
4598                performDexOptLI(libPkg, instructionSet, forceDex, defer, done);
4599            }
4600        }
4601    }
4602
4603    static final int DEX_OPT_SKIPPED = 0;
4604    static final int DEX_OPT_PERFORMED = 1;
4605    static final int DEX_OPT_DEFERRED = 2;
4606    static final int DEX_OPT_FAILED = -1;
4607
4608    private int performDexOptLI(PackageParser.Package pkg, String instructionSetOverride,
4609            boolean forceDex, boolean defer, HashSet<String> done) {
4610        final String instructionSet = instructionSetOverride != null ?
4611                instructionSetOverride : getAppInstructionSet(pkg.applicationInfo);
4612
4613        if (done != null) {
4614            done.add(pkg.packageName);
4615            if (pkg.usesLibraries != null) {
4616                performDexOptLibsLI(pkg.usesLibraries, instructionSet, forceDex, defer, done);
4617            }
4618            if (pkg.usesOptionalLibraries != null) {
4619                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSet, forceDex, defer, done);
4620            }
4621        }
4622
4623        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0) {
4624            final Collection<String> paths = pkg.getAllCodePaths();
4625            for (String path : paths) {
4626                try {
4627                    boolean isDexOptNeededInternal = DexFile.isDexOptNeededInternal(path,
4628                            pkg.packageName, instructionSet, defer);
4629                    // There are three basic cases here:
4630                    // 1.) we need to dexopt, either because we are forced or it is needed
4631                    // 2.) we are defering a needed dexopt
4632                    // 3.) we are skipping an unneeded dexopt
4633                    if (forceDex || (!defer && isDexOptNeededInternal)) {
4634                        Log.i(TAG, "Running dexopt on: " + pkg.applicationInfo.packageName);
4635                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4636                        int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4637                                                    pkg.packageName, instructionSet);
4638                        // Note that we ran dexopt, since rerunning will
4639                        // probably just result in an error again.
4640                        pkg.mDexOptNeeded = false;
4641                        if (ret < 0) {
4642                            return DEX_OPT_FAILED;
4643                        }
4644                        return DEX_OPT_PERFORMED;
4645                    }
4646                    if (defer && isDexOptNeededInternal) {
4647                        if (mDeferredDexOpt == null) {
4648                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4649                        }
4650                        mDeferredDexOpt.add(pkg);
4651                        return DEX_OPT_DEFERRED;
4652                    }
4653                    pkg.mDexOptNeeded = false;
4654                    return DEX_OPT_SKIPPED;
4655                } catch (FileNotFoundException e) {
4656                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4657                    return DEX_OPT_FAILED;
4658                } catch (IOException e) {
4659                    Slog.w(TAG, "IOException reading apk: " + path, e);
4660                    return DEX_OPT_FAILED;
4661                } catch (StaleDexCacheError e) {
4662                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4663                    return DEX_OPT_FAILED;
4664                } catch (Exception e) {
4665                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4666                    return DEX_OPT_FAILED;
4667                }
4668            }
4669        }
4670        return DEX_OPT_SKIPPED;
4671    }
4672
4673    private String getAppInstructionSet(ApplicationInfo info) {
4674        String instructionSet = getPreferredInstructionSet();
4675
4676        if (info.cpuAbi != null) {
4677            instructionSet = VMRuntime.getInstructionSet(info.cpuAbi);
4678        }
4679
4680        return instructionSet;
4681    }
4682
4683    private String getAppInstructionSetFromSettings(PackageSetting ps) {
4684        String instructionSet = getPreferredInstructionSet();
4685
4686        if (ps.cpuAbiString != null) {
4687            instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
4688        }
4689
4690        return instructionSet;
4691    }
4692
4693    private static String getPreferredInstructionSet() {
4694        if (sPreferredInstructionSet == null) {
4695            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4696        }
4697
4698        return sPreferredInstructionSet;
4699    }
4700
4701    private static List<String> getAllInstructionSets() {
4702        final String[] allAbis = Build.SUPPORTED_ABIS;
4703        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4704
4705        for (String abi : allAbis) {
4706            final String instructionSet = VMRuntime.getInstructionSet(abi);
4707            if (!allInstructionSets.contains(instructionSet)) {
4708                allInstructionSets.add(instructionSet);
4709            }
4710        }
4711
4712        return allInstructionSets;
4713    }
4714
4715    private int performDexOptLI(PackageParser.Package pkg, boolean forceDex, boolean defer,
4716            boolean inclDependencies) {
4717        HashSet<String> done;
4718        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4719            done = new HashSet<String>();
4720            done.add(pkg.packageName);
4721        } else {
4722            done = null;
4723        }
4724        return performDexOptLI(pkg, null /* instruction set override */,  forceDex, defer, done);
4725    }
4726
4727    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4728        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4729            Slog.w(TAG, "Unable to update from " + oldPkg.name
4730                    + " to " + newPkg.packageName
4731                    + ": old package not in system partition");
4732            return false;
4733        } else if (mPackages.get(oldPkg.name) != null) {
4734            Slog.w(TAG, "Unable to update from " + oldPkg.name
4735                    + " to " + newPkg.packageName
4736                    + ": old package still exists");
4737            return false;
4738        }
4739        return true;
4740    }
4741
4742    File getDataPathForUser(int userId) {
4743        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4744    }
4745
4746    private File getDataPathForPackage(String packageName, int userId) {
4747        /*
4748         * Until we fully support multiple users, return the directory we
4749         * previously would have. The PackageManagerTests will need to be
4750         * revised when this is changed back..
4751         */
4752        if (userId == 0) {
4753            return new File(mAppDataDir, packageName);
4754        } else {
4755            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4756                + File.separator + packageName);
4757        }
4758    }
4759
4760    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4761        int[] users = sUserManager.getUserIds();
4762        int res = mInstaller.install(packageName, uid, uid, seinfo);
4763        if (res < 0) {
4764            return res;
4765        }
4766        for (int user : users) {
4767            if (user != 0) {
4768                res = mInstaller.createUserData(packageName,
4769                        UserHandle.getUid(user, uid), user, seinfo);
4770                if (res < 0) {
4771                    return res;
4772                }
4773            }
4774        }
4775        return res;
4776    }
4777
4778    private int removeDataDirsLI(String packageName) {
4779        int[] users = sUserManager.getUserIds();
4780        int res = 0;
4781        for (int user : users) {
4782            int resInner = mInstaller.remove(packageName, user);
4783            if (resInner < 0) {
4784                res = resInner;
4785            }
4786        }
4787
4788        final File nativeLibraryFile = new File(mAppLibInstallDir, packageName);
4789        NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
4790        if (!nativeLibraryFile.delete()) {
4791            Slog.w(TAG, "Couldn't delete native library directory " + nativeLibraryFile.getPath());
4792        }
4793
4794        return res;
4795    }
4796
4797    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4798            PackageParser.Package changingLib) {
4799        if (file.path != null) {
4800            usesLibraryFiles.add(file.path);
4801            return;
4802        }
4803        PackageParser.Package p = mPackages.get(file.apk);
4804        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4805            // If we are doing this while in the middle of updating a library apk,
4806            // then we need to make sure to use that new apk for determining the
4807            // dependencies here.  (We haven't yet finished committing the new apk
4808            // to the package manager state.)
4809            if (p == null || p.packageName.equals(changingLib.packageName)) {
4810                p = changingLib;
4811            }
4812        }
4813        if (p != null) {
4814            usesLibraryFiles.addAll(p.getAllCodePaths());
4815        }
4816    }
4817
4818    private boolean updateSharedLibrariesLPw(PackageParser.Package pkg,
4819            PackageParser.Package changingLib) {
4820        // We might be upgrading from a version of the platform that did not
4821        // provide per-package native library directories for system apps.
4822        // Fix that up here.
4823        if (isSystemApp(pkg)) {
4824            PackageSetting ps = mSettings.mPackages.get(pkg.applicationInfo.packageName);
4825            setInternalAppNativeLibraryPath(pkg, ps);
4826        }
4827
4828        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4829            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4830            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4831            for (int i=0; i<N; i++) {
4832                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4833                if (file == null) {
4834                    Slog.e(TAG, "Package " + pkg.packageName
4835                            + " requires unavailable shared library "
4836                            + pkg.usesLibraries.get(i) + "; failing!");
4837                    mLastScanError = PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
4838                    return false;
4839                }
4840                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4841            }
4842            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4843            for (int i=0; i<N; i++) {
4844                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4845                if (file == null) {
4846                    Slog.w(TAG, "Package " + pkg.packageName
4847                            + " desires unavailable shared library "
4848                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4849                } else {
4850                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4851                }
4852            }
4853            N = usesLibraryFiles.size();
4854            if (N > 0) {
4855                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4856            } else {
4857                pkg.usesLibraryFiles = null;
4858            }
4859        }
4860        return true;
4861    }
4862
4863    private static boolean hasString(List<String> list, List<String> which) {
4864        if (list == null) {
4865            return false;
4866        }
4867        for (int i=list.size()-1; i>=0; i--) {
4868            for (int j=which.size()-1; j>=0; j--) {
4869                if (which.get(j).equals(list.get(i))) {
4870                    return true;
4871                }
4872            }
4873        }
4874        return false;
4875    }
4876
4877    private void updateAllSharedLibrariesLPw() {
4878        for (PackageParser.Package pkg : mPackages.values()) {
4879            updateSharedLibrariesLPw(pkg, null);
4880        }
4881    }
4882
4883    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4884            PackageParser.Package changingPkg) {
4885        ArrayList<PackageParser.Package> res = null;
4886        for (PackageParser.Package pkg : mPackages.values()) {
4887            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4888                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4889                if (res == null) {
4890                    res = new ArrayList<PackageParser.Package>();
4891                }
4892                res.add(pkg);
4893                updateSharedLibrariesLPw(pkg, changingPkg);
4894            }
4895        }
4896        return res;
4897    }
4898
4899    private PackageParser.Package scanPackageLI(PackageParser.Package pkg,
4900            int parseFlags, int scanMode, long currentTime, UserHandle user, String abiOverride) {
4901        final File scanFile = new File(pkg.codePath);
4902        if (pkg.applicationInfo.sourceDir == null ||
4903                pkg.applicationInfo.publicSourceDir == null) {
4904            // Bail out. The resource and code paths haven't been set.
4905            Slog.w(TAG, " Code and resource paths haven't been set correctly");
4906            mLastScanError = PackageManager.INSTALL_FAILED_INVALID_APK;
4907            return null;
4908        }
4909
4910        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4911            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4912        }
4913
4914        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
4915            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
4916        }
4917
4918        if (mCustomResolverComponentName != null &&
4919                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
4920            setUpCustomResolverActivity(pkg);
4921        }
4922
4923        if (pkg.packageName.equals("android")) {
4924            synchronized (mPackages) {
4925                if (mAndroidApplication != null) {
4926                    Slog.w(TAG, "*************************************************");
4927                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
4928                    Slog.w(TAG, " file=" + scanFile);
4929                    Slog.w(TAG, "*************************************************");
4930                    mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4931                    return null;
4932                }
4933
4934                // Set up information for our fall-back user intent resolution activity.
4935                mPlatformPackage = pkg;
4936                pkg.mVersionCode = mSdkVersion;
4937                mAndroidApplication = pkg.applicationInfo;
4938
4939                if (!mResolverReplaced) {
4940                    mResolveActivity.applicationInfo = mAndroidApplication;
4941                    mResolveActivity.name = ResolverActivity.class.getName();
4942                    mResolveActivity.packageName = mAndroidApplication.packageName;
4943                    mResolveActivity.processName = "system:ui";
4944                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
4945                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
4946                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
4947                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
4948                    mResolveActivity.exported = true;
4949                    mResolveActivity.enabled = true;
4950                    mResolveInfo.activityInfo = mResolveActivity;
4951                    mResolveInfo.priority = 0;
4952                    mResolveInfo.preferredOrder = 0;
4953                    mResolveInfo.match = 0;
4954                    mResolveComponentName = new ComponentName(
4955                            mAndroidApplication.packageName, mResolveActivity.name);
4956                }
4957            }
4958        }
4959
4960        if (DEBUG_PACKAGE_SCANNING) {
4961            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4962                Log.d(TAG, "Scanning package " + pkg.packageName);
4963        }
4964
4965        if (mPackages.containsKey(pkg.packageName)
4966                || mSharedLibraries.containsKey(pkg.packageName)) {
4967            Slog.w(TAG, "Application package " + pkg.packageName
4968                    + " already installed.  Skipping duplicate.");
4969            mLastScanError = PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
4970            return null;
4971        }
4972
4973        // Initialize package source and resource directories
4974        File destCodeFile = new File(pkg.applicationInfo.sourceDir);
4975        File destResourceFile = new File(pkg.applicationInfo.publicSourceDir);
4976
4977        SharedUserSetting suid = null;
4978        PackageSetting pkgSetting = null;
4979
4980        if (!isSystemApp(pkg)) {
4981            // Only system apps can use these features.
4982            pkg.mOriginalPackages = null;
4983            pkg.mRealPackage = null;
4984            pkg.mAdoptPermissions = null;
4985        }
4986
4987        // writer
4988        synchronized (mPackages) {
4989            if (pkg.mSharedUserId != null) {
4990                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
4991                if (suid == null) {
4992                    Slog.w(TAG, "Creating application package " + pkg.packageName
4993                            + " for shared user failed");
4994                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
4995                    return null;
4996                }
4997                if (DEBUG_PACKAGE_SCANNING) {
4998                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
4999                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5000                                + "): packages=" + suid.packages);
5001                }
5002            }
5003
5004            // Check if we are renaming from an original package name.
5005            PackageSetting origPackage = null;
5006            String realName = null;
5007            if (pkg.mOriginalPackages != null) {
5008                // This package may need to be renamed to a previously
5009                // installed name.  Let's check on that...
5010                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5011                if (pkg.mOriginalPackages.contains(renamed)) {
5012                    // This package had originally been installed as the
5013                    // original name, and we have already taken care of
5014                    // transitioning to the new one.  Just update the new
5015                    // one to continue using the old name.
5016                    realName = pkg.mRealPackage;
5017                    if (!pkg.packageName.equals(renamed)) {
5018                        // Callers into this function may have already taken
5019                        // care of renaming the package; only do it here if
5020                        // it is not already done.
5021                        pkg.setPackageName(renamed);
5022                    }
5023
5024                } else {
5025                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5026                        if ((origPackage = mSettings.peekPackageLPr(
5027                                pkg.mOriginalPackages.get(i))) != null) {
5028                            // We do have the package already installed under its
5029                            // original name...  should we use it?
5030                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5031                                // New package is not compatible with original.
5032                                origPackage = null;
5033                                continue;
5034                            } else if (origPackage.sharedUser != null) {
5035                                // Make sure uid is compatible between packages.
5036                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5037                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5038                                            + " to " + pkg.packageName + ": old uid "
5039                                            + origPackage.sharedUser.name
5040                                            + " differs from " + pkg.mSharedUserId);
5041                                    origPackage = null;
5042                                    continue;
5043                                }
5044                            } else {
5045                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5046                                        + pkg.packageName + " to old name " + origPackage.name);
5047                            }
5048                            break;
5049                        }
5050                    }
5051                }
5052            }
5053
5054            if (mTransferedPackages.contains(pkg.packageName)) {
5055                Slog.w(TAG, "Package " + pkg.packageName
5056                        + " was transferred to another, but its .apk remains");
5057            }
5058
5059            // Just create the setting, don't add it yet. For already existing packages
5060            // the PkgSetting exists already and doesn't have to be created.
5061            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5062                    destResourceFile, pkg.applicationInfo.nativeLibraryDir,
5063                    pkg.applicationInfo.cpuAbi,
5064                    pkg.applicationInfo.flags, user, false);
5065            if (pkgSetting == null) {
5066                Slog.w(TAG, "Creating application package " + pkg.packageName + " failed");
5067                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5068                return null;
5069            }
5070
5071            if (pkgSetting.origPackage != null) {
5072                // If we are first transitioning from an original package,
5073                // fix up the new package's name now.  We need to do this after
5074                // looking up the package under its new name, so getPackageLP
5075                // can take care of fiddling things correctly.
5076                pkg.setPackageName(origPackage.name);
5077
5078                // File a report about this.
5079                String msg = "New package " + pkgSetting.realName
5080                        + " renamed to replace old package " + pkgSetting.name;
5081                reportSettingsProblem(Log.WARN, msg);
5082
5083                // Make a note of it.
5084                mTransferedPackages.add(origPackage.name);
5085
5086                // No longer need to retain this.
5087                pkgSetting.origPackage = null;
5088            }
5089
5090            if (realName != null) {
5091                // Make a note of it.
5092                mTransferedPackages.add(pkg.packageName);
5093            }
5094
5095            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5096                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5097            }
5098
5099            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5100                // Check all shared libraries and map to their actual file path.
5101                // We only do this here for apps not on a system dir, because those
5102                // are the only ones that can fail an install due to this.  We
5103                // will take care of the system apps by updating all of their
5104                // library paths after the scan is done.
5105                if (!updateSharedLibrariesLPw(pkg, null)) {
5106                    return null;
5107                }
5108            }
5109
5110            if (mFoundPolicyFile) {
5111                SELinuxMMAC.assignSeinfoValue(pkg);
5112            }
5113
5114            pkg.applicationInfo.uid = pkgSetting.appId;
5115            pkg.mExtras = pkgSetting;
5116            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5117                if (!verifySignaturesLP(pkgSetting, pkg)) {
5118                    if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5119                        return null;
5120                    }
5121                    // The signature has changed, but this package is in the system
5122                    // image...  let's recover!
5123                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5124                    // However...  if this package is part of a shared user, but it
5125                    // doesn't match the signature of the shared user, let's fail.
5126                    // What this means is that you can't change the signatures
5127                    // associated with an overall shared user, which doesn't seem all
5128                    // that unreasonable.
5129                    if (pkgSetting.sharedUser != null) {
5130                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5131                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5132                            Log.w(TAG, "Signature mismatch for shared user : " + pkgSetting.sharedUser);
5133                            mLastScanError = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
5134                            return null;
5135                        }
5136                    }
5137                    // File a report about this.
5138                    String msg = "System package " + pkg.packageName
5139                        + " signature changed; retaining data.";
5140                    reportSettingsProblem(Log.WARN, msg);
5141                }
5142            } else {
5143                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5144                    Slog.e(TAG, "Package " + pkg.packageName
5145                           + " upgrade keys do not match the previously installed version; ");
5146                    mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5147                    return null;
5148                } else {
5149                    // signatures may have changed as result of upgrade
5150                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5151                }
5152            }
5153            // Verify that this new package doesn't have any content providers
5154            // that conflict with existing packages.  Only do this if the
5155            // package isn't already installed, since we don't want to break
5156            // things that are installed.
5157            if ((scanMode&SCAN_NEW_INSTALL) != 0) {
5158                final int N = pkg.providers.size();
5159                int i;
5160                for (i=0; i<N; i++) {
5161                    PackageParser.Provider p = pkg.providers.get(i);
5162                    if (p.info.authority != null) {
5163                        String names[] = p.info.authority.split(";");
5164                        for (int j = 0; j < names.length; j++) {
5165                            if (mProvidersByAuthority.containsKey(names[j])) {
5166                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5167                                Slog.w(TAG, "Can't install because provider name " + names[j] +
5168                                        " (in package " + pkg.applicationInfo.packageName +
5169                                        ") is already used by "
5170                                        + ((other != null && other.getComponentName() != null)
5171                                                ? other.getComponentName().getPackageName() : "?"));
5172                                mLastScanError = PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
5173                                return null;
5174                            }
5175                        }
5176                    }
5177                }
5178            }
5179
5180            if (pkg.mAdoptPermissions != null) {
5181                // This package wants to adopt ownership of permissions from
5182                // another package.
5183                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5184                    final String origName = pkg.mAdoptPermissions.get(i);
5185                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5186                    if (orig != null) {
5187                        if (verifyPackageUpdateLPr(orig, pkg)) {
5188                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5189                                    + pkg.packageName);
5190                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5191                        }
5192                    }
5193                }
5194            }
5195        }
5196
5197        final String pkgName = pkg.packageName;
5198
5199        final long scanFileTime = scanFile.lastModified();
5200        final boolean forceDex = (scanMode&SCAN_FORCE_DEX) != 0;
5201        pkg.applicationInfo.processName = fixProcessName(
5202                pkg.applicationInfo.packageName,
5203                pkg.applicationInfo.processName,
5204                pkg.applicationInfo.uid);
5205
5206        File dataPath;
5207        if (mPlatformPackage == pkg) {
5208            // The system package is special.
5209            dataPath = new File (Environment.getDataDirectory(), "system");
5210            pkg.applicationInfo.dataDir = dataPath.getPath();
5211        } else {
5212            // This is a normal package, need to make its data directory.
5213            dataPath = getDataPathForPackage(pkg.packageName, 0);
5214
5215            boolean uidError = false;
5216
5217            if (dataPath.exists()) {
5218                int currentUid = 0;
5219                try {
5220                    StructStat stat = Os.stat(dataPath.getPath());
5221                    currentUid = stat.st_uid;
5222                } catch (ErrnoException e) {
5223                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5224                }
5225
5226                // If we have mismatched owners for the data path, we have a problem.
5227                if (currentUid != pkg.applicationInfo.uid) {
5228                    boolean recovered = false;
5229                    if (currentUid == 0) {
5230                        // The directory somehow became owned by root.  Wow.
5231                        // This is probably because the system was stopped while
5232                        // installd was in the middle of messing with its libs
5233                        // directory.  Ask installd to fix that.
5234                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5235                                pkg.applicationInfo.uid);
5236                        if (ret >= 0) {
5237                            recovered = true;
5238                            String msg = "Package " + pkg.packageName
5239                                    + " unexpectedly changed to uid 0; recovered to " +
5240                                    + pkg.applicationInfo.uid;
5241                            reportSettingsProblem(Log.WARN, msg);
5242                        }
5243                    }
5244                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5245                            || (scanMode&SCAN_BOOTING) != 0)) {
5246                        // If this is a system app, we can at least delete its
5247                        // current data so the application will still work.
5248                        int ret = removeDataDirsLI(pkgName);
5249                        if (ret >= 0) {
5250                            // TODO: Kill the processes first
5251                            // Old data gone!
5252                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5253                                    ? "System package " : "Third party package ";
5254                            String msg = prefix + pkg.packageName
5255                                    + " has changed from uid: "
5256                                    + currentUid + " to "
5257                                    + pkg.applicationInfo.uid + "; old data erased";
5258                            reportSettingsProblem(Log.WARN, msg);
5259                            recovered = true;
5260
5261                            // And now re-install the app.
5262                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5263                                                   pkg.applicationInfo.seinfo);
5264                            if (ret == -1) {
5265                                // Ack should not happen!
5266                                msg = prefix + pkg.packageName
5267                                        + " could not have data directory re-created after delete.";
5268                                reportSettingsProblem(Log.WARN, msg);
5269                                mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5270                                return null;
5271                            }
5272                        }
5273                        if (!recovered) {
5274                            mHasSystemUidErrors = true;
5275                        }
5276                    } else if (!recovered) {
5277                        // If we allow this install to proceed, we will be broken.
5278                        // Abort, abort!
5279                        mLastScanError = PackageManager.INSTALL_FAILED_UID_CHANGED;
5280                        return null;
5281                    }
5282                    if (!recovered) {
5283                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5284                            + pkg.applicationInfo.uid + "/fs_"
5285                            + currentUid;
5286                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5287                        String msg = "Package " + pkg.packageName
5288                                + " has mismatched uid: "
5289                                + currentUid + " on disk, "
5290                                + pkg.applicationInfo.uid + " in settings";
5291                        // writer
5292                        synchronized (mPackages) {
5293                            mSettings.mReadMessages.append(msg);
5294                            mSettings.mReadMessages.append('\n');
5295                            uidError = true;
5296                            if (!pkgSetting.uidError) {
5297                                reportSettingsProblem(Log.ERROR, msg);
5298                            }
5299                        }
5300                    }
5301                }
5302                pkg.applicationInfo.dataDir = dataPath.getPath();
5303                if (mShouldRestoreconData) {
5304                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5305                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5306                                pkg.applicationInfo.uid);
5307                }
5308            } else {
5309                if (DEBUG_PACKAGE_SCANNING) {
5310                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5311                        Log.v(TAG, "Want this data dir: " + dataPath);
5312                }
5313                //invoke installer to do the actual installation
5314                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5315                                           pkg.applicationInfo.seinfo);
5316                if (ret < 0) {
5317                    // Error from installer
5318                    mLastScanError = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
5319                    return null;
5320                }
5321
5322                if (dataPath.exists()) {
5323                    pkg.applicationInfo.dataDir = dataPath.getPath();
5324                } else {
5325                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5326                    pkg.applicationInfo.dataDir = null;
5327                }
5328            }
5329
5330            /*
5331             * Set the data dir to the default "/data/data/<package name>/lib"
5332             * if we got here without anyone telling us different (e.g., apps
5333             * stored on SD card have their native libraries stored in the ASEC
5334             * container with the APK).
5335             *
5336             * This happens during an upgrade from a package settings file that
5337             * doesn't have a native library path attribute at all.
5338             */
5339            if (pkg.applicationInfo.nativeLibraryDir == null && pkg.applicationInfo.dataDir != null) {
5340                if (pkgSetting.nativeLibraryPathString == null) {
5341                    setInternalAppNativeLibraryPath(pkg, pkgSetting);
5342                } else {
5343                    pkg.applicationInfo.nativeLibraryDir = pkgSetting.nativeLibraryPathString;
5344                }
5345            }
5346            pkgSetting.uidError = uidError;
5347        }
5348
5349        final String path = scanFile.getPath();
5350        /* Note: We don't want to unpack the native binaries for
5351         *        system applications, unless they have been updated
5352         *        (the binaries are already under /system/lib).
5353         *        Also, don't unpack libs for apps on the external card
5354         *        since they should have their libraries in the ASEC
5355         *        container already.
5356         *
5357         *        In other words, we're going to unpack the binaries
5358         *        only for non-system apps and system app upgrades.
5359         */
5360        if (pkg.applicationInfo.nativeLibraryDir != null) {
5361            NativeLibraryHelper.Handle handle = null;
5362            try {
5363                handle = NativeLibraryHelper.Handle.create(scanFile);
5364                // Enable gross and lame hacks for apps that are built with old
5365                // SDK tools. We must scan their APKs for renderscript bitcode and
5366                // not launch them if it's present. Don't bother checking on devices
5367                // that don't have 64 bit support.
5368                String[] abiList = Build.SUPPORTED_ABIS;
5369                boolean hasLegacyRenderscriptBitcode = false;
5370                if (abiOverride != null) {
5371                    abiList = new String[] { abiOverride };
5372                } else if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
5373                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5374                    abiList = Build.SUPPORTED_32_BIT_ABIS;
5375                    hasLegacyRenderscriptBitcode = true;
5376                }
5377
5378                File nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5379                final String dataPathString = dataPath.getCanonicalPath();
5380
5381                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5382                    /*
5383                     * Upgrading from a previous version of the OS sometimes
5384                     * leaves native libraries in the /data/data/<app>/lib
5385                     * directory for system apps even when they shouldn't be.
5386                     * Recent changes in the JNI library search path
5387                     * necessitates we remove those to match previous behavior.
5388                     */
5389                    if (NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryDir)) {
5390                        Log.i(TAG, "removed obsolete native libraries for system package "
5391                                + path);
5392                    }
5393                    if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5394                        pkg.applicationInfo.cpuAbi = abiList[0];
5395                        pkgSetting.cpuAbiString = abiList[0];
5396                    } else {
5397                        setInternalAppAbi(pkg, pkgSetting);
5398                    }
5399                } else {
5400                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
5401                        /*
5402                        * Update native library dir if it starts with
5403                        * /data/data
5404                        */
5405                        if (nativeLibraryDir.getPath().startsWith(dataPathString)) {
5406                            setInternalAppNativeLibraryPath(pkg, pkgSetting);
5407                            nativeLibraryDir = new File(pkg.applicationInfo.nativeLibraryDir);
5408                        }
5409
5410                        try {
5411                            int copyRet = copyNativeLibrariesForInternalApp(handle,
5412                                    nativeLibraryDir, abiList);
5413                            if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5414                                Slog.e(TAG, "Unable to copy native libraries");
5415                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5416                                return null;
5417                            }
5418
5419                            // We've successfully copied native libraries across, so we make a
5420                            // note of what ABI we're using
5421                            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5422                                pkg.applicationInfo.cpuAbi = abiList[copyRet];
5423                            } else if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5424                                pkg.applicationInfo.cpuAbi = abiList[0];
5425                            } else {
5426                                pkg.applicationInfo.cpuAbi = null;
5427                            }
5428                        } catch (IOException e) {
5429                            Slog.e(TAG, "Unable to copy native libraries", e);
5430                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5431                            return null;
5432                        }
5433                    } else {
5434                        // We don't have to copy the shared libraries if we're in the ASEC container
5435                        // but we still need to scan the file to figure out what ABI the app needs.
5436                        //
5437                        // TODO: This duplicates work done in the default container service. It's possible
5438                        // to clean this up but we'll need to change the interface between this service
5439                        // and IMediaContainerService (but doing so will spread this logic out, rather
5440                        // than centralizing it).
5441                        final int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5442                        if (abi >= 0) {
5443                            pkg.applicationInfo.cpuAbi = abiList[abi];
5444                        } else if (abi == PackageManager.NO_NATIVE_LIBRARIES) {
5445                            // Note that (non upgraded) system apps will not have any native
5446                            // libraries bundled in their APK, but we're guaranteed not to be
5447                            // such an app at this point.
5448                            if (abiOverride != null || hasLegacyRenderscriptBitcode) {
5449                                pkg.applicationInfo.cpuAbi = abiList[0];
5450                            } else {
5451                                pkg.applicationInfo.cpuAbi = null;
5452                            }
5453                        } else {
5454                            mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5455                            return null;
5456                        }
5457                    }
5458
5459                    if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5460                    final int[] userIds = sUserManager.getUserIds();
5461                    synchronized (mInstallLock) {
5462                        for (int userId : userIds) {
5463                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
5464                                    pkg.applicationInfo.nativeLibraryDir, userId) < 0) {
5465                                Slog.w(TAG, "Failed linking native library dir (user=" + userId
5466                                        + ")");
5467                                mLastScanError = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
5468                                return null;
5469                            }
5470                        }
5471                    }
5472                }
5473
5474                pkgSetting.cpuAbiString = pkg.applicationInfo.cpuAbi;
5475            } catch (IOException ioe) {
5476                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5477            } finally {
5478                IoUtils.closeQuietly(handle);
5479            }
5480        }
5481
5482        if ((scanMode&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5483            // We don't do this here during boot because we can do it all
5484            // at once after scanning all existing packages.
5485            //
5486            // We also do this *before* we perform dexopt on this package, so that
5487            // we can avoid redundant dexopts, and also to make sure we've got the
5488            // code and package path correct.
5489            if (!adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5490                    pkg, forceDex, (scanMode & SCAN_DEFER_DEX) != 0)) {
5491                mLastScanError = PackageManager.INSTALL_FAILED_CPU_ABI_INCOMPATIBLE;
5492                return null;
5493            }
5494        }
5495
5496        if ((scanMode&SCAN_NO_DEX) == 0) {
5497            if (performDexOptLI(pkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5498                    == DEX_OPT_FAILED) {
5499                if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5500                    removeDataDirsLI(pkg.packageName);
5501                }
5502
5503                mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5504                return null;
5505            }
5506        }
5507
5508        if (mFactoryTest && pkg.requestedPermissions.contains(
5509                android.Manifest.permission.FACTORY_TEST)) {
5510            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5511        }
5512
5513        ArrayList<PackageParser.Package> clientLibPkgs = null;
5514
5515        // writer
5516        synchronized (mPackages) {
5517            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5518                // Only system apps can add new shared libraries.
5519                if (pkg.libraryNames != null) {
5520                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5521                        String name = pkg.libraryNames.get(i);
5522                        boolean allowed = false;
5523                        if (isUpdatedSystemApp(pkg)) {
5524                            // New library entries can only be added through the
5525                            // system image.  This is important to get rid of a lot
5526                            // of nasty edge cases: for example if we allowed a non-
5527                            // system update of the app to add a library, then uninstalling
5528                            // the update would make the library go away, and assumptions
5529                            // we made such as through app install filtering would now
5530                            // have allowed apps on the device which aren't compatible
5531                            // with it.  Better to just have the restriction here, be
5532                            // conservative, and create many fewer cases that can negatively
5533                            // impact the user experience.
5534                            final PackageSetting sysPs = mSettings
5535                                    .getDisabledSystemPkgLPr(pkg.packageName);
5536                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5537                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5538                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5539                                        allowed = true;
5540                                        allowed = true;
5541                                        break;
5542                                    }
5543                                }
5544                            }
5545                        } else {
5546                            allowed = true;
5547                        }
5548                        if (allowed) {
5549                            if (!mSharedLibraries.containsKey(name)) {
5550                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5551                            } else if (!name.equals(pkg.packageName)) {
5552                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5553                                        + name + " already exists; skipping");
5554                            }
5555                        } else {
5556                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5557                                    + name + " that is not declared on system image; skipping");
5558                        }
5559                    }
5560                    if ((scanMode&SCAN_BOOTING) == 0) {
5561                        // If we are not booting, we need to update any applications
5562                        // that are clients of our shared library.  If we are booting,
5563                        // this will all be done once the scan is complete.
5564                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5565                    }
5566                }
5567            }
5568        }
5569
5570        // We also need to dexopt any apps that are dependent on this library.  Note that
5571        // if these fail, we should abort the install since installing the library will
5572        // result in some apps being broken.
5573        if (clientLibPkgs != null) {
5574            if ((scanMode&SCAN_NO_DEX) == 0) {
5575                for (int i=0; i<clientLibPkgs.size(); i++) {
5576                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5577                    if (performDexOptLI(clientPkg, forceDex, (scanMode&SCAN_DEFER_DEX) != 0, false)
5578                            == DEX_OPT_FAILED) {
5579                        if ((scanMode & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5580                            removeDataDirsLI(pkg.packageName);
5581                        }
5582
5583                        mLastScanError = PackageManager.INSTALL_FAILED_DEXOPT;
5584                        return null;
5585                    }
5586                }
5587            }
5588        }
5589
5590        // Request the ActivityManager to kill the process(only for existing packages)
5591        // so that we do not end up in a confused state while the user is still using the older
5592        // version of the application while the new one gets installed.
5593        if ((parseFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
5594            // If the package lives in an asec, tell everyone that the container is going
5595            // away so they can clean up any references to its resources (which would prevent
5596            // vold from being able to unmount the asec)
5597            if (isForwardLocked(pkg) || isExternal(pkg)) {
5598                if (DEBUG_INSTALL) {
5599                    Slog.i(TAG, "upgrading pkg " + pkg + " is ASEC-hosted -> UNAVAILABLE");
5600                }
5601                final int[] uidArray = new int[] { pkg.applicationInfo.uid };
5602                final ArrayList<String> pkgList = new ArrayList<String>(1);
5603                pkgList.add(pkg.applicationInfo.packageName);
5604                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
5605            }
5606
5607            // Post the request that it be killed now that the going-away broadcast is en route
5608            killApplication(pkg.applicationInfo.packageName,
5609                        pkg.applicationInfo.uid, "update pkg");
5610        }
5611
5612        // Also need to kill any apps that are dependent on the library.
5613        if (clientLibPkgs != null) {
5614            for (int i=0; i<clientLibPkgs.size(); i++) {
5615                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5616                killApplication(clientPkg.applicationInfo.packageName,
5617                        clientPkg.applicationInfo.uid, "update lib");
5618            }
5619        }
5620
5621        // writer
5622        synchronized (mPackages) {
5623            // We don't expect installation to fail beyond this point,
5624            if ((scanMode&SCAN_MONITOR) != 0) {
5625                mAppDirs.put(pkg.codePath, pkg);
5626            }
5627            // Add the new setting to mSettings
5628            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5629            // Add the new setting to mPackages
5630            mPackages.put(pkg.applicationInfo.packageName, pkg);
5631            // Make sure we don't accidentally delete its data.
5632            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5633            while (iter.hasNext()) {
5634                PackageCleanItem item = iter.next();
5635                if (pkgName.equals(item.packageName)) {
5636                    iter.remove();
5637                }
5638            }
5639
5640            // Take care of first install / last update times.
5641            if (currentTime != 0) {
5642                if (pkgSetting.firstInstallTime == 0) {
5643                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5644                } else if ((scanMode&SCAN_UPDATE_TIME) != 0) {
5645                    pkgSetting.lastUpdateTime = currentTime;
5646                }
5647            } else if (pkgSetting.firstInstallTime == 0) {
5648                // We need *something*.  Take time time stamp of the file.
5649                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5650            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5651                if (scanFileTime != pkgSetting.timeStamp) {
5652                    // A package on the system image has changed; consider this
5653                    // to be an update.
5654                    pkgSetting.lastUpdateTime = scanFileTime;
5655                }
5656            }
5657
5658            // Add the package's KeySets to the global KeySetManagerService
5659            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5660            try {
5661                // Old KeySetData no longer valid.
5662                ksms.removeAppKeySetData(pkg.packageName);
5663                ksms.addSigningKeySetToPackage(pkg.packageName, pkg.mSigningKeys);
5664                if (pkg.mKeySetMapping != null) {
5665                    for (Map.Entry<String, Set<PublicKey>> entry :
5666                            pkg.mKeySetMapping.entrySet()) {
5667                        if (entry.getValue() != null) {
5668                            ksms.addDefinedKeySetToPackage(pkg.packageName,
5669                                                          entry.getValue(), entry.getKey());
5670                        }
5671                    }
5672                    if (pkg.mUpgradeKeySets != null
5673                            && pkg.mKeySetMapping.keySet().containsAll(pkg.mUpgradeKeySets)) {
5674                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5675                            ksms.addUpgradeKeySetToPackage(pkg.packageName, upgradeAlias);
5676                        }
5677                    }
5678                }
5679            } catch (NullPointerException e) {
5680                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5681            } catch (IllegalArgumentException e) {
5682                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5683            }
5684
5685            int N = pkg.providers.size();
5686            StringBuilder r = null;
5687            int i;
5688            for (i=0; i<N; i++) {
5689                PackageParser.Provider p = pkg.providers.get(i);
5690                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5691                        p.info.processName, pkg.applicationInfo.uid);
5692                mProviders.addProvider(p);
5693                p.syncable = p.info.isSyncable;
5694                if (p.info.authority != null) {
5695                    String names[] = p.info.authority.split(";");
5696                    p.info.authority = null;
5697                    for (int j = 0; j < names.length; j++) {
5698                        if (j == 1 && p.syncable) {
5699                            // We only want the first authority for a provider to possibly be
5700                            // syncable, so if we already added this provider using a different
5701                            // authority clear the syncable flag. We copy the provider before
5702                            // changing it because the mProviders object contains a reference
5703                            // to a provider that we don't want to change.
5704                            // Only do this for the second authority since the resulting provider
5705                            // object can be the same for all future authorities for this provider.
5706                            p = new PackageParser.Provider(p);
5707                            p.syncable = false;
5708                        }
5709                        if (!mProvidersByAuthority.containsKey(names[j])) {
5710                            mProvidersByAuthority.put(names[j], p);
5711                            if (p.info.authority == null) {
5712                                p.info.authority = names[j];
5713                            } else {
5714                                p.info.authority = p.info.authority + ";" + names[j];
5715                            }
5716                            if (DEBUG_PACKAGE_SCANNING) {
5717                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5718                                    Log.d(TAG, "Registered content provider: " + names[j]
5719                                            + ", className = " + p.info.name + ", isSyncable = "
5720                                            + p.info.isSyncable);
5721                            }
5722                        } else {
5723                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5724                            Slog.w(TAG, "Skipping provider name " + names[j] +
5725                                    " (in package " + pkg.applicationInfo.packageName +
5726                                    "): name already used by "
5727                                    + ((other != null && other.getComponentName() != null)
5728                                            ? other.getComponentName().getPackageName() : "?"));
5729                        }
5730                    }
5731                }
5732                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5733                    if (r == null) {
5734                        r = new StringBuilder(256);
5735                    } else {
5736                        r.append(' ');
5737                    }
5738                    r.append(p.info.name);
5739                }
5740            }
5741            if (r != null) {
5742                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5743            }
5744
5745            N = pkg.services.size();
5746            r = null;
5747            for (i=0; i<N; i++) {
5748                PackageParser.Service s = pkg.services.get(i);
5749                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5750                        s.info.processName, pkg.applicationInfo.uid);
5751                mServices.addService(s);
5752                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5753                    if (r == null) {
5754                        r = new StringBuilder(256);
5755                    } else {
5756                        r.append(' ');
5757                    }
5758                    r.append(s.info.name);
5759                }
5760            }
5761            if (r != null) {
5762                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5763            }
5764
5765            N = pkg.receivers.size();
5766            r = null;
5767            for (i=0; i<N; i++) {
5768                PackageParser.Activity a = pkg.receivers.get(i);
5769                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5770                        a.info.processName, pkg.applicationInfo.uid);
5771                mReceivers.addActivity(a, "receiver");
5772                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5773                    if (r == null) {
5774                        r = new StringBuilder(256);
5775                    } else {
5776                        r.append(' ');
5777                    }
5778                    r.append(a.info.name);
5779                }
5780            }
5781            if (r != null) {
5782                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5783            }
5784
5785            N = pkg.activities.size();
5786            r = null;
5787            for (i=0; i<N; i++) {
5788                PackageParser.Activity a = pkg.activities.get(i);
5789                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5790                        a.info.processName, pkg.applicationInfo.uid);
5791                mActivities.addActivity(a, "activity");
5792                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5793                    if (r == null) {
5794                        r = new StringBuilder(256);
5795                    } else {
5796                        r.append(' ');
5797                    }
5798                    r.append(a.info.name);
5799                }
5800            }
5801            if (r != null) {
5802                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5803            }
5804
5805            N = pkg.permissionGroups.size();
5806            r = null;
5807            for (i=0; i<N; i++) {
5808                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5809                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5810                if (cur == null) {
5811                    mPermissionGroups.put(pg.info.name, pg);
5812                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5813                        if (r == null) {
5814                            r = new StringBuilder(256);
5815                        } else {
5816                            r.append(' ');
5817                        }
5818                        r.append(pg.info.name);
5819                    }
5820                } else {
5821                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5822                            + pg.info.packageName + " ignored: original from "
5823                            + cur.info.packageName);
5824                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5825                        if (r == null) {
5826                            r = new StringBuilder(256);
5827                        } else {
5828                            r.append(' ');
5829                        }
5830                        r.append("DUP:");
5831                        r.append(pg.info.name);
5832                    }
5833                }
5834            }
5835            if (r != null) {
5836                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5837            }
5838
5839            N = pkg.permissions.size();
5840            r = null;
5841            for (i=0; i<N; i++) {
5842                PackageParser.Permission p = pkg.permissions.get(i);
5843                HashMap<String, BasePermission> permissionMap =
5844                        p.tree ? mSettings.mPermissionTrees
5845                        : mSettings.mPermissions;
5846                p.group = mPermissionGroups.get(p.info.group);
5847                if (p.info.group == null || p.group != null) {
5848                    BasePermission bp = permissionMap.get(p.info.name);
5849                    if (bp == null) {
5850                        bp = new BasePermission(p.info.name, p.info.packageName,
5851                                BasePermission.TYPE_NORMAL);
5852                        permissionMap.put(p.info.name, bp);
5853                    }
5854                    if (bp.perm == null) {
5855                        if (bp.sourcePackage != null
5856                                && !bp.sourcePackage.equals(p.info.packageName)) {
5857                            // If this is a permission that was formerly defined by a non-system
5858                            // app, but is now defined by a system app (following an upgrade),
5859                            // discard the previous declaration and consider the system's to be
5860                            // canonical.
5861                            if (isSystemApp(p.owner)) {
5862                                String msg = "New decl " + p.owner + " of permission  "
5863                                        + p.info.name + " is system";
5864                                reportSettingsProblem(Log.WARN, msg);
5865                                bp.sourcePackage = null;
5866                            }
5867                        }
5868                        if (bp.sourcePackage == null
5869                                || bp.sourcePackage.equals(p.info.packageName)) {
5870                            BasePermission tree = findPermissionTreeLP(p.info.name);
5871                            if (tree == null
5872                                    || tree.sourcePackage.equals(p.info.packageName)) {
5873                                bp.packageSetting = pkgSetting;
5874                                bp.perm = p;
5875                                bp.uid = pkg.applicationInfo.uid;
5876                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5877                                    if (r == null) {
5878                                        r = new StringBuilder(256);
5879                                    } else {
5880                                        r.append(' ');
5881                                    }
5882                                    r.append(p.info.name);
5883                                }
5884                            } else {
5885                                Slog.w(TAG, "Permission " + p.info.name + " from package "
5886                                        + p.info.packageName + " ignored: base tree "
5887                                        + tree.name + " is from package "
5888                                        + tree.sourcePackage);
5889                            }
5890                        } else {
5891                            Slog.w(TAG, "Permission " + p.info.name + " from package "
5892                                    + p.info.packageName + " ignored: original from "
5893                                    + bp.sourcePackage);
5894                        }
5895                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5896                        if (r == null) {
5897                            r = new StringBuilder(256);
5898                        } else {
5899                            r.append(' ');
5900                        }
5901                        r.append("DUP:");
5902                        r.append(p.info.name);
5903                    }
5904                    if (bp.perm == p) {
5905                        bp.protectionLevel = p.info.protectionLevel;
5906                    }
5907                } else {
5908                    Slog.w(TAG, "Permission " + p.info.name + " from package "
5909                            + p.info.packageName + " ignored: no group "
5910                            + p.group);
5911                }
5912            }
5913            if (r != null) {
5914                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
5915            }
5916
5917            N = pkg.instrumentation.size();
5918            r = null;
5919            for (i=0; i<N; i++) {
5920                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
5921                a.info.packageName = pkg.applicationInfo.packageName;
5922                a.info.sourceDir = pkg.applicationInfo.sourceDir;
5923                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
5924                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
5925                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
5926                a.info.dataDir = pkg.applicationInfo.dataDir;
5927                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
5928                mInstrumentation.put(a.getComponentName(), a);
5929                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5930                    if (r == null) {
5931                        r = new StringBuilder(256);
5932                    } else {
5933                        r.append(' ');
5934                    }
5935                    r.append(a.info.name);
5936                }
5937            }
5938            if (r != null) {
5939                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
5940            }
5941
5942            if (pkg.protectedBroadcasts != null) {
5943                N = pkg.protectedBroadcasts.size();
5944                for (i=0; i<N; i++) {
5945                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
5946                }
5947            }
5948
5949            pkgSetting.setTimeStamp(scanFileTime);
5950
5951            // Create idmap files for pairs of (packages, overlay packages).
5952            // Note: "android", ie framework-res.apk, is handled by native layers.
5953            if (pkg.mOverlayTarget != null) {
5954                // This is an overlay package.
5955                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
5956                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
5957                        mOverlays.put(pkg.mOverlayTarget,
5958                                new HashMap<String, PackageParser.Package>());
5959                    }
5960                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
5961                    map.put(pkg.packageName, pkg);
5962                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
5963                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
5964                        mLastScanError = PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
5965                        return null;
5966                    }
5967                }
5968            } else if (mOverlays.containsKey(pkg.packageName) &&
5969                    !pkg.packageName.equals("android")) {
5970                // This is a regular package, with one or more known overlay packages.
5971                createIdmapsForPackageLI(pkg);
5972            }
5973        }
5974
5975        return pkg;
5976    }
5977
5978    /**
5979     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
5980     * i.e, so that all packages can be run inside a single process if required.
5981     *
5982     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
5983     * this function will either try and make the ABI for all packages in {@code packagesForUser}
5984     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
5985     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
5986     * updating a package that belongs to a shared user.
5987     */
5988    private boolean adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
5989            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
5990        String requiredInstructionSet = null;
5991        if (scannedPackage != null && scannedPackage.applicationInfo.cpuAbi != null) {
5992            requiredInstructionSet = VMRuntime.getInstructionSet(
5993                     scannedPackage.applicationInfo.cpuAbi);
5994        }
5995
5996        PackageSetting requirer = null;
5997        for (PackageSetting ps : packagesForUser) {
5998            // If packagesForUser contains scannedPackage, we skip it. This will happen
5999            // when scannedPackage is an update of an existing package. Without this check,
6000            // we will never be able to change the ABI of any package belonging to a shared
6001            // user, even if it's compatible with other packages.
6002            if (scannedPackage == null || ! scannedPackage.packageName.equals(ps.name)) {
6003                if (ps.cpuAbiString == null) {
6004                    continue;
6005                }
6006
6007                final String instructionSet = VMRuntime.getInstructionSet(ps.cpuAbiString);
6008                if (requiredInstructionSet != null) {
6009                    if (!instructionSet.equals(requiredInstructionSet)) {
6010                        // We have a mismatch between instruction sets (say arm vs arm64).
6011                        // bail out.
6012                        String errorMessage = "Instruction set mismatch, "
6013                                + ((requirer == null) ? "[caller]" : requirer)
6014                                + " requires " + requiredInstructionSet + " whereas " + ps
6015                                + " requires " + instructionSet;
6016                        Slog.e(TAG, errorMessage);
6017
6018                        reportSettingsProblem(Log.WARN, errorMessage);
6019                        // Give up, don't bother making any other changes to the package settings.
6020                        return false;
6021                    }
6022                } else {
6023                    requiredInstructionSet = instructionSet;
6024                    requirer = ps;
6025                }
6026            }
6027        }
6028
6029        if (requiredInstructionSet != null) {
6030            String adjustedAbi;
6031            if (requirer != null) {
6032                // requirer != null implies that either scannedPackage was null or that scannedPackage
6033                // did not require an ABI, in which case we have to adjust scannedPackage to match
6034                // the ABI of the set (which is the same as requirer's ABI)
6035                adjustedAbi = requirer.cpuAbiString;
6036                if (scannedPackage != null) {
6037                    scannedPackage.applicationInfo.cpuAbi = adjustedAbi;
6038                }
6039            } else {
6040                // requirer == null implies that we're updating all ABIs in the set to
6041                // match scannedPackage.
6042                adjustedAbi =  scannedPackage.applicationInfo.cpuAbi;
6043            }
6044
6045            for (PackageSetting ps : packagesForUser) {
6046                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6047                    if (ps.cpuAbiString != null) {
6048                        continue;
6049                    }
6050
6051                    ps.cpuAbiString = adjustedAbi;
6052                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6053                        ps.pkg.applicationInfo.cpuAbi = adjustedAbi;
6054                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6055
6056                        if (performDexOptLI(ps.pkg, forceDexOpt, deferDexOpt, true) == DEX_OPT_FAILED) {
6057                            ps.cpuAbiString = null;
6058                            ps.pkg.applicationInfo.cpuAbi = null;
6059                            return false;
6060                        } else {
6061                            mInstaller.rmdex(ps.codePathString, getPreferredInstructionSet());
6062                        }
6063                    }
6064                }
6065            }
6066        }
6067
6068        return true;
6069    }
6070
6071    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6072        synchronized (mPackages) {
6073            mResolverReplaced = true;
6074            // Set up information for custom user intent resolution activity.
6075            mResolveActivity.applicationInfo = pkg.applicationInfo;
6076            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6077            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6078            mResolveActivity.processName = null;
6079            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6080            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6081                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6082            mResolveActivity.theme = 0;
6083            mResolveActivity.exported = true;
6084            mResolveActivity.enabled = true;
6085            mResolveInfo.activityInfo = mResolveActivity;
6086            mResolveInfo.priority = 0;
6087            mResolveInfo.preferredOrder = 0;
6088            mResolveInfo.match = 0;
6089            mResolveComponentName = mCustomResolverComponentName;
6090            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6091                    mResolveComponentName);
6092        }
6093    }
6094
6095    private String calculateApkRoot(final String codePathString) {
6096        final File codePath = new File(codePathString);
6097        final File codeRoot;
6098        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6099            codeRoot = Environment.getRootDirectory();
6100        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6101            codeRoot = Environment.getOemDirectory();
6102        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6103            codeRoot = Environment.getVendorDirectory();
6104        } else {
6105            // Unrecognized code path; take its top real segment as the apk root:
6106            // e.g. /something/app/blah.apk => /something
6107            try {
6108                File f = codePath.getCanonicalFile();
6109                File parent = f.getParentFile();    // non-null because codePath is a file
6110                File tmp;
6111                while ((tmp = parent.getParentFile()) != null) {
6112                    f = parent;
6113                    parent = tmp;
6114                }
6115                codeRoot = f;
6116                Slog.w(TAG, "Unrecognized code path "
6117                        + codePath + " - using " + codeRoot);
6118            } catch (IOException e) {
6119                // Can't canonicalize the lib path -- shenanigans?
6120                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6121                return Environment.getRootDirectory().getPath();
6122            }
6123        }
6124        return codeRoot.getPath();
6125    }
6126
6127    // This is the initial scan-time determination of how to handle a given
6128    // package for purposes of native library location.
6129    private void setInternalAppNativeLibraryPath(PackageParser.Package pkg,
6130            PackageSetting pkgSetting) {
6131        // "bundled" here means system-installed with no overriding update
6132        final boolean bundledApk = isSystemApp(pkg) && !isUpdatedSystemApp(pkg);
6133        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6134        final File libDir;
6135        if (bundledApk) {
6136            // If "/system/lib64/apkname" exists, assume that is the per-package
6137            // native library directory to use; otherwise use "/system/lib/apkname".
6138            String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6139            File lib64 = new File(apkRoot, LIB64_DIR_NAME);
6140            File packLib64 = new File(lib64, apkName);
6141            libDir = (packLib64.exists()) ? lib64 : new File(apkRoot, LIB_DIR_NAME);
6142        } else {
6143            libDir = mAppLibInstallDir;
6144        }
6145        final String nativeLibraryPath = (new File(libDir, apkName)).getPath();
6146        pkg.applicationInfo.nativeLibraryDir = nativeLibraryPath;
6147        // pkgSetting might be null during rescan following uninstall of updates
6148        // to a bundled app, so accommodate that possibility.  The settings in
6149        // that case will be established later from the parsed package.
6150        if (pkgSetting != null) {
6151            pkgSetting.nativeLibraryPathString = nativeLibraryPath;
6152        }
6153    }
6154
6155    // Deduces the required ABI of an upgraded system app.
6156    private void setInternalAppAbi(PackageParser.Package pkg, PackageSetting pkgSetting) {
6157        final String apkRoot = calculateApkRoot(pkg.applicationInfo.sourceDir);
6158        final String apkName = getApkName(pkg.applicationInfo.sourceDir);
6159
6160        // This is of the form "/system/lib64/<packagename>", "/vendor/lib64/<packagename>"
6161        // or similar.
6162        final File lib64 = new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath());
6163        final File lib = new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath());
6164
6165        // Assume that the bundled native libraries always correspond to the
6166        // most preferred 32 or 64 bit ABI.
6167        if (lib64.exists()) {
6168            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6169            pkgSetting.cpuAbiString = Build.SUPPORTED_64_BIT_ABIS[0];
6170        } else if (lib.exists()) {
6171            pkg.applicationInfo.cpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6172            pkgSetting.cpuAbiString = Build.SUPPORTED_32_BIT_ABIS[0];
6173        } else {
6174            // This is the case where the app has no native code.
6175            pkg.applicationInfo.cpuAbi = null;
6176            pkgSetting.cpuAbiString = null;
6177        }
6178    }
6179
6180    private static int copyNativeLibrariesForInternalApp(NativeLibraryHelper.Handle handle,
6181            final File nativeLibraryDir, String[] abiList) throws IOException {
6182        if (!nativeLibraryDir.isDirectory()) {
6183            nativeLibraryDir.delete();
6184
6185            if (!nativeLibraryDir.mkdir()) {
6186                throw new IOException("Cannot create " + nativeLibraryDir.getPath());
6187            }
6188
6189            try {
6190                Os.chmod(nativeLibraryDir.getPath(), S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH);
6191            } catch (ErrnoException e) {
6192                throw new IOException("Cannot chmod native library directory "
6193                        + nativeLibraryDir.getPath(), e);
6194            }
6195        } else if (!SELinux.restorecon(nativeLibraryDir)) {
6196            throw new IOException("Cannot set SELinux context for " + nativeLibraryDir.getPath());
6197        }
6198
6199        /*
6200         * If this is an internal application or our nativeLibraryPath points to
6201         * the app-lib directory, unpack the libraries if necessary.
6202         */
6203        int abi = NativeLibraryHelper.findSupportedAbi(handle, abiList);
6204        if (abi >= 0) {
6205            int copyRet = NativeLibraryHelper.copyNativeBinariesIfNeededLI(handle,
6206                    nativeLibraryDir, Build.SUPPORTED_ABIS[abi]);
6207            if (copyRet != PackageManager.INSTALL_SUCCEEDED) {
6208                return copyRet;
6209            }
6210        }
6211
6212        return abi;
6213    }
6214
6215    private void killApplication(String pkgName, int appId, String reason) {
6216        // Request the ActivityManager to kill the process(only for existing packages)
6217        // so that we do not end up in a confused state while the user is still using the older
6218        // version of the application while the new one gets installed.
6219        IActivityManager am = ActivityManagerNative.getDefault();
6220        if (am != null) {
6221            try {
6222                am.killApplicationWithAppId(pkgName, appId, reason);
6223            } catch (RemoteException e) {
6224            }
6225        }
6226    }
6227
6228    void removePackageLI(PackageSetting ps, boolean chatty) {
6229        if (DEBUG_INSTALL) {
6230            if (chatty)
6231                Log.d(TAG, "Removing package " + ps.name);
6232        }
6233
6234        // writer
6235        synchronized (mPackages) {
6236            mPackages.remove(ps.name);
6237            if (ps.codePathString != null) {
6238                mAppDirs.remove(ps.codePathString);
6239            }
6240
6241            final PackageParser.Package pkg = ps.pkg;
6242            if (pkg != null) {
6243                cleanPackageDataStructuresLILPw(pkg, chatty);
6244            }
6245        }
6246    }
6247
6248    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6249        if (DEBUG_INSTALL) {
6250            if (chatty)
6251                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6252        }
6253
6254        // writer
6255        synchronized (mPackages) {
6256            mPackages.remove(pkg.applicationInfo.packageName);
6257            if (pkg.codePath != null) {
6258                mAppDirs.remove(pkg.codePath);
6259            }
6260            cleanPackageDataStructuresLILPw(pkg, chatty);
6261        }
6262    }
6263
6264    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6265        int N = pkg.providers.size();
6266        StringBuilder r = null;
6267        int i;
6268        for (i=0; i<N; i++) {
6269            PackageParser.Provider p = pkg.providers.get(i);
6270            mProviders.removeProvider(p);
6271            if (p.info.authority == null) {
6272
6273                /* There was another ContentProvider with this authority when
6274                 * this app was installed so this authority is null,
6275                 * Ignore it as we don't have to unregister the provider.
6276                 */
6277                continue;
6278            }
6279            String names[] = p.info.authority.split(";");
6280            for (int j = 0; j < names.length; j++) {
6281                if (mProvidersByAuthority.get(names[j]) == p) {
6282                    mProvidersByAuthority.remove(names[j]);
6283                    if (DEBUG_REMOVE) {
6284                        if (chatty)
6285                            Log.d(TAG, "Unregistered content provider: " + names[j]
6286                                    + ", className = " + p.info.name + ", isSyncable = "
6287                                    + p.info.isSyncable);
6288                    }
6289                }
6290            }
6291            if (DEBUG_REMOVE && chatty) {
6292                if (r == null) {
6293                    r = new StringBuilder(256);
6294                } else {
6295                    r.append(' ');
6296                }
6297                r.append(p.info.name);
6298            }
6299        }
6300        if (r != null) {
6301            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6302        }
6303
6304        N = pkg.services.size();
6305        r = null;
6306        for (i=0; i<N; i++) {
6307            PackageParser.Service s = pkg.services.get(i);
6308            mServices.removeService(s);
6309            if (chatty) {
6310                if (r == null) {
6311                    r = new StringBuilder(256);
6312                } else {
6313                    r.append(' ');
6314                }
6315                r.append(s.info.name);
6316            }
6317        }
6318        if (r != null) {
6319            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6320        }
6321
6322        N = pkg.receivers.size();
6323        r = null;
6324        for (i=0; i<N; i++) {
6325            PackageParser.Activity a = pkg.receivers.get(i);
6326            mReceivers.removeActivity(a, "receiver");
6327            if (DEBUG_REMOVE && chatty) {
6328                if (r == null) {
6329                    r = new StringBuilder(256);
6330                } else {
6331                    r.append(' ');
6332                }
6333                r.append(a.info.name);
6334            }
6335        }
6336        if (r != null) {
6337            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6338        }
6339
6340        N = pkg.activities.size();
6341        r = null;
6342        for (i=0; i<N; i++) {
6343            PackageParser.Activity a = pkg.activities.get(i);
6344            mActivities.removeActivity(a, "activity");
6345            if (DEBUG_REMOVE && chatty) {
6346                if (r == null) {
6347                    r = new StringBuilder(256);
6348                } else {
6349                    r.append(' ');
6350                }
6351                r.append(a.info.name);
6352            }
6353        }
6354        if (r != null) {
6355            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6356        }
6357
6358        N = pkg.permissions.size();
6359        r = null;
6360        for (i=0; i<N; i++) {
6361            PackageParser.Permission p = pkg.permissions.get(i);
6362            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6363            if (bp == null) {
6364                bp = mSettings.mPermissionTrees.get(p.info.name);
6365            }
6366            if (bp != null && bp.perm == p) {
6367                bp.perm = null;
6368                if (DEBUG_REMOVE && chatty) {
6369                    if (r == null) {
6370                        r = new StringBuilder(256);
6371                    } else {
6372                        r.append(' ');
6373                    }
6374                    r.append(p.info.name);
6375                }
6376            }
6377        }
6378        if (r != null) {
6379            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6380        }
6381
6382        N = pkg.instrumentation.size();
6383        r = null;
6384        for (i=0; i<N; i++) {
6385            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6386            mInstrumentation.remove(a.getComponentName());
6387            if (DEBUG_REMOVE && chatty) {
6388                if (r == null) {
6389                    r = new StringBuilder(256);
6390                } else {
6391                    r.append(' ');
6392                }
6393                r.append(a.info.name);
6394            }
6395        }
6396        if (r != null) {
6397            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6398        }
6399
6400        r = null;
6401        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6402            // Only system apps can hold shared libraries.
6403            if (pkg.libraryNames != null) {
6404                for (i=0; i<pkg.libraryNames.size(); i++) {
6405                    String name = pkg.libraryNames.get(i);
6406                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6407                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6408                        mSharedLibraries.remove(name);
6409                        if (DEBUG_REMOVE && chatty) {
6410                            if (r == null) {
6411                                r = new StringBuilder(256);
6412                            } else {
6413                                r.append(' ');
6414                            }
6415                            r.append(name);
6416                        }
6417                    }
6418                }
6419            }
6420        }
6421        if (r != null) {
6422            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6423        }
6424    }
6425
6426    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6427        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6428            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6429                return true;
6430            }
6431        }
6432        return false;
6433    }
6434
6435    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6436    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6437    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6438
6439    private void updatePermissionsLPw(String changingPkg,
6440            PackageParser.Package pkgInfo, int flags) {
6441        // Make sure there are no dangling permission trees.
6442        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6443        while (it.hasNext()) {
6444            final BasePermission bp = it.next();
6445            if (bp.packageSetting == null) {
6446                // We may not yet have parsed the package, so just see if
6447                // we still know about its settings.
6448                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6449            }
6450            if (bp.packageSetting == null) {
6451                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6452                        + " from package " + bp.sourcePackage);
6453                it.remove();
6454            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6455                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6456                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6457                            + " from package " + bp.sourcePackage);
6458                    flags |= UPDATE_PERMISSIONS_ALL;
6459                    it.remove();
6460                }
6461            }
6462        }
6463
6464        // Make sure all dynamic permissions have been assigned to a package,
6465        // and make sure there are no dangling permissions.
6466        it = mSettings.mPermissions.values().iterator();
6467        while (it.hasNext()) {
6468            final BasePermission bp = it.next();
6469            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6470                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6471                        + bp.name + " pkg=" + bp.sourcePackage
6472                        + " info=" + bp.pendingInfo);
6473                if (bp.packageSetting == null && bp.pendingInfo != null) {
6474                    final BasePermission tree = findPermissionTreeLP(bp.name);
6475                    if (tree != null && tree.perm != null) {
6476                        bp.packageSetting = tree.packageSetting;
6477                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6478                                new PermissionInfo(bp.pendingInfo));
6479                        bp.perm.info.packageName = tree.perm.info.packageName;
6480                        bp.perm.info.name = bp.name;
6481                        bp.uid = tree.uid;
6482                    }
6483                }
6484            }
6485            if (bp.packageSetting == null) {
6486                // We may not yet have parsed the package, so just see if
6487                // we still know about its settings.
6488                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6489            }
6490            if (bp.packageSetting == null) {
6491                Slog.w(TAG, "Removing dangling permission: " + bp.name
6492                        + " from package " + bp.sourcePackage);
6493                it.remove();
6494            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6495                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6496                    Slog.i(TAG, "Removing old permission: " + bp.name
6497                            + " from package " + bp.sourcePackage);
6498                    flags |= UPDATE_PERMISSIONS_ALL;
6499                    it.remove();
6500                }
6501            }
6502        }
6503
6504        // Now update the permissions for all packages, in particular
6505        // replace the granted permissions of the system packages.
6506        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6507            for (PackageParser.Package pkg : mPackages.values()) {
6508                if (pkg != pkgInfo) {
6509                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0);
6510                }
6511            }
6512        }
6513
6514        if (pkgInfo != null) {
6515            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0);
6516        }
6517    }
6518
6519    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace) {
6520        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6521        if (ps == null) {
6522            return;
6523        }
6524        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6525        HashSet<String> origPermissions = gp.grantedPermissions;
6526        boolean changedPermission = false;
6527
6528        if (replace) {
6529            ps.permissionsFixed = false;
6530            if (gp == ps) {
6531                origPermissions = new HashSet<String>(gp.grantedPermissions);
6532                gp.grantedPermissions.clear();
6533                gp.gids = mGlobalGids;
6534            }
6535        }
6536
6537        if (gp.gids == null) {
6538            gp.gids = mGlobalGids;
6539        }
6540
6541        final int N = pkg.requestedPermissions.size();
6542        for (int i=0; i<N; i++) {
6543            final String name = pkg.requestedPermissions.get(i);
6544            final boolean required = pkg.requestedPermissionsRequired.get(i);
6545            final BasePermission bp = mSettings.mPermissions.get(name);
6546            if (DEBUG_INSTALL) {
6547                if (gp != ps) {
6548                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6549                }
6550            }
6551
6552            if (bp == null || bp.packageSetting == null) {
6553                Slog.w(TAG, "Unknown permission " + name
6554                        + " in package " + pkg.packageName);
6555                continue;
6556            }
6557
6558            final String perm = bp.name;
6559            boolean allowed;
6560            boolean allowedSig = false;
6561            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6562            if (level == PermissionInfo.PROTECTION_NORMAL
6563                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6564                // We grant a normal or dangerous permission if any of the following
6565                // are true:
6566                // 1) The permission is required
6567                // 2) The permission is optional, but was granted in the past
6568                // 3) The permission is optional, but was requested by an
6569                //    app in /system (not /data)
6570                //
6571                // Otherwise, reject the permission.
6572                allowed = (required || origPermissions.contains(perm)
6573                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6574            } else if (bp.packageSetting == null) {
6575                // This permission is invalid; skip it.
6576                allowed = false;
6577            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6578                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6579                if (allowed) {
6580                    allowedSig = true;
6581                }
6582            } else {
6583                allowed = false;
6584            }
6585            if (DEBUG_INSTALL) {
6586                if (gp != ps) {
6587                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6588                }
6589            }
6590            if (allowed) {
6591                if (!isSystemApp(ps) && ps.permissionsFixed) {
6592                    // If this is an existing, non-system package, then
6593                    // we can't add any new permissions to it.
6594                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6595                        // Except...  if this is a permission that was added
6596                        // to the platform (note: need to only do this when
6597                        // updating the platform).
6598                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6599                    }
6600                }
6601                if (allowed) {
6602                    if (!gp.grantedPermissions.contains(perm)) {
6603                        changedPermission = true;
6604                        gp.grantedPermissions.add(perm);
6605                        gp.gids = appendInts(gp.gids, bp.gids);
6606                    } else if (!ps.haveGids) {
6607                        gp.gids = appendInts(gp.gids, bp.gids);
6608                    }
6609                } else {
6610                    Slog.w(TAG, "Not granting permission " + perm
6611                            + " to package " + pkg.packageName
6612                            + " because it was previously installed without");
6613                }
6614            } else {
6615                if (gp.grantedPermissions.remove(perm)) {
6616                    changedPermission = true;
6617                    gp.gids = removeInts(gp.gids, bp.gids);
6618                    Slog.i(TAG, "Un-granting permission " + perm
6619                            + " from package " + pkg.packageName
6620                            + " (protectionLevel=" + bp.protectionLevel
6621                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6622                            + ")");
6623                } else {
6624                    Slog.w(TAG, "Not granting permission " + perm
6625                            + " to package " + pkg.packageName
6626                            + " (protectionLevel=" + bp.protectionLevel
6627                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6628                            + ")");
6629                }
6630            }
6631        }
6632
6633        if ((changedPermission || replace) && !ps.permissionsFixed &&
6634                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6635            // This is the first that we have heard about this package, so the
6636            // permissions we have now selected are fixed until explicitly
6637            // changed.
6638            ps.permissionsFixed = true;
6639        }
6640        ps.haveGids = true;
6641    }
6642
6643    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6644        boolean allowed = false;
6645        final int NP = PackageParser.NEW_PERMISSIONS.length;
6646        for (int ip=0; ip<NP; ip++) {
6647            final PackageParser.NewPermissionInfo npi
6648                    = PackageParser.NEW_PERMISSIONS[ip];
6649            if (npi.name.equals(perm)
6650                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6651                allowed = true;
6652                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6653                        + pkg.packageName);
6654                break;
6655            }
6656        }
6657        return allowed;
6658    }
6659
6660    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6661                                          BasePermission bp, HashSet<String> origPermissions) {
6662        boolean allowed;
6663        allowed = (compareSignatures(
6664                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6665                        == PackageManager.SIGNATURE_MATCH)
6666                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6667                        == PackageManager.SIGNATURE_MATCH);
6668        if (!allowed && (bp.protectionLevel
6669                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6670            if (isSystemApp(pkg)) {
6671                // For updated system applications, a system permission
6672                // is granted only if it had been defined by the original application.
6673                if (isUpdatedSystemApp(pkg)) {
6674                    final PackageSetting sysPs = mSettings
6675                            .getDisabledSystemPkgLPr(pkg.packageName);
6676                    final GrantedPermissions origGp = sysPs.sharedUser != null
6677                            ? sysPs.sharedUser : sysPs;
6678
6679                    if (origGp.grantedPermissions.contains(perm)) {
6680                        // If the original was granted this permission, we take
6681                        // that grant decision as read and propagate it to the
6682                        // update.
6683                        allowed = true;
6684                    } else {
6685                        // The system apk may have been updated with an older
6686                        // version of the one on the data partition, but which
6687                        // granted a new system permission that it didn't have
6688                        // before.  In this case we do want to allow the app to
6689                        // now get the new permission if the ancestral apk is
6690                        // privileged to get it.
6691                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6692                            for (int j=0;
6693                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6694                                if (perm.equals(
6695                                        sysPs.pkg.requestedPermissions.get(j))) {
6696                                    allowed = true;
6697                                    break;
6698                                }
6699                            }
6700                        }
6701                    }
6702                } else {
6703                    allowed = isPrivilegedApp(pkg);
6704                }
6705            }
6706        }
6707        if (!allowed && (bp.protectionLevel
6708                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6709            // For development permissions, a development permission
6710            // is granted only if it was already granted.
6711            allowed = origPermissions.contains(perm);
6712        }
6713        return allowed;
6714    }
6715
6716    final class ActivityIntentResolver
6717            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6718        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6719                boolean defaultOnly, int userId) {
6720            if (!sUserManager.exists(userId)) return null;
6721            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6722            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6723        }
6724
6725        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6726                int userId) {
6727            if (!sUserManager.exists(userId)) return null;
6728            mFlags = flags;
6729            return super.queryIntent(intent, resolvedType,
6730                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6731        }
6732
6733        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6734                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6735            if (!sUserManager.exists(userId)) return null;
6736            if (packageActivities == null) {
6737                return null;
6738            }
6739            mFlags = flags;
6740            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6741            final int N = packageActivities.size();
6742            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6743                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6744
6745            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6746            for (int i = 0; i < N; ++i) {
6747                intentFilters = packageActivities.get(i).intents;
6748                if (intentFilters != null && intentFilters.size() > 0) {
6749                    PackageParser.ActivityIntentInfo[] array =
6750                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6751                    intentFilters.toArray(array);
6752                    listCut.add(array);
6753                }
6754            }
6755            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6756        }
6757
6758        public final void addActivity(PackageParser.Activity a, String type) {
6759            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6760            mActivities.put(a.getComponentName(), a);
6761            if (DEBUG_SHOW_INFO)
6762                Log.v(
6763                TAG, "  " + type + " " +
6764                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
6765            if (DEBUG_SHOW_INFO)
6766                Log.v(TAG, "    Class=" + a.info.name);
6767            final int NI = a.intents.size();
6768            for (int j=0; j<NI; j++) {
6769                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6770                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
6771                    intent.setPriority(0);
6772                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
6773                            + a.className + " with priority > 0, forcing to 0");
6774                }
6775                if (DEBUG_SHOW_INFO) {
6776                    Log.v(TAG, "    IntentFilter:");
6777                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6778                }
6779                if (!intent.debugCheck()) {
6780                    Log.w(TAG, "==> For Activity " + a.info.name);
6781                }
6782                addFilter(intent);
6783            }
6784        }
6785
6786        public final void removeActivity(PackageParser.Activity a, String type) {
6787            mActivities.remove(a.getComponentName());
6788            if (DEBUG_SHOW_INFO) {
6789                Log.v(TAG, "  " + type + " "
6790                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
6791                                : a.info.name) + ":");
6792                Log.v(TAG, "    Class=" + a.info.name);
6793            }
6794            final int NI = a.intents.size();
6795            for (int j=0; j<NI; j++) {
6796                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
6797                if (DEBUG_SHOW_INFO) {
6798                    Log.v(TAG, "    IntentFilter:");
6799                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6800                }
6801                removeFilter(intent);
6802            }
6803        }
6804
6805        @Override
6806        protected boolean allowFilterResult(
6807                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
6808            ActivityInfo filterAi = filter.activity.info;
6809            for (int i=dest.size()-1; i>=0; i--) {
6810                ActivityInfo destAi = dest.get(i).activityInfo;
6811                if (destAi.name == filterAi.name
6812                        && destAi.packageName == filterAi.packageName) {
6813                    return false;
6814                }
6815            }
6816            return true;
6817        }
6818
6819        @Override
6820        protected ActivityIntentInfo[] newArray(int size) {
6821            return new ActivityIntentInfo[size];
6822        }
6823
6824        @Override
6825        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
6826            if (!sUserManager.exists(userId)) return true;
6827            PackageParser.Package p = filter.activity.owner;
6828            if (p != null) {
6829                PackageSetting ps = (PackageSetting)p.mExtras;
6830                if (ps != null) {
6831                    // System apps are never considered stopped for purposes of
6832                    // filtering, because there may be no way for the user to
6833                    // actually re-launch them.
6834                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
6835                            && ps.getStopped(userId);
6836                }
6837            }
6838            return false;
6839        }
6840
6841        @Override
6842        protected boolean isPackageForFilter(String packageName,
6843                PackageParser.ActivityIntentInfo info) {
6844            return packageName.equals(info.activity.owner.packageName);
6845        }
6846
6847        @Override
6848        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
6849                int match, int userId) {
6850            if (!sUserManager.exists(userId)) return null;
6851            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
6852                return null;
6853            }
6854            final PackageParser.Activity activity = info.activity;
6855            if (mSafeMode && (activity.info.applicationInfo.flags
6856                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
6857                return null;
6858            }
6859            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
6860            if (ps == null) {
6861                return null;
6862            }
6863            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
6864                    ps.readUserState(userId), userId);
6865            if (ai == null) {
6866                return null;
6867            }
6868            final ResolveInfo res = new ResolveInfo();
6869            res.activityInfo = ai;
6870            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
6871                res.filter = info;
6872            }
6873            res.priority = info.getPriority();
6874            res.preferredOrder = activity.owner.mPreferredOrder;
6875            //System.out.println("Result: " + res.activityInfo.className +
6876            //                   " = " + res.priority);
6877            res.match = match;
6878            res.isDefault = info.hasDefault;
6879            res.labelRes = info.labelRes;
6880            res.nonLocalizedLabel = info.nonLocalizedLabel;
6881            if (userNeedsBadging(userId)) {
6882                res.noResourceId = true;
6883            } else {
6884                res.icon = info.icon;
6885            }
6886            res.system = isSystemApp(res.activityInfo.applicationInfo);
6887            return res;
6888        }
6889
6890        @Override
6891        protected void sortResults(List<ResolveInfo> results) {
6892            Collections.sort(results, mResolvePrioritySorter);
6893        }
6894
6895        @Override
6896        protected void dumpFilter(PrintWriter out, String prefix,
6897                PackageParser.ActivityIntentInfo filter) {
6898            out.print(prefix); out.print(
6899                    Integer.toHexString(System.identityHashCode(filter.activity)));
6900                    out.print(' ');
6901                    filter.activity.printComponentShortName(out);
6902                    out.print(" filter ");
6903                    out.println(Integer.toHexString(System.identityHashCode(filter)));
6904        }
6905
6906//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
6907//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
6908//            final List<ResolveInfo> retList = Lists.newArrayList();
6909//            while (i.hasNext()) {
6910//                final ResolveInfo resolveInfo = i.next();
6911//                if (isEnabledLP(resolveInfo.activityInfo)) {
6912//                    retList.add(resolveInfo);
6913//                }
6914//            }
6915//            return retList;
6916//        }
6917
6918        // Keys are String (activity class name), values are Activity.
6919        private final HashMap<ComponentName, PackageParser.Activity> mActivities
6920                = new HashMap<ComponentName, PackageParser.Activity>();
6921        private int mFlags;
6922    }
6923
6924    private final class ServiceIntentResolver
6925            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
6926        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6927                boolean defaultOnly, int userId) {
6928            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6929            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6930        }
6931
6932        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6933                int userId) {
6934            if (!sUserManager.exists(userId)) return null;
6935            mFlags = flags;
6936            return super.queryIntent(intent, resolvedType,
6937                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6938        }
6939
6940        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6941                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
6942            if (!sUserManager.exists(userId)) return null;
6943            if (packageServices == null) {
6944                return null;
6945            }
6946            mFlags = flags;
6947            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6948            final int N = packageServices.size();
6949            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
6950                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
6951
6952            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
6953            for (int i = 0; i < N; ++i) {
6954                intentFilters = packageServices.get(i).intents;
6955                if (intentFilters != null && intentFilters.size() > 0) {
6956                    PackageParser.ServiceIntentInfo[] array =
6957                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
6958                    intentFilters.toArray(array);
6959                    listCut.add(array);
6960                }
6961            }
6962            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6963        }
6964
6965        public final void addService(PackageParser.Service s) {
6966            mServices.put(s.getComponentName(), s);
6967            if (DEBUG_SHOW_INFO) {
6968                Log.v(TAG, "  "
6969                        + (s.info.nonLocalizedLabel != null
6970                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6971                Log.v(TAG, "    Class=" + s.info.name);
6972            }
6973            final int NI = s.intents.size();
6974            int j;
6975            for (j=0; j<NI; j++) {
6976                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6977                if (DEBUG_SHOW_INFO) {
6978                    Log.v(TAG, "    IntentFilter:");
6979                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
6980                }
6981                if (!intent.debugCheck()) {
6982                    Log.w(TAG, "==> For Service " + s.info.name);
6983                }
6984                addFilter(intent);
6985            }
6986        }
6987
6988        public final void removeService(PackageParser.Service s) {
6989            mServices.remove(s.getComponentName());
6990            if (DEBUG_SHOW_INFO) {
6991                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
6992                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
6993                Log.v(TAG, "    Class=" + s.info.name);
6994            }
6995            final int NI = s.intents.size();
6996            int j;
6997            for (j=0; j<NI; j++) {
6998                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
6999                if (DEBUG_SHOW_INFO) {
7000                    Log.v(TAG, "    IntentFilter:");
7001                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7002                }
7003                removeFilter(intent);
7004            }
7005        }
7006
7007        @Override
7008        protected boolean allowFilterResult(
7009                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7010            ServiceInfo filterSi = filter.service.info;
7011            for (int i=dest.size()-1; i>=0; i--) {
7012                ServiceInfo destAi = dest.get(i).serviceInfo;
7013                if (destAi.name == filterSi.name
7014                        && destAi.packageName == filterSi.packageName) {
7015                    return false;
7016                }
7017            }
7018            return true;
7019        }
7020
7021        @Override
7022        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7023            return new PackageParser.ServiceIntentInfo[size];
7024        }
7025
7026        @Override
7027        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7028            if (!sUserManager.exists(userId)) return true;
7029            PackageParser.Package p = filter.service.owner;
7030            if (p != null) {
7031                PackageSetting ps = (PackageSetting)p.mExtras;
7032                if (ps != null) {
7033                    // System apps are never considered stopped for purposes of
7034                    // filtering, because there may be no way for the user to
7035                    // actually re-launch them.
7036                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7037                            && ps.getStopped(userId);
7038                }
7039            }
7040            return false;
7041        }
7042
7043        @Override
7044        protected boolean isPackageForFilter(String packageName,
7045                PackageParser.ServiceIntentInfo info) {
7046            return packageName.equals(info.service.owner.packageName);
7047        }
7048
7049        @Override
7050        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7051                int match, int userId) {
7052            if (!sUserManager.exists(userId)) return null;
7053            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7054            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7055                return null;
7056            }
7057            final PackageParser.Service service = info.service;
7058            if (mSafeMode && (service.info.applicationInfo.flags
7059                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7060                return null;
7061            }
7062            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7063            if (ps == null) {
7064                return null;
7065            }
7066            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7067                    ps.readUserState(userId), userId);
7068            if (si == null) {
7069                return null;
7070            }
7071            final ResolveInfo res = new ResolveInfo();
7072            res.serviceInfo = si;
7073            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7074                res.filter = filter;
7075            }
7076            res.priority = info.getPriority();
7077            res.preferredOrder = service.owner.mPreferredOrder;
7078            //System.out.println("Result: " + res.activityInfo.className +
7079            //                   " = " + res.priority);
7080            res.match = match;
7081            res.isDefault = info.hasDefault;
7082            res.labelRes = info.labelRes;
7083            res.nonLocalizedLabel = info.nonLocalizedLabel;
7084            res.icon = info.icon;
7085            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7086            return res;
7087        }
7088
7089        @Override
7090        protected void sortResults(List<ResolveInfo> results) {
7091            Collections.sort(results, mResolvePrioritySorter);
7092        }
7093
7094        @Override
7095        protected void dumpFilter(PrintWriter out, String prefix,
7096                PackageParser.ServiceIntentInfo filter) {
7097            out.print(prefix); out.print(
7098                    Integer.toHexString(System.identityHashCode(filter.service)));
7099                    out.print(' ');
7100                    filter.service.printComponentShortName(out);
7101                    out.print(" filter ");
7102                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7103        }
7104
7105//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7106//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7107//            final List<ResolveInfo> retList = Lists.newArrayList();
7108//            while (i.hasNext()) {
7109//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7110//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7111//                    retList.add(resolveInfo);
7112//                }
7113//            }
7114//            return retList;
7115//        }
7116
7117        // Keys are String (activity class name), values are Activity.
7118        private final HashMap<ComponentName, PackageParser.Service> mServices
7119                = new HashMap<ComponentName, PackageParser.Service>();
7120        private int mFlags;
7121    };
7122
7123    private final class ProviderIntentResolver
7124            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7125        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7126                boolean defaultOnly, int userId) {
7127            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7128            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7129        }
7130
7131        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7132                int userId) {
7133            if (!sUserManager.exists(userId))
7134                return null;
7135            mFlags = flags;
7136            return super.queryIntent(intent, resolvedType,
7137                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7138        }
7139
7140        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7141                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7142            if (!sUserManager.exists(userId))
7143                return null;
7144            if (packageProviders == null) {
7145                return null;
7146            }
7147            mFlags = flags;
7148            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7149            final int N = packageProviders.size();
7150            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7151                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7152
7153            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7154            for (int i = 0; i < N; ++i) {
7155                intentFilters = packageProviders.get(i).intents;
7156                if (intentFilters != null && intentFilters.size() > 0) {
7157                    PackageParser.ProviderIntentInfo[] array =
7158                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7159                    intentFilters.toArray(array);
7160                    listCut.add(array);
7161                }
7162            }
7163            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7164        }
7165
7166        public final void addProvider(PackageParser.Provider p) {
7167            if (mProviders.containsKey(p.getComponentName())) {
7168                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7169                return;
7170            }
7171
7172            mProviders.put(p.getComponentName(), p);
7173            if (DEBUG_SHOW_INFO) {
7174                Log.v(TAG, "  "
7175                        + (p.info.nonLocalizedLabel != null
7176                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7177                Log.v(TAG, "    Class=" + p.info.name);
7178            }
7179            final int NI = p.intents.size();
7180            int j;
7181            for (j = 0; j < NI; j++) {
7182                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7183                if (DEBUG_SHOW_INFO) {
7184                    Log.v(TAG, "    IntentFilter:");
7185                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7186                }
7187                if (!intent.debugCheck()) {
7188                    Log.w(TAG, "==> For Provider " + p.info.name);
7189                }
7190                addFilter(intent);
7191            }
7192        }
7193
7194        public final void removeProvider(PackageParser.Provider p) {
7195            mProviders.remove(p.getComponentName());
7196            if (DEBUG_SHOW_INFO) {
7197                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7198                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7199                Log.v(TAG, "    Class=" + p.info.name);
7200            }
7201            final int NI = p.intents.size();
7202            int j;
7203            for (j = 0; j < NI; j++) {
7204                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7205                if (DEBUG_SHOW_INFO) {
7206                    Log.v(TAG, "    IntentFilter:");
7207                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7208                }
7209                removeFilter(intent);
7210            }
7211        }
7212
7213        @Override
7214        protected boolean allowFilterResult(
7215                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7216            ProviderInfo filterPi = filter.provider.info;
7217            for (int i = dest.size() - 1; i >= 0; i--) {
7218                ProviderInfo destPi = dest.get(i).providerInfo;
7219                if (destPi.name == filterPi.name
7220                        && destPi.packageName == filterPi.packageName) {
7221                    return false;
7222                }
7223            }
7224            return true;
7225        }
7226
7227        @Override
7228        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7229            return new PackageParser.ProviderIntentInfo[size];
7230        }
7231
7232        @Override
7233        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7234            if (!sUserManager.exists(userId))
7235                return true;
7236            PackageParser.Package p = filter.provider.owner;
7237            if (p != null) {
7238                PackageSetting ps = (PackageSetting) p.mExtras;
7239                if (ps != null) {
7240                    // System apps are never considered stopped for purposes of
7241                    // filtering, because there may be no way for the user to
7242                    // actually re-launch them.
7243                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7244                            && ps.getStopped(userId);
7245                }
7246            }
7247            return false;
7248        }
7249
7250        @Override
7251        protected boolean isPackageForFilter(String packageName,
7252                PackageParser.ProviderIntentInfo info) {
7253            return packageName.equals(info.provider.owner.packageName);
7254        }
7255
7256        @Override
7257        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7258                int match, int userId) {
7259            if (!sUserManager.exists(userId))
7260                return null;
7261            final PackageParser.ProviderIntentInfo info = filter;
7262            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7263                return null;
7264            }
7265            final PackageParser.Provider provider = info.provider;
7266            if (mSafeMode && (provider.info.applicationInfo.flags
7267                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7268                return null;
7269            }
7270            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7271            if (ps == null) {
7272                return null;
7273            }
7274            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7275                    ps.readUserState(userId), userId);
7276            if (pi == null) {
7277                return null;
7278            }
7279            final ResolveInfo res = new ResolveInfo();
7280            res.providerInfo = pi;
7281            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7282                res.filter = filter;
7283            }
7284            res.priority = info.getPriority();
7285            res.preferredOrder = provider.owner.mPreferredOrder;
7286            res.match = match;
7287            res.isDefault = info.hasDefault;
7288            res.labelRes = info.labelRes;
7289            res.nonLocalizedLabel = info.nonLocalizedLabel;
7290            res.icon = info.icon;
7291            res.system = isSystemApp(res.providerInfo.applicationInfo);
7292            return res;
7293        }
7294
7295        @Override
7296        protected void sortResults(List<ResolveInfo> results) {
7297            Collections.sort(results, mResolvePrioritySorter);
7298        }
7299
7300        @Override
7301        protected void dumpFilter(PrintWriter out, String prefix,
7302                PackageParser.ProviderIntentInfo filter) {
7303            out.print(prefix);
7304            out.print(
7305                    Integer.toHexString(System.identityHashCode(filter.provider)));
7306            out.print(' ');
7307            filter.provider.printComponentShortName(out);
7308            out.print(" filter ");
7309            out.println(Integer.toHexString(System.identityHashCode(filter)));
7310        }
7311
7312        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7313                = new HashMap<ComponentName, PackageParser.Provider>();
7314        private int mFlags;
7315    };
7316
7317    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7318            new Comparator<ResolveInfo>() {
7319        public int compare(ResolveInfo r1, ResolveInfo r2) {
7320            int v1 = r1.priority;
7321            int v2 = r2.priority;
7322            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7323            if (v1 != v2) {
7324                return (v1 > v2) ? -1 : 1;
7325            }
7326            v1 = r1.preferredOrder;
7327            v2 = r2.preferredOrder;
7328            if (v1 != v2) {
7329                return (v1 > v2) ? -1 : 1;
7330            }
7331            if (r1.isDefault != r2.isDefault) {
7332                return r1.isDefault ? -1 : 1;
7333            }
7334            v1 = r1.match;
7335            v2 = r2.match;
7336            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7337            if (v1 != v2) {
7338                return (v1 > v2) ? -1 : 1;
7339            }
7340            if (r1.system != r2.system) {
7341                return r1.system ? -1 : 1;
7342            }
7343            return 0;
7344        }
7345    };
7346
7347    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7348            new Comparator<ProviderInfo>() {
7349        public int compare(ProviderInfo p1, ProviderInfo p2) {
7350            final int v1 = p1.initOrder;
7351            final int v2 = p2.initOrder;
7352            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7353        }
7354    };
7355
7356    static final void sendPackageBroadcast(String action, String pkg,
7357            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7358            int[] userIds) {
7359        IActivityManager am = ActivityManagerNative.getDefault();
7360        if (am != null) {
7361            try {
7362                if (userIds == null) {
7363                    userIds = am.getRunningUserIds();
7364                }
7365                for (int id : userIds) {
7366                    final Intent intent = new Intent(action,
7367                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7368                    if (extras != null) {
7369                        intent.putExtras(extras);
7370                    }
7371                    if (targetPkg != null) {
7372                        intent.setPackage(targetPkg);
7373                    }
7374                    // Modify the UID when posting to other users
7375                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7376                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7377                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7378                        intent.putExtra(Intent.EXTRA_UID, uid);
7379                    }
7380                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7381                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7382                    if (DEBUG_BROADCASTS) {
7383                        RuntimeException here = new RuntimeException("here");
7384                        here.fillInStackTrace();
7385                        Slog.d(TAG, "Sending to user " + id + ": "
7386                                + intent.toShortString(false, true, false, false)
7387                                + " " + intent.getExtras(), here);
7388                    }
7389                    am.broadcastIntent(null, intent, null, finishedReceiver,
7390                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7391                            finishedReceiver != null, false, id);
7392                }
7393            } catch (RemoteException ex) {
7394            }
7395        }
7396    }
7397
7398    /**
7399     * Check if the external storage media is available. This is true if there
7400     * is a mounted external storage medium or if the external storage is
7401     * emulated.
7402     */
7403    private boolean isExternalMediaAvailable() {
7404        return mMediaMounted || Environment.isExternalStorageEmulated();
7405    }
7406
7407    @Override
7408    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7409        // writer
7410        synchronized (mPackages) {
7411            if (!isExternalMediaAvailable()) {
7412                // If the external storage is no longer mounted at this point,
7413                // the caller may not have been able to delete all of this
7414                // packages files and can not delete any more.  Bail.
7415                return null;
7416            }
7417            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7418            if (lastPackage != null) {
7419                pkgs.remove(lastPackage);
7420            }
7421            if (pkgs.size() > 0) {
7422                return pkgs.get(0);
7423            }
7424        }
7425        return null;
7426    }
7427
7428    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7429        if (false) {
7430            RuntimeException here = new RuntimeException("here");
7431            here.fillInStackTrace();
7432            Slog.d(TAG, "Schedule cleaning " + packageName + " user=" + userId
7433                    + " andCode=" + andCode, here);
7434        }
7435        mHandler.sendMessage(mHandler.obtainMessage(START_CLEANING_PACKAGE,
7436                userId, andCode ? 1 : 0, packageName));
7437    }
7438
7439    void startCleaningPackages() {
7440        // reader
7441        synchronized (mPackages) {
7442            if (!isExternalMediaAvailable()) {
7443                return;
7444            }
7445            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7446                return;
7447            }
7448        }
7449        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7450        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7451        IActivityManager am = ActivityManagerNative.getDefault();
7452        if (am != null) {
7453            try {
7454                am.startService(null, intent, null, UserHandle.USER_OWNER);
7455            } catch (RemoteException e) {
7456            }
7457        }
7458    }
7459
7460    private final class AppDirObserver extends FileObserver {
7461        public AppDirObserver(String path, int mask, boolean isrom, boolean isPrivileged) {
7462            super(path, mask);
7463            mRootDir = path;
7464            mIsRom = isrom;
7465            mIsPrivileged = isPrivileged;
7466        }
7467
7468        public void onEvent(int event, String path) {
7469            String removedPackage = null;
7470            int removedAppId = -1;
7471            int[] removedUsers = null;
7472            String addedPackage = null;
7473            int addedAppId = -1;
7474            int[] addedUsers = null;
7475
7476            // TODO post a message to the handler to obtain serial ordering
7477            synchronized (mInstallLock) {
7478                String fullPathStr = null;
7479                File fullPath = null;
7480                if (path != null) {
7481                    fullPath = new File(mRootDir, path);
7482                    fullPathStr = fullPath.getPath();
7483                }
7484
7485                if (DEBUG_APP_DIR_OBSERVER)
7486                    Log.v(TAG, "File " + fullPathStr + " changed: " + Integer.toHexString(event));
7487
7488                if (!isApkFile(fullPath)) {
7489                    if (DEBUG_APP_DIR_OBSERVER)
7490                        Log.v(TAG, "Ignoring change of non-package file: " + fullPathStr);
7491                    return;
7492                }
7493
7494                // Ignore packages that are being installed or
7495                // have just been installed.
7496                if (ignoreCodePath(fullPathStr)) {
7497                    return;
7498                }
7499                PackageParser.Package p = null;
7500                PackageSetting ps = null;
7501                // reader
7502                synchronized (mPackages) {
7503                    p = mAppDirs.get(fullPathStr);
7504                    if (p != null) {
7505                        ps = mSettings.mPackages.get(p.applicationInfo.packageName);
7506                        if (ps != null) {
7507                            removedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
7508                        } else {
7509                            removedUsers = sUserManager.getUserIds();
7510                        }
7511                    }
7512                    addedUsers = sUserManager.getUserIds();
7513                }
7514                if ((event&REMOVE_EVENTS) != 0) {
7515                    if (ps != null) {
7516                        if (DEBUG_REMOVE) Slog.d(TAG, "Package disappeared: " + ps);
7517                        removePackageLI(ps, true);
7518                        removedPackage = ps.name;
7519                        removedAppId = ps.appId;
7520                    }
7521                }
7522
7523                if ((event&ADD_EVENTS) != 0) {
7524                    if (p == null) {
7525                        if (DEBUG_INSTALL) Slog.d(TAG, "New file appeared: " + fullPath);
7526                        int flags = PackageParser.PARSE_CHATTY | PackageParser.PARSE_MUST_BE_APK;
7527                        if (mIsRom) {
7528                            flags |= PackageParser.PARSE_IS_SYSTEM
7529                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
7530                            if (mIsPrivileged) {
7531                                flags |= PackageParser.PARSE_IS_PRIVILEGED;
7532                            }
7533                        }
7534                        p = scanPackageLI(fullPath, flags,
7535                                SCAN_MONITOR | SCAN_NO_PATHS | SCAN_UPDATE_TIME,
7536                                System.currentTimeMillis(), UserHandle.ALL, null);
7537                        if (p != null) {
7538                            /*
7539                             * TODO this seems dangerous as the package may have
7540                             * changed since we last acquired the mPackages
7541                             * lock.
7542                             */
7543                            // writer
7544                            synchronized (mPackages) {
7545                                updatePermissionsLPw(p.packageName, p,
7546                                        p.permissions.size() > 0 ? UPDATE_PERMISSIONS_ALL : 0);
7547                            }
7548                            addedPackage = p.applicationInfo.packageName;
7549                            addedAppId = UserHandle.getAppId(p.applicationInfo.uid);
7550                        }
7551                    }
7552                }
7553
7554                // reader
7555                synchronized (mPackages) {
7556                    mSettings.writeLPr();
7557                }
7558            }
7559
7560            if (removedPackage != null) {
7561                Bundle extras = new Bundle(1);
7562                extras.putInt(Intent.EXTRA_UID, removedAppId);
7563                extras.putBoolean(Intent.EXTRA_DATA_REMOVED, false);
7564                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
7565                        extras, null, null, removedUsers);
7566            }
7567            if (addedPackage != null) {
7568                Bundle extras = new Bundle(1);
7569                extras.putInt(Intent.EXTRA_UID, addedAppId);
7570                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, addedPackage,
7571                        extras, null, null, addedUsers);
7572            }
7573        }
7574
7575        private final String mRootDir;
7576        private final boolean mIsRom;
7577        private final boolean mIsPrivileged;
7578    }
7579
7580    /*
7581     * The old-style observer methods all just trampoline to the newer signature with
7582     * expanded install observer API.  The older API continues to work but does not
7583     * supply the additional details of the Observer2 API.
7584     */
7585
7586    /* Called when a downloaded package installation has been confirmed by the user */
7587    public void installPackage(
7588            final Uri packageURI, final IPackageInstallObserver observer, final int flags) {
7589        installPackageEtc(packageURI, observer, null, flags, null);
7590    }
7591
7592    /* Called when a downloaded package installation has been confirmed by the user */
7593    @Override
7594    public void installPackage(
7595            final Uri packageURI, final IPackageInstallObserver observer, final int flags,
7596            final String installerPackageName) {
7597        installPackageWithVerificationEtc(packageURI, observer, null, flags,
7598                installerPackageName, null, null, null);
7599    }
7600
7601    @Override
7602    public void installPackageWithVerification(Uri packageURI, IPackageInstallObserver observer,
7603            int flags, String installerPackageName, Uri verificationURI,
7604            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7605        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7606                VerificationParams.NO_UID, manifestDigest);
7607        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7608                installerPackageName, verificationParams, encryptionParams);
7609    }
7610
7611    @Override
7612    public void installPackageWithVerificationAndEncryption(Uri packageURI,
7613            IPackageInstallObserver observer, int flags, String installerPackageName,
7614            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7615        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, null, flags,
7616                installerPackageName, verificationParams, encryptionParams);
7617    }
7618
7619    /*
7620     * And here are the "live" versions that take both observer arguments
7621     */
7622    public void installPackageEtc(
7623            final Uri packageURI, final IPackageInstallObserver observer,
7624            IPackageInstallObserver2 observer2, final int flags) {
7625        installPackageEtc(packageURI, observer, observer2, flags, null);
7626    }
7627
7628    public void installPackageEtc(
7629            final Uri packageURI, final IPackageInstallObserver observer,
7630            final IPackageInstallObserver2 observer2, final int flags,
7631            final String installerPackageName) {
7632        installPackageWithVerificationEtc(packageURI, observer, observer2, flags,
7633                installerPackageName, null, null, null);
7634    }
7635
7636    @Override
7637    public void installPackageWithVerificationEtc(Uri packageURI, IPackageInstallObserver observer,
7638            IPackageInstallObserver2 observer2,
7639            int flags, String installerPackageName, Uri verificationURI,
7640            ManifestDigest manifestDigest, ContainerEncryptionParams encryptionParams) {
7641        VerificationParams verificationParams = new VerificationParams(verificationURI, null, null,
7642                VerificationParams.NO_UID, manifestDigest);
7643        installPackageWithVerificationAndEncryptionEtc(packageURI, observer, observer2, flags,
7644                installerPackageName, verificationParams, encryptionParams);
7645    }
7646
7647    /*
7648     * All of the installPackage...*() methods redirect to this one for the master implementation
7649     */
7650    public void installPackageWithVerificationAndEncryptionEtc(Uri packageURI,
7651            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7652            int flags, String installerPackageName,
7653            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams) {
7654        if (observer == null && observer2 == null) {
7655            throw new IllegalArgumentException("No install observer supplied");
7656        }
7657        installPackageWithVerificationEncryptionAndAbiOverrideEtc(packageURI, observer, observer2,
7658                flags, installerPackageName, verificationParams, encryptionParams, null);
7659    }
7660
7661    @Override
7662    public void installPackageWithVerificationEncryptionAndAbiOverrideEtc(Uri packageURI,
7663            IPackageInstallObserver observer, IPackageInstallObserver2 observer2,
7664            int flags, String installerPackageName,
7665            VerificationParams verificationParams, ContainerEncryptionParams encryptionParams,
7666            String packageAbiOverride) {
7667        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7668                null);
7669
7670        final int uid = Binder.getCallingUid();
7671        if (isUserRestricted(UserHandle.getUserId(uid), UserManager.DISALLOW_INSTALL_APPS)) {
7672            try {
7673                if (observer != null) {
7674                    observer.packageInstalled("", PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7675                }
7676                if (observer2 != null) {
7677                    observer2.packageInstalled("", null, PackageManager.INSTALL_FAILED_USER_RESTRICTED);
7678                }
7679            } catch (RemoteException re) {
7680            }
7681            return;
7682        }
7683
7684        UserHandle user;
7685        if ((flags&PackageManager.INSTALL_ALL_USERS) != 0) {
7686            user = UserHandle.ALL;
7687        } else {
7688            user = new UserHandle(UserHandle.getUserId(uid));
7689        }
7690
7691        final int filteredFlags;
7692
7693        if (uid == Process.SHELL_UID || uid == 0) {
7694            if (DEBUG_INSTALL) {
7695                Slog.v(TAG, "Install from ADB");
7696            }
7697            filteredFlags = flags | PackageManager.INSTALL_FROM_ADB;
7698        } else {
7699            filteredFlags = flags & ~PackageManager.INSTALL_FROM_ADB;
7700        }
7701
7702        verificationParams.setInstallerUid(uid);
7703
7704        if (!"file".equals(packageURI.getScheme())) {
7705            throw new UnsupportedOperationException("Only file:// URIs are supported");
7706        }
7707        final File fromFile = new File(packageURI.getPath());
7708
7709        if (encryptionParams != null) {
7710            throw new UnsupportedOperationException("ContainerEncryptionParams not supported");
7711        }
7712
7713        final Message msg = mHandler.obtainMessage(INIT_COPY);
7714        msg.obj = new InstallParams(fromFile, observer, observer2, filteredFlags,
7715                installerPackageName, verificationParams, user, packageAbiOverride);
7716        mHandler.sendMessage(msg);
7717    }
7718
7719    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7720        Bundle extras = new Bundle(1);
7721        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7722
7723        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7724                packageName, extras, null, null, new int[] {userId});
7725        try {
7726            IActivityManager am = ActivityManagerNative.getDefault();
7727            final boolean isSystem =
7728                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7729            if (isSystem && am.isUserRunning(userId, false)) {
7730                // The just-installed/enabled app is bundled on the system, so presumed
7731                // to be able to run automatically without needing an explicit launch.
7732                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7733                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7734                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7735                        .setPackage(packageName);
7736                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7737                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7738            }
7739        } catch (RemoteException e) {
7740            // shouldn't happen
7741            Slog.w(TAG, "Unable to bootstrap installed package", e);
7742        }
7743    }
7744
7745    @Override
7746    public boolean setApplicationBlockedSettingAsUser(String packageName, boolean blocked,
7747            int userId) {
7748        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7749        PackageSetting pkgSetting;
7750        final int uid = Binder.getCallingUid();
7751        if (UserHandle.getUserId(uid) != userId) {
7752            mContext.enforceCallingOrSelfPermission(
7753                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
7754                    "setApplicationBlockedSetting for user " + userId);
7755        }
7756
7757        if (blocked && isPackageDeviceAdmin(packageName, userId)) {
7758            Slog.w(TAG, "Not blocking package " + packageName + ": has active device admin");
7759            return false;
7760        }
7761
7762        long callingId = Binder.clearCallingIdentity();
7763        try {
7764            boolean sendAdded = false;
7765            boolean sendRemoved = false;
7766            // writer
7767            synchronized (mPackages) {
7768                pkgSetting = mSettings.mPackages.get(packageName);
7769                if (pkgSetting == null) {
7770                    return false;
7771                }
7772                if (pkgSetting.getBlocked(userId) != blocked) {
7773                    pkgSetting.setBlocked(blocked, userId);
7774                    mSettings.writePackageRestrictionsLPr(userId);
7775                    if (blocked) {
7776                        sendRemoved = true;
7777                    } else {
7778                        sendAdded = true;
7779                    }
7780                }
7781            }
7782            if (sendAdded) {
7783                sendPackageAddedForUser(packageName, pkgSetting, userId);
7784                return true;
7785            }
7786            if (sendRemoved) {
7787                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7788                        "blocking pkg");
7789                sendPackageBlockedForUser(packageName, pkgSetting, userId);
7790            }
7791        } finally {
7792            Binder.restoreCallingIdentity(callingId);
7793        }
7794        return false;
7795    }
7796
7797    private void sendPackageBlockedForUser(String packageName, PackageSetting pkgSetting,
7798            int userId) {
7799        final PackageRemovedInfo info = new PackageRemovedInfo();
7800        info.removedPackage = packageName;
7801        info.removedUsers = new int[] {userId};
7802        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7803        info.sendBroadcast(false, false, false);
7804    }
7805
7806    /**
7807     * Returns true if application is not found or there was an error. Otherwise it returns
7808     * the blocked state of the package for the given user.
7809     */
7810    @Override
7811    public boolean getApplicationBlockedSettingAsUser(String packageName, int userId) {
7812        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7813        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7814                "getApplicationBlocked for user " + userId);
7815        PackageSetting pkgSetting;
7816        long callingId = Binder.clearCallingIdentity();
7817        try {
7818            // writer
7819            synchronized (mPackages) {
7820                pkgSetting = mSettings.mPackages.get(packageName);
7821                if (pkgSetting == null) {
7822                    return true;
7823                }
7824                return pkgSetting.getBlocked(userId);
7825            }
7826        } finally {
7827            Binder.restoreCallingIdentity(callingId);
7828        }
7829    }
7830
7831    void installStage(String packageName, File stageDir, IPackageInstallObserver2 observer2,
7832            PackageInstallerParams params, String installerPackageName, int installerUid,
7833            UserHandle user) {
7834        Slog.e(TAG, "TODO: install stage!");
7835        try {
7836            observer2.packageInstalled(packageName, null,
7837                    PackageManager.INSTALL_FAILED_INTERNAL_ERROR);
7838        } catch (RemoteException ignored) {
7839        }
7840    }
7841
7842    /**
7843     * @hide
7844     */
7845    @Override
7846    public int installExistingPackageAsUser(String packageName, int userId) {
7847        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7848                null);
7849        PackageSetting pkgSetting;
7850        final int uid = Binder.getCallingUid();
7851        enforceCrossUserPermission(uid, userId, true, "installExistingPackage for user " + userId);
7852        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7853            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7854        }
7855
7856        long callingId = Binder.clearCallingIdentity();
7857        try {
7858            boolean sendAdded = false;
7859            Bundle extras = new Bundle(1);
7860
7861            // writer
7862            synchronized (mPackages) {
7863                pkgSetting = mSettings.mPackages.get(packageName);
7864                if (pkgSetting == null) {
7865                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7866                }
7867                if (!pkgSetting.getInstalled(userId)) {
7868                    pkgSetting.setInstalled(true, userId);
7869                    pkgSetting.setBlocked(false, userId);
7870                    mSettings.writePackageRestrictionsLPr(userId);
7871                    sendAdded = true;
7872                }
7873            }
7874
7875            if (sendAdded) {
7876                sendPackageAddedForUser(packageName, pkgSetting, userId);
7877            }
7878        } finally {
7879            Binder.restoreCallingIdentity(callingId);
7880        }
7881
7882        return PackageManager.INSTALL_SUCCEEDED;
7883    }
7884
7885    boolean isUserRestricted(int userId, String restrictionKey) {
7886        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7887        if (restrictions.getBoolean(restrictionKey, false)) {
7888            Log.w(TAG, "User is restricted: " + restrictionKey);
7889            return true;
7890        }
7891        return false;
7892    }
7893
7894    @Override
7895    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7896        mContext.enforceCallingOrSelfPermission(
7897                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7898                "Only package verification agents can verify applications");
7899
7900        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7901        final PackageVerificationResponse response = new PackageVerificationResponse(
7902                verificationCode, Binder.getCallingUid());
7903        msg.arg1 = id;
7904        msg.obj = response;
7905        mHandler.sendMessage(msg);
7906    }
7907
7908    @Override
7909    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7910            long millisecondsToDelay) {
7911        mContext.enforceCallingOrSelfPermission(
7912                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7913                "Only package verification agents can extend verification timeouts");
7914
7915        final PackageVerificationState state = mPendingVerification.get(id);
7916        final PackageVerificationResponse response = new PackageVerificationResponse(
7917                verificationCodeAtTimeout, Binder.getCallingUid());
7918
7919        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7920            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7921        }
7922        if (millisecondsToDelay < 0) {
7923            millisecondsToDelay = 0;
7924        }
7925        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7926                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7927            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7928        }
7929
7930        if ((state != null) && !state.timeoutExtended()) {
7931            state.extendTimeout();
7932
7933            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7934            msg.arg1 = id;
7935            msg.obj = response;
7936            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7937        }
7938    }
7939
7940    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7941            int verificationCode, UserHandle user) {
7942        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7943        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7944        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7945        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7946        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7947
7948        mContext.sendBroadcastAsUser(intent, user,
7949                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7950    }
7951
7952    private ComponentName matchComponentForVerifier(String packageName,
7953            List<ResolveInfo> receivers) {
7954        ActivityInfo targetReceiver = null;
7955
7956        final int NR = receivers.size();
7957        for (int i = 0; i < NR; i++) {
7958            final ResolveInfo info = receivers.get(i);
7959            if (info.activityInfo == null) {
7960                continue;
7961            }
7962
7963            if (packageName.equals(info.activityInfo.packageName)) {
7964                targetReceiver = info.activityInfo;
7965                break;
7966            }
7967        }
7968
7969        if (targetReceiver == null) {
7970            return null;
7971        }
7972
7973        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
7974    }
7975
7976    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
7977            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
7978        if (pkgInfo.verifiers.length == 0) {
7979            return null;
7980        }
7981
7982        final int N = pkgInfo.verifiers.length;
7983        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
7984        for (int i = 0; i < N; i++) {
7985            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
7986
7987            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
7988                    receivers);
7989            if (comp == null) {
7990                continue;
7991            }
7992
7993            final int verifierUid = getUidForVerifier(verifierInfo);
7994            if (verifierUid == -1) {
7995                continue;
7996            }
7997
7998            if (DEBUG_VERIFY) {
7999                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8000                        + " with the correct signature");
8001            }
8002            sufficientVerifiers.add(comp);
8003            verificationState.addSufficientVerifier(verifierUid);
8004        }
8005
8006        return sufficientVerifiers;
8007    }
8008
8009    private int getUidForVerifier(VerifierInfo verifierInfo) {
8010        synchronized (mPackages) {
8011            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8012            if (pkg == null) {
8013                return -1;
8014            } else if (pkg.mSignatures.length != 1) {
8015                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8016                        + " has more than one signature; ignoring");
8017                return -1;
8018            }
8019
8020            /*
8021             * If the public key of the package's signature does not match
8022             * our expected public key, then this is a different package and
8023             * we should skip.
8024             */
8025
8026            final byte[] expectedPublicKey;
8027            try {
8028                final Signature verifierSig = pkg.mSignatures[0];
8029                final PublicKey publicKey = verifierSig.getPublicKey();
8030                expectedPublicKey = publicKey.getEncoded();
8031            } catch (CertificateException e) {
8032                return -1;
8033            }
8034
8035            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8036
8037            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8038                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8039                        + " does not have the expected public key; ignoring");
8040                return -1;
8041            }
8042
8043            return pkg.applicationInfo.uid;
8044        }
8045    }
8046
8047    @Override
8048    public void finishPackageInstall(int token) {
8049        enforceSystemOrRoot("Only the system is allowed to finish installs");
8050
8051        if (DEBUG_INSTALL) {
8052            Slog.v(TAG, "BM finishing package install for " + token);
8053        }
8054
8055        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8056        mHandler.sendMessage(msg);
8057    }
8058
8059    /**
8060     * Get the verification agent timeout.
8061     *
8062     * @return verification timeout in milliseconds
8063     */
8064    private long getVerificationTimeout() {
8065        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8066                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8067                DEFAULT_VERIFICATION_TIMEOUT);
8068    }
8069
8070    /**
8071     * Get the default verification agent response code.
8072     *
8073     * @return default verification response code
8074     */
8075    private int getDefaultVerificationResponse() {
8076        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8077                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8078                DEFAULT_VERIFICATION_RESPONSE);
8079    }
8080
8081    /**
8082     * Check whether or not package verification has been enabled.
8083     *
8084     * @return true if verification should be performed
8085     */
8086    private boolean isVerificationEnabled(int userId, int flags) {
8087        if (!DEFAULT_VERIFY_ENABLE) {
8088            return false;
8089        }
8090
8091        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8092
8093        // Check if installing from ADB
8094        if ((flags & PackageManager.INSTALL_FROM_ADB) != 0) {
8095            // Do not run verification in a test harness environment
8096            if (ActivityManager.isRunningInTestHarness()) {
8097                return false;
8098            }
8099            if (ensureVerifyAppsEnabled) {
8100                return true;
8101            }
8102            // Check if the developer does not want package verification for ADB installs
8103            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8104                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8105                return false;
8106            }
8107        }
8108
8109        if (ensureVerifyAppsEnabled) {
8110            return true;
8111        }
8112
8113        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8114                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8115    }
8116
8117    /**
8118     * Get the "allow unknown sources" setting.
8119     *
8120     * @return the current "allow unknown sources" setting
8121     */
8122    private int getUnknownSourcesSettings() {
8123        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8124                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8125                -1);
8126    }
8127
8128    @Override
8129    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8130        final int uid = Binder.getCallingUid();
8131        // writer
8132        synchronized (mPackages) {
8133            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8134            if (targetPackageSetting == null) {
8135                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8136            }
8137
8138            PackageSetting installerPackageSetting;
8139            if (installerPackageName != null) {
8140                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8141                if (installerPackageSetting == null) {
8142                    throw new IllegalArgumentException("Unknown installer package: "
8143                            + installerPackageName);
8144                }
8145            } else {
8146                installerPackageSetting = null;
8147            }
8148
8149            Signature[] callerSignature;
8150            Object obj = mSettings.getUserIdLPr(uid);
8151            if (obj != null) {
8152                if (obj instanceof SharedUserSetting) {
8153                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8154                } else if (obj instanceof PackageSetting) {
8155                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8156                } else {
8157                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8158                }
8159            } else {
8160                throw new SecurityException("Unknown calling uid " + uid);
8161            }
8162
8163            // Verify: can't set installerPackageName to a package that is
8164            // not signed with the same cert as the caller.
8165            if (installerPackageSetting != null) {
8166                if (compareSignatures(callerSignature,
8167                        installerPackageSetting.signatures.mSignatures)
8168                        != PackageManager.SIGNATURE_MATCH) {
8169                    throw new SecurityException(
8170                            "Caller does not have same cert as new installer package "
8171                            + installerPackageName);
8172                }
8173            }
8174
8175            // Verify: if target already has an installer package, it must
8176            // be signed with the same cert as the caller.
8177            if (targetPackageSetting.installerPackageName != null) {
8178                PackageSetting setting = mSettings.mPackages.get(
8179                        targetPackageSetting.installerPackageName);
8180                // If the currently set package isn't valid, then it's always
8181                // okay to change it.
8182                if (setting != null) {
8183                    if (compareSignatures(callerSignature,
8184                            setting.signatures.mSignatures)
8185                            != PackageManager.SIGNATURE_MATCH) {
8186                        throw new SecurityException(
8187                                "Caller does not have same cert as old installer package "
8188                                + targetPackageSetting.installerPackageName);
8189                    }
8190                }
8191            }
8192
8193            // Okay!
8194            targetPackageSetting.installerPackageName = installerPackageName;
8195            scheduleWriteSettingsLocked();
8196        }
8197    }
8198
8199    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8200        // Queue up an async operation since the package installation may take a little while.
8201        mHandler.post(new Runnable() {
8202            public void run() {
8203                mHandler.removeCallbacks(this);
8204                 // Result object to be returned
8205                PackageInstalledInfo res = new PackageInstalledInfo();
8206                res.returnCode = currentStatus;
8207                res.uid = -1;
8208                res.pkg = null;
8209                res.removedInfo = new PackageRemovedInfo();
8210                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8211                    args.doPreInstall(res.returnCode);
8212                    synchronized (mInstallLock) {
8213                        installPackageLI(args, true, res);
8214                    }
8215                    args.doPostInstall(res.returnCode, res.uid);
8216                }
8217
8218                // A restore should be performed at this point if (a) the install
8219                // succeeded, (b) the operation is not an update, and (c) the new
8220                // package has a backupAgent defined.
8221                final boolean update = res.removedInfo.removedPackage != null;
8222                boolean doRestore = (!update
8223                        && res.pkg != null
8224                        && res.pkg.applicationInfo.backupAgentName != null);
8225
8226                // Set up the post-install work request bookkeeping.  This will be used
8227                // and cleaned up by the post-install event handling regardless of whether
8228                // there's a restore pass performed.  Token values are >= 1.
8229                int token;
8230                if (mNextInstallToken < 0) mNextInstallToken = 1;
8231                token = mNextInstallToken++;
8232
8233                PostInstallData data = new PostInstallData(args, res);
8234                mRunningInstalls.put(token, data);
8235                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8236
8237                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8238                    // Pass responsibility to the Backup Manager.  It will perform a
8239                    // restore if appropriate, then pass responsibility back to the
8240                    // Package Manager to run the post-install observer callbacks
8241                    // and broadcasts.
8242                    IBackupManager bm = IBackupManager.Stub.asInterface(
8243                            ServiceManager.getService(Context.BACKUP_SERVICE));
8244                    if (bm != null) {
8245                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8246                                + " to BM for possible restore");
8247                        try {
8248                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8249                        } catch (RemoteException e) {
8250                            // can't happen; the backup manager is local
8251                        } catch (Exception e) {
8252                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8253                            doRestore = false;
8254                        }
8255                    } else {
8256                        Slog.e(TAG, "Backup Manager not found!");
8257                        doRestore = false;
8258                    }
8259                }
8260
8261                if (!doRestore) {
8262                    // No restore possible, or the Backup Manager was mysteriously not
8263                    // available -- just fire the post-install work request directly.
8264                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8265                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8266                    mHandler.sendMessage(msg);
8267                }
8268            }
8269        });
8270    }
8271
8272    private abstract class HandlerParams {
8273        private static final int MAX_RETRIES = 4;
8274
8275        /**
8276         * Number of times startCopy() has been attempted and had a non-fatal
8277         * error.
8278         */
8279        private int mRetries = 0;
8280
8281        /** User handle for the user requesting the information or installation. */
8282        private final UserHandle mUser;
8283
8284        HandlerParams(UserHandle user) {
8285            mUser = user;
8286        }
8287
8288        UserHandle getUser() {
8289            return mUser;
8290        }
8291
8292        final boolean startCopy() {
8293            boolean res;
8294            try {
8295                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8296
8297                if (++mRetries > MAX_RETRIES) {
8298                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8299                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8300                    handleServiceError();
8301                    return false;
8302                } else {
8303                    handleStartCopy();
8304                    res = true;
8305                }
8306            } catch (RemoteException e) {
8307                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8308                mHandler.sendEmptyMessage(MCS_RECONNECT);
8309                res = false;
8310            }
8311            handleReturnCode();
8312            return res;
8313        }
8314
8315        final void serviceError() {
8316            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8317            handleServiceError();
8318            handleReturnCode();
8319        }
8320
8321        abstract void handleStartCopy() throws RemoteException;
8322        abstract void handleServiceError();
8323        abstract void handleReturnCode();
8324    }
8325
8326    class MeasureParams extends HandlerParams {
8327        private final PackageStats mStats;
8328        private boolean mSuccess;
8329
8330        private final IPackageStatsObserver mObserver;
8331
8332        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8333            super(new UserHandle(stats.userHandle));
8334            mObserver = observer;
8335            mStats = stats;
8336        }
8337
8338        @Override
8339        public String toString() {
8340            return "MeasureParams{"
8341                + Integer.toHexString(System.identityHashCode(this))
8342                + " " + mStats.packageName + "}";
8343        }
8344
8345        @Override
8346        void handleStartCopy() throws RemoteException {
8347            synchronized (mInstallLock) {
8348                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8349            }
8350
8351            if (mSuccess) {
8352                final boolean mounted;
8353                if (Environment.isExternalStorageEmulated()) {
8354                    mounted = true;
8355                } else {
8356                    final String status = Environment.getExternalStorageState();
8357                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8358                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8359                }
8360
8361                if (mounted) {
8362                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8363
8364                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8365                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8366
8367                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8368                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8369
8370                    // Always subtract cache size, since it's a subdirectory
8371                    mStats.externalDataSize -= mStats.externalCacheSize;
8372
8373                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8374                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8375
8376                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8377                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8378                }
8379            }
8380        }
8381
8382        @Override
8383        void handleReturnCode() {
8384            if (mObserver != null) {
8385                try {
8386                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8387                } catch (RemoteException e) {
8388                    Slog.i(TAG, "Observer no longer exists.");
8389                }
8390            }
8391        }
8392
8393        @Override
8394        void handleServiceError() {
8395            Slog.e(TAG, "Could not measure application " + mStats.packageName
8396                            + " external storage");
8397        }
8398    }
8399
8400    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8401            throws RemoteException {
8402        long result = 0;
8403        for (File path : paths) {
8404            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8405        }
8406        return result;
8407    }
8408
8409    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8410        for (File path : paths) {
8411            try {
8412                mcs.clearDirectory(path.getAbsolutePath());
8413            } catch (RemoteException e) {
8414            }
8415        }
8416    }
8417
8418    class InstallParams extends HandlerParams {
8419        /**
8420         * Location where install is coming from, before it has been
8421         * copied/renamed into place. This could be a single monolithic APK
8422         * file, or a cluster directory. This location may be untrusted.
8423         */
8424        private final File mFromFile;
8425
8426        final IPackageInstallObserver observer;
8427        final IPackageInstallObserver2 observer2;
8428        int flags;
8429        final String installerPackageName;
8430        final VerificationParams verificationParams;
8431        private InstallArgs mArgs;
8432        private int mRet;
8433        final String packageAbiOverride;
8434        final String packageInstructionSetOverride;
8435
8436        InstallParams(File fromFile, IPackageInstallObserver observer,
8437                IPackageInstallObserver2 observer2, int flags, String installerPackageName,
8438                VerificationParams verificationParams, UserHandle user, String packageAbiOverride) {
8439            super(user);
8440            mFromFile = Preconditions.checkNotNull(fromFile);
8441            this.observer = observer;
8442            this.observer2 = observer2;
8443            this.flags = flags;
8444            this.installerPackageName = installerPackageName;
8445            this.verificationParams = verificationParams;
8446            this.packageAbiOverride = packageAbiOverride;
8447            this.packageInstructionSetOverride = (packageAbiOverride == null) ?
8448                    packageAbiOverride : VMRuntime.getInstructionSet(packageAbiOverride);
8449        }
8450
8451        @Override
8452        public String toString() {
8453            return "InstallParams{"
8454                + Integer.toHexString(System.identityHashCode(this))
8455                + " " + mFromFile + "}";
8456        }
8457
8458        public ManifestDigest getManifestDigest() {
8459            if (verificationParams == null) {
8460                return null;
8461            }
8462            return verificationParams.getManifestDigest();
8463        }
8464
8465        private int installLocationPolicy(PackageInfoLite pkgLite, int flags) {
8466            String packageName = pkgLite.packageName;
8467            int installLocation = pkgLite.installLocation;
8468            boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8469            // reader
8470            synchronized (mPackages) {
8471                PackageParser.Package pkg = mPackages.get(packageName);
8472                if (pkg != null) {
8473                    if ((flags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8474                        // Check for downgrading.
8475                        if ((flags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8476                            if (pkgLite.versionCode < pkg.mVersionCode) {
8477                                Slog.w(TAG, "Can't install update of " + packageName
8478                                        + " update version " + pkgLite.versionCode
8479                                        + " is older than installed version "
8480                                        + pkg.mVersionCode);
8481                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8482                            }
8483                        }
8484                        // Check for updated system application.
8485                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8486                            if (onSd) {
8487                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8488                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8489                            }
8490                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8491                        } else {
8492                            if (onSd) {
8493                                // Install flag overrides everything.
8494                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8495                            }
8496                            // If current upgrade specifies particular preference
8497                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8498                                // Application explicitly specified internal.
8499                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8500                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8501                                // App explictly prefers external. Let policy decide
8502                            } else {
8503                                // Prefer previous location
8504                                if (isExternal(pkg)) {
8505                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8506                                }
8507                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8508                            }
8509                        }
8510                    } else {
8511                        // Invalid install. Return error code
8512                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8513                    }
8514                }
8515            }
8516            // All the special cases have been taken care of.
8517            // Return result based on recommended install location.
8518            if (onSd) {
8519                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8520            }
8521            return pkgLite.recommendedInstallLocation;
8522        }
8523
8524        private long getMemoryLowThreshold() {
8525            final DeviceStorageMonitorInternal
8526                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
8527            if (dsm == null) {
8528                return 0L;
8529            }
8530            return dsm.getMemoryLowThreshold();
8531        }
8532
8533        /*
8534         * Invoke remote method to get package information and install
8535         * location values. Override install location based on default
8536         * policy if needed and then create install arguments based
8537         * on the install location.
8538         */
8539        public void handleStartCopy() throws RemoteException {
8540            int ret = PackageManager.INSTALL_SUCCEEDED;
8541            final boolean onSd = (flags & PackageManager.INSTALL_EXTERNAL) != 0;
8542            final boolean onInt = (flags & PackageManager.INSTALL_INTERNAL) != 0;
8543            PackageInfoLite pkgLite = null;
8544
8545            if (onInt && onSd) {
8546                // Check if both bits are set.
8547                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8548                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8549            } else {
8550                final long lowThreshold = getMemoryLowThreshold();
8551                if (lowThreshold == 0L) {
8552                    Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
8553                }
8554
8555                // Remote call to find out default install location
8556                final String fromPath = getFromFile().getAbsolutePath();
8557                pkgLite = mContainerService.getMinimalPackageInfo(fromPath, flags, lowThreshold,
8558                        packageAbiOverride);
8559
8560                /*
8561                 * If we have too little free space, try to free cache
8562                 * before giving up.
8563                 */
8564                if (pkgLite.recommendedInstallLocation
8565                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8566                    final long size = mContainerService.calculateInstalledSize(
8567                            fromPath, isForwardLocked(), packageAbiOverride);
8568                    if (mInstaller.freeCache(size + lowThreshold) >= 0) {
8569                        pkgLite = mContainerService.getMinimalPackageInfo(fromPath,
8570                                flags, lowThreshold, packageAbiOverride);
8571                    }
8572                    /*
8573                     * The cache free must have deleted the file we
8574                     * downloaded to install.
8575                     *
8576                     * TODO: fix the "freeCache" call to not delete
8577                     *       the file we care about.
8578                     */
8579                    if (pkgLite.recommendedInstallLocation
8580                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8581                        pkgLite.recommendedInstallLocation
8582                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8583                    }
8584                }
8585            }
8586
8587            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8588                int loc = pkgLite.recommendedInstallLocation;
8589                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8590                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8591                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8592                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8593                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8594                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8595                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8596                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8597                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8598                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8599                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8600                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8601                } else {
8602                    // Override with defaults if needed.
8603                    loc = installLocationPolicy(pkgLite, flags);
8604                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8605                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8606                    } else if (!onSd && !onInt) {
8607                        // Override install location with flags
8608                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8609                            // Set the flag to install on external media.
8610                            flags |= PackageManager.INSTALL_EXTERNAL;
8611                            flags &= ~PackageManager.INSTALL_INTERNAL;
8612                        } else {
8613                            // Make sure the flag for installing on external
8614                            // media is unset
8615                            flags |= PackageManager.INSTALL_INTERNAL;
8616                            flags &= ~PackageManager.INSTALL_EXTERNAL;
8617                        }
8618                    }
8619                }
8620            }
8621
8622            final InstallArgs args = createInstallArgs(this);
8623            mArgs = args;
8624
8625            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8626                 /*
8627                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8628                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8629                 */
8630                int userIdentifier = getUser().getIdentifier();
8631                if (userIdentifier == UserHandle.USER_ALL
8632                        && ((flags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8633                    userIdentifier = UserHandle.USER_OWNER;
8634                }
8635
8636                /*
8637                 * Determine if we have any installed package verifiers. If we
8638                 * do, then we'll defer to them to verify the packages.
8639                 */
8640                final int requiredUid = mRequiredVerifierPackage == null ? -1
8641                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8642                if (requiredUid != -1 && isVerificationEnabled(userIdentifier, flags)) {
8643                    // TODO: send verifier the install session instead of uri
8644                    final Intent verification = new Intent(
8645                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8646                    verification.setDataAndType(Uri.fromFile(getFromFile()), PACKAGE_MIME_TYPE);
8647                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8648
8649                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8650                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8651                            0 /* TODO: Which userId? */);
8652
8653                    if (DEBUG_VERIFY) {
8654                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8655                                + verification.toString() + " with " + pkgLite.verifiers.length
8656                                + " optional verifiers");
8657                    }
8658
8659                    final int verificationId = mPendingVerificationToken++;
8660
8661                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8662
8663                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8664                            installerPackageName);
8665
8666                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, flags);
8667
8668                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8669                            pkgLite.packageName);
8670
8671                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8672                            pkgLite.versionCode);
8673
8674                    if (verificationParams != null) {
8675                        if (verificationParams.getVerificationURI() != null) {
8676                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8677                                 verificationParams.getVerificationURI());
8678                        }
8679                        if (verificationParams.getOriginatingURI() != null) {
8680                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8681                                  verificationParams.getOriginatingURI());
8682                        }
8683                        if (verificationParams.getReferrer() != null) {
8684                            verification.putExtra(Intent.EXTRA_REFERRER,
8685                                  verificationParams.getReferrer());
8686                        }
8687                        if (verificationParams.getOriginatingUid() >= 0) {
8688                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8689                                  verificationParams.getOriginatingUid());
8690                        }
8691                        if (verificationParams.getInstallerUid() >= 0) {
8692                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8693                                  verificationParams.getInstallerUid());
8694                        }
8695                    }
8696
8697                    final PackageVerificationState verificationState = new PackageVerificationState(
8698                            requiredUid, args);
8699
8700                    mPendingVerification.append(verificationId, verificationState);
8701
8702                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8703                            receivers, verificationState);
8704
8705                    /*
8706                     * If any sufficient verifiers were listed in the package
8707                     * manifest, attempt to ask them.
8708                     */
8709                    if (sufficientVerifiers != null) {
8710                        final int N = sufficientVerifiers.size();
8711                        if (N == 0) {
8712                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8713                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8714                        } else {
8715                            for (int i = 0; i < N; i++) {
8716                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8717
8718                                final Intent sufficientIntent = new Intent(verification);
8719                                sufficientIntent.setComponent(verifierComponent);
8720
8721                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8722                            }
8723                        }
8724                    }
8725
8726                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8727                            mRequiredVerifierPackage, receivers);
8728                    if (ret == PackageManager.INSTALL_SUCCEEDED
8729                            && mRequiredVerifierPackage != null) {
8730                        /*
8731                         * Send the intent to the required verification agent,
8732                         * but only start the verification timeout after the
8733                         * target BroadcastReceivers have run.
8734                         */
8735                        verification.setComponent(requiredVerifierComponent);
8736                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8737                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8738                                new BroadcastReceiver() {
8739                                    @Override
8740                                    public void onReceive(Context context, Intent intent) {
8741                                        final Message msg = mHandler
8742                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8743                                        msg.arg1 = verificationId;
8744                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8745                                    }
8746                                }, null, 0, null, null);
8747
8748                        /*
8749                         * We don't want the copy to proceed until verification
8750                         * succeeds, so null out this field.
8751                         */
8752                        mArgs = null;
8753                    }
8754                } else {
8755                    /*
8756                     * No package verification is enabled, so immediately start
8757                     * the remote call to initiate copy using temporary file.
8758                     */
8759                    ret = args.copyApk(mContainerService, true);
8760                }
8761            }
8762
8763            mRet = ret;
8764        }
8765
8766        @Override
8767        void handleReturnCode() {
8768            // If mArgs is null, then MCS couldn't be reached. When it
8769            // reconnects, it will try again to install. At that point, this
8770            // will succeed.
8771            if (mArgs != null) {
8772                processPendingInstall(mArgs, mRet);
8773            }
8774        }
8775
8776        @Override
8777        void handleServiceError() {
8778            mArgs = createInstallArgs(this);
8779            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8780        }
8781
8782        public boolean isForwardLocked() {
8783            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8784        }
8785
8786        public File getFromFile() {
8787            return mFromFile;
8788        }
8789    }
8790
8791    /*
8792     * Utility class used in movePackage api.
8793     * srcArgs and targetArgs are not set for invalid flags and make
8794     * sure to do null checks when invoking methods on them.
8795     * We probably want to return ErrorPrams for both failed installs
8796     * and moves.
8797     */
8798    class MoveParams extends HandlerParams {
8799        final IPackageMoveObserver observer;
8800        final int flags;
8801        final String packageName;
8802        final InstallArgs srcArgs;
8803        final InstallArgs targetArgs;
8804        int uid;
8805        int mRet;
8806
8807        MoveParams(InstallArgs srcArgs, IPackageMoveObserver observer, int flags,
8808                String packageName, String dataDir, String instructionSet,
8809                int uid, UserHandle user) {
8810            super(user);
8811            this.srcArgs = srcArgs;
8812            this.observer = observer;
8813            this.flags = flags;
8814            this.packageName = packageName;
8815            this.uid = uid;
8816            if (srcArgs != null) {
8817                final String codePath = srcArgs.getCodePath();
8818                targetArgs = createInstallArgsForMoveTarget(codePath, flags, packageName, dataDir,
8819                        instructionSet);
8820            } else {
8821                targetArgs = null;
8822            }
8823        }
8824
8825        @Override
8826        public String toString() {
8827            return "MoveParams{"
8828                + Integer.toHexString(System.identityHashCode(this))
8829                + " " + packageName + "}";
8830        }
8831
8832        public void handleStartCopy() throws RemoteException {
8833            mRet = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8834            // Check for storage space on target medium
8835            if (!targetArgs.checkFreeStorage(mContainerService)) {
8836                Log.w(TAG, "Insufficient storage to install");
8837                return;
8838            }
8839
8840            mRet = srcArgs.doPreCopy();
8841            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8842                return;
8843            }
8844
8845            mRet = targetArgs.copyApk(mContainerService, false);
8846            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8847                srcArgs.doPostCopy(uid);
8848                return;
8849            }
8850
8851            mRet = srcArgs.doPostCopy(uid);
8852            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8853                return;
8854            }
8855
8856            mRet = targetArgs.doPreInstall(mRet);
8857            if (mRet != PackageManager.INSTALL_SUCCEEDED) {
8858                return;
8859            }
8860
8861            if (DEBUG_SD_INSTALL) {
8862                StringBuilder builder = new StringBuilder();
8863                if (srcArgs != null) {
8864                    builder.append("src: ");
8865                    builder.append(srcArgs.getCodePath());
8866                }
8867                if (targetArgs != null) {
8868                    builder.append(" target : ");
8869                    builder.append(targetArgs.getCodePath());
8870                }
8871                Log.i(TAG, builder.toString());
8872            }
8873        }
8874
8875        @Override
8876        void handleReturnCode() {
8877            targetArgs.doPostInstall(mRet, uid);
8878            int currentStatus = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
8879            if (mRet == PackageManager.INSTALL_SUCCEEDED) {
8880                currentStatus = PackageManager.MOVE_SUCCEEDED;
8881            } else if (mRet == PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE){
8882                currentStatus = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
8883            }
8884            processPendingMove(this, currentStatus);
8885        }
8886
8887        @Override
8888        void handleServiceError() {
8889            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8890        }
8891    }
8892
8893    /**
8894     * Used during creation of InstallArgs
8895     *
8896     * @param flags package installation flags
8897     * @return true if should be installed on external storage
8898     */
8899    private static boolean installOnSd(int flags) {
8900        if ((flags & PackageManager.INSTALL_INTERNAL) != 0) {
8901            return false;
8902        }
8903        if ((flags & PackageManager.INSTALL_EXTERNAL) != 0) {
8904            return true;
8905        }
8906        return false;
8907    }
8908
8909    /**
8910     * Used during creation of InstallArgs
8911     *
8912     * @param flags package installation flags
8913     * @return true if should be installed as forward locked
8914     */
8915    private static boolean installForwardLocked(int flags) {
8916        return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8917    }
8918
8919    private InstallArgs createInstallArgs(InstallParams params) {
8920        // TODO: extend to support incoming zero-copy locations
8921
8922        if (installOnSd(params.flags) || params.isForwardLocked()) {
8923            return new AsecInstallArgs(params);
8924        } else {
8925            return new FileInstallArgs(params);
8926        }
8927    }
8928
8929    /**
8930     * Create args that describe an existing installed package. Typically used
8931     * when cleaning up old installs, or used as a move source.
8932     */
8933    private InstallArgs createInstallArgsForExisting(int flags, String codePath,
8934            String resourcePath, String nativeLibraryPath, String instructionSet) {
8935        final boolean isInAsec;
8936        if (installOnSd(flags)) {
8937            /* Apps on SD card are always in ASEC containers. */
8938            isInAsec = true;
8939        } else if (installForwardLocked(flags)
8940                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8941            /*
8942             * Forward-locked apps are only in ASEC containers if they're the
8943             * new style
8944             */
8945            isInAsec = true;
8946        } else {
8947            isInAsec = false;
8948        }
8949
8950        if (isInAsec) {
8951            return new AsecInstallArgs(codePath, resourcePath, nativeLibraryPath,
8952                    instructionSet, installOnSd(flags), installForwardLocked(flags));
8953        } else {
8954            return new FileInstallArgs(codePath, resourcePath, nativeLibraryPath, instructionSet);
8955        }
8956    }
8957
8958    private InstallArgs createInstallArgsForMoveTarget(String codePath, int flags, String pkgName,
8959            String dataDir, String instructionSet) {
8960        final File codeFile = new File(codePath);
8961        if (installOnSd(flags) || installForwardLocked(flags)) {
8962            String cid = getNextCodePath(codePath, pkgName, "/"
8963                    + AsecInstallArgs.RES_FILE_NAME);
8964            return new AsecInstallArgs(codeFile, cid, instructionSet, installOnSd(flags),
8965                    installForwardLocked(flags));
8966        } else {
8967            return new FileInstallArgs(codeFile, pkgName, dataDir, instructionSet);
8968        }
8969    }
8970
8971    static abstract class InstallArgs {
8972        /**
8973         * Location where install is coming from, before it has been
8974         * copied/renamed into place. This could be a single monolithic APK
8975         * file, or a cluster directory. This location is typically untrusted.
8976         */
8977        final File fromFile;
8978
8979        final IPackageInstallObserver observer;
8980        final IPackageInstallObserver2 observer2;
8981        // Always refers to PackageManager flags only
8982        final int flags;
8983        final String installerPackageName;
8984        final ManifestDigest manifestDigest;
8985        final UserHandle user;
8986        final String instructionSet;
8987        final String abiOverride;
8988
8989        InstallArgs(File fromFile, IPackageInstallObserver observer,
8990                IPackageInstallObserver2 observer2, int flags, String installerPackageName,
8991                ManifestDigest manifestDigest, UserHandle user, String instructionSet,
8992                String abiOverride) {
8993            this.fromFile = fromFile;
8994            this.flags = flags;
8995            this.observer = observer;
8996            this.observer2 = observer2;
8997            this.installerPackageName = installerPackageName;
8998            this.manifestDigest = manifestDigest;
8999            this.user = user;
9000            this.instructionSet = instructionSet;
9001            this.abiOverride = abiOverride;
9002        }
9003
9004        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9005        abstract int doPreInstall(int status);
9006        abstract boolean doRename(int status, String pkgName, String oldCodePath);
9007        abstract int doPostInstall(int status, int uid);
9008
9009        /** @see PackageSettingBase#codePathString */
9010        abstract String getCodePath();
9011        /** @see PackageSettingBase#resourcePathString */
9012        abstract String getResourcePath();
9013        /** @see PackageSettingBase#nativeLibraryPathString */
9014        abstract String getNativeLibraryPath();
9015
9016        // Need installer lock especially for dex file removal.
9017        abstract void cleanUpResourcesLI();
9018        abstract boolean doPostDeleteLI(boolean delete);
9019        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9020
9021        /**
9022         * Called before the source arguments are copied. This is used mostly
9023         * for MoveParams when it needs to read the source file to put it in the
9024         * destination.
9025         */
9026        int doPreCopy() {
9027            return PackageManager.INSTALL_SUCCEEDED;
9028        }
9029
9030        /**
9031         * Called after the source arguments are copied. This is used mostly for
9032         * MoveParams when it needs to read the source file to put it in the
9033         * destination.
9034         *
9035         * @return
9036         */
9037        int doPostCopy(int uid) {
9038            return PackageManager.INSTALL_SUCCEEDED;
9039        }
9040
9041        protected boolean isFwdLocked() {
9042            return (flags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9043        }
9044
9045        UserHandle getUser() {
9046            return user;
9047        }
9048    }
9049
9050    /**
9051     * Logic to handle installation of non-ASEC applications, including copying
9052     * and renaming logic.
9053     */
9054    class FileInstallArgs extends InstallArgs {
9055        // TODO: teach about handling cluster directories
9056
9057        File installDir;
9058        String codeFileName;
9059        String resourceFileName;
9060        String libraryPath;
9061        boolean created = false;
9062
9063        /** New install */
9064        FileInstallArgs(InstallParams params) {
9065            super(params.getFromFile(), params.observer, params.observer2, params.flags,
9066                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9067                    params.packageInstructionSetOverride, params.packageAbiOverride);
9068        }
9069
9070        /** Existing install */
9071        FileInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9072                String instructionSet) {
9073            super(null, null, null, 0, null, null, null, instructionSet, null);
9074            File codeFile = new File(fullCodePath);
9075            installDir = codeFile.getParentFile();
9076            codeFileName = fullCodePath;
9077            resourceFileName = fullResourcePath;
9078            libraryPath = nativeLibraryPath;
9079        }
9080
9081        /** New install from existing */
9082        FileInstallArgs(File fromFile, String pkgName, String dataDir, String instructionSet) {
9083            super(fromFile, null, null, 0, null, null, null, instructionSet, null);
9084            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9085            String apkName = getNextCodePath(null, pkgName, ".apk");
9086            codeFileName = new File(installDir, apkName + ".apk").getPath();
9087            resourceFileName = getResourcePathFromCodePath();
9088            libraryPath = new File(mAppLibInstallDir, pkgName).getPath();
9089        }
9090
9091        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9092            final long lowThreshold;
9093
9094            final DeviceStorageMonitorInternal
9095                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
9096            if (dsm == null) {
9097                Log.w(TAG, "Couldn't get low memory threshold; no free limit imposed");
9098                lowThreshold = 0L;
9099            } else {
9100                if (dsm.isMemoryLow()) {
9101                    Log.w(TAG, "Memory is reported as being too low; aborting package install");
9102                    return false;
9103                }
9104
9105                lowThreshold = dsm.getMemoryLowThreshold();
9106            }
9107
9108            return imcs.checkInternalFreeStorage(fromFile.getAbsolutePath(), isFwdLocked(),
9109                    lowThreshold);
9110        }
9111
9112        void createCopyFile() {
9113            installDir = isFwdLocked() ? mDrmAppPrivateInstallDir : mAppInstallDir;
9114            codeFileName = createTempPackageFile(installDir).getPath();
9115            resourceFileName = getResourcePathFromCodePath();
9116            libraryPath = getLibraryPathFromCodePath();
9117            created = true;
9118        }
9119
9120        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9121            if (temp) {
9122                // Generate temp file name
9123                createCopyFile();
9124            }
9125            // Get a ParcelFileDescriptor to write to the output file
9126            File codeFile = new File(codeFileName);
9127            if (!created) {
9128                try {
9129                    codeFile.createNewFile();
9130                    // Set permissions
9131                    if (!setPermissions()) {
9132                        // Failed setting permissions.
9133                        return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9134                    }
9135                } catch (IOException e) {
9136                   Slog.w(TAG, "Failed to create file " + codeFile);
9137                   return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9138                }
9139            }
9140            ParcelFileDescriptor out = null;
9141            try {
9142                out = ParcelFileDescriptor.open(codeFile, ParcelFileDescriptor.MODE_READ_WRITE);
9143            } catch (FileNotFoundException e) {
9144                Slog.e(TAG, "Failed to create file descriptor for : " + codeFileName);
9145                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9146            }
9147            // Copy the resource now
9148            int ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9149            try {
9150                ret = imcs.copyResource(fromFile.getAbsolutePath(), out);
9151            } finally {
9152                IoUtils.closeQuietly(out);
9153            }
9154
9155            if (isFwdLocked()) {
9156                final File destResourceFile = new File(getResourcePath());
9157
9158                // Copy the public files
9159                try {
9160                    PackageHelper.extractPublicFiles(codeFileName, destResourceFile);
9161                } catch (IOException e) {
9162                    Slog.e(TAG, "Couldn't create a new zip file for the public parts of a"
9163                            + " forward-locked app.");
9164                    destResourceFile.delete();
9165                    return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9166                }
9167            }
9168
9169            final File nativeLibraryFile = new File(getNativeLibraryPath());
9170            Slog.i(TAG, "Copying native libraries to " + nativeLibraryFile.getPath());
9171            if (nativeLibraryFile.exists()) {
9172                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9173                nativeLibraryFile.delete();
9174            }
9175
9176            String[] abiList = (abiOverride != null) ?
9177                    new String[] { abiOverride } : Build.SUPPORTED_ABIS;
9178            NativeLibraryHelper.Handle handle = null;
9179            try {
9180                handle = NativeLibraryHelper.Handle.create(codeFile);
9181                if (Build.SUPPORTED_64_BIT_ABIS.length > 0 &&
9182                        abiOverride == null &&
9183                        NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
9184                    abiList = Build.SUPPORTED_32_BIT_ABIS;
9185                }
9186
9187                int copyRet = copyNativeLibrariesForInternalApp(handle, nativeLibraryFile, abiList);
9188                if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
9189                    return copyRet;
9190                }
9191            } catch (IOException e) {
9192                Slog.e(TAG, "Copying native libraries failed", e);
9193                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9194            } finally {
9195                IoUtils.closeQuietly(handle);
9196            }
9197
9198            return ret;
9199        }
9200
9201        int doPreInstall(int status) {
9202            if (status != PackageManager.INSTALL_SUCCEEDED) {
9203                cleanUp();
9204            }
9205            return status;
9206        }
9207
9208        boolean doRename(int status, final String pkgName, String oldCodePath) {
9209            if (status != PackageManager.INSTALL_SUCCEEDED) {
9210                cleanUp();
9211                return false;
9212            } else {
9213                final File oldCodeFile = new File(getCodePath());
9214                final File oldResourceFile = new File(getResourcePath());
9215                final File oldLibraryFile = new File(getNativeLibraryPath());
9216
9217                // Rename APK file based on packageName
9218                final String apkName = getNextCodePath(oldCodePath, pkgName, ".apk");
9219                final File newCodeFile = new File(installDir, apkName + ".apk");
9220                if (!oldCodeFile.renameTo(newCodeFile)) {
9221                    return false;
9222                }
9223                codeFileName = newCodeFile.getPath();
9224
9225                // Rename public resource file if it's forward-locked.
9226                final File newResFile = new File(getResourcePathFromCodePath());
9227                if (isFwdLocked() && !oldResourceFile.renameTo(newResFile)) {
9228                    return false;
9229                }
9230                resourceFileName = newResFile.getPath();
9231
9232                // Rename library path
9233                final File newLibraryFile = new File(getLibraryPathFromCodePath());
9234                if (newLibraryFile.exists()) {
9235                    NativeLibraryHelper.removeNativeBinariesFromDirLI(newLibraryFile);
9236                    newLibraryFile.delete();
9237                }
9238                if (!oldLibraryFile.renameTo(newLibraryFile)) {
9239                    Slog.e(TAG, "Cannot rename native library directory "
9240                            + oldLibraryFile.getPath() + " to " + newLibraryFile.getPath());
9241                    return false;
9242                }
9243                libraryPath = newLibraryFile.getPath();
9244
9245                // Attempt to set permissions
9246                if (!setPermissions()) {
9247                    return false;
9248                }
9249
9250                if (!SELinux.restorecon(newCodeFile)) {
9251                    return false;
9252                }
9253
9254                return true;
9255            }
9256        }
9257
9258        int doPostInstall(int status, int uid) {
9259            if (status != PackageManager.INSTALL_SUCCEEDED) {
9260                cleanUp();
9261            }
9262            return status;
9263        }
9264
9265        private String getResourcePathFromCodePath() {
9266            final String codePath = getCodePath();
9267            if (isFwdLocked()) {
9268                final StringBuilder sb = new StringBuilder();
9269
9270                sb.append(mAppInstallDir.getPath());
9271                sb.append('/');
9272                sb.append(getApkName(codePath));
9273                sb.append(".zip");
9274
9275                /*
9276                 * If our APK is a temporary file, mark the resource as a
9277                 * temporary file as well so it can be cleaned up after
9278                 * catastrophic failure.
9279                 */
9280                if (codePath.endsWith(".tmp")) {
9281                    sb.append(".tmp");
9282                }
9283
9284                return sb.toString();
9285            } else {
9286                return codePath;
9287            }
9288        }
9289
9290        private String getLibraryPathFromCodePath() {
9291            return new File(mAppLibInstallDir, getApkName(getCodePath())).getPath();
9292        }
9293
9294        @Override
9295        String getCodePath() {
9296            return codeFileName;
9297        }
9298
9299        @Override
9300        String getResourcePath() {
9301            return resourceFileName;
9302        }
9303
9304        @Override
9305        String getNativeLibraryPath() {
9306            if (libraryPath == null) {
9307                libraryPath = getLibraryPathFromCodePath();
9308            }
9309            return libraryPath;
9310        }
9311
9312        private boolean cleanUp() {
9313            boolean ret = true;
9314            String sourceDir = getCodePath();
9315            String publicSourceDir = getResourcePath();
9316            if (sourceDir != null) {
9317                File sourceFile = new File(sourceDir);
9318                if (!sourceFile.exists()) {
9319                    Slog.w(TAG, "Package source " + sourceDir + " does not exist.");
9320                    ret = false;
9321                }
9322                // Delete application's code and resources
9323                sourceFile.delete();
9324            }
9325            if (publicSourceDir != null && !publicSourceDir.equals(sourceDir)) {
9326                final File publicSourceFile = new File(publicSourceDir);
9327                if (!publicSourceFile.exists()) {
9328                    Slog.w(TAG, "Package public source " + publicSourceFile + " does not exist.");
9329                }
9330                if (publicSourceFile.exists()) {
9331                    publicSourceFile.delete();
9332                }
9333            }
9334
9335            if (libraryPath != null) {
9336                File nativeLibraryFile = new File(libraryPath);
9337                NativeLibraryHelper.removeNativeBinariesFromDirLI(nativeLibraryFile);
9338                if (!nativeLibraryFile.delete()) {
9339                    Slog.w(TAG, "Couldn't delete native library directory " + libraryPath);
9340                }
9341            }
9342
9343            return ret;
9344        }
9345
9346        void cleanUpResourcesLI() {
9347            String sourceDir = getCodePath();
9348            if (cleanUp()) {
9349                if (instructionSet == null) {
9350                    throw new IllegalStateException("instructionSet == null");
9351                }
9352                int retCode = mInstaller.rmdex(sourceDir, instructionSet);
9353                if (retCode < 0) {
9354                    Slog.w(TAG, "Couldn't remove dex file for package: "
9355                            +  " at location "
9356                            + sourceDir + ", retcode=" + retCode);
9357                    // we don't consider this to be a failure of the core package deletion
9358                }
9359            }
9360        }
9361
9362        private boolean setPermissions() {
9363            // TODO Do this in a more elegant way later on. for now just a hack
9364            if (!isFwdLocked()) {
9365                final int filePermissions =
9366                    FileUtils.S_IRUSR|FileUtils.S_IWUSR|FileUtils.S_IRGRP
9367                    |FileUtils.S_IROTH;
9368                int retCode = FileUtils.setPermissions(getCodePath(), filePermissions, -1, -1);
9369                if (retCode != 0) {
9370                    Slog.e(TAG, "Couldn't set new package file permissions for " +
9371                            getCodePath()
9372                            + ". The return code was: " + retCode);
9373                    // TODO Define new internal error
9374                    return false;
9375                }
9376                return true;
9377            }
9378            return true;
9379        }
9380
9381        boolean doPostDeleteLI(boolean delete) {
9382            // XXX err, shouldn't we respect the delete flag?
9383            cleanUpResourcesLI();
9384            return true;
9385        }
9386    }
9387
9388    private boolean isAsecExternal(String cid) {
9389        final String asecPath = PackageHelper.getSdFilesystem(cid);
9390        return !asecPath.startsWith(mAsecInternalPath);
9391    }
9392
9393    /**
9394     * Extract the MountService "container ID" from the full code path of an
9395     * .apk.
9396     */
9397    static String cidFromCodePath(String fullCodePath) {
9398        int eidx = fullCodePath.lastIndexOf("/");
9399        String subStr1 = fullCodePath.substring(0, eidx);
9400        int sidx = subStr1.lastIndexOf("/");
9401        return subStr1.substring(sidx+1, eidx);
9402    }
9403
9404    /**
9405     * Logic to handle installation of ASEC applications, including copying and
9406     * renaming logic.
9407     */
9408    class AsecInstallArgs extends InstallArgs {
9409        // TODO: teach about handling cluster directories
9410
9411        static final String RES_FILE_NAME = "pkg.apk";
9412        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9413
9414        String cid;
9415        String packagePath;
9416        String resourcePath;
9417        String libraryPath;
9418
9419        /** New install */
9420        AsecInstallArgs(InstallParams params) {
9421            super(params.getFromFile(), params.observer, params.observer2, params.flags,
9422                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9423                    params.packageInstructionSetOverride, params.packageAbiOverride);
9424        }
9425
9426        /** Existing install */
9427        AsecInstallArgs(String fullCodePath, String fullResourcePath, String nativeLibraryPath,
9428                String instructionSet, boolean isExternal, boolean isForwardLocked) {
9429            super(null, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9430                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9431                    null, null, null, instructionSet, null);
9432            // Extract cid from fullCodePath
9433            int eidx = fullCodePath.lastIndexOf("/");
9434            String subStr1 = fullCodePath.substring(0, eidx);
9435            int sidx = subStr1.lastIndexOf("/");
9436            cid = subStr1.substring(sidx+1, eidx);
9437            setCachePath(subStr1);
9438        }
9439
9440        AsecInstallArgs(String cid, String instructionSet, boolean isForwardLocked) {
9441            super(null, null, null, (isAsecExternal(cid) ? PackageManager.INSTALL_EXTERNAL : 0)
9442                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9443                    null, null, null, instructionSet, null);
9444            this.cid = cid;
9445            setCachePath(PackageHelper.getSdDir(cid));
9446        }
9447
9448        /** New install from existing */
9449        AsecInstallArgs(File fromFile, String cid, String instructionSet,
9450                boolean isExternal, boolean isForwardLocked) {
9451            super(fromFile, null, null, (isExternal ? PackageManager.INSTALL_EXTERNAL : 0)
9452                    | (isForwardLocked ? PackageManager.INSTALL_FORWARD_LOCK : 0),
9453                    null, null, null, instructionSet, null);
9454            this.cid = cid;
9455        }
9456
9457        void createCopyFile() {
9458            cid = getTempContainerId();
9459        }
9460
9461        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9462            return imcs.checkExternalFreeStorage(fromFile.getAbsolutePath(), isFwdLocked(),
9463                    abiOverride);
9464        }
9465
9466        private final boolean isExternal() {
9467            return (flags & PackageManager.INSTALL_EXTERNAL) != 0;
9468        }
9469
9470        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9471            if (temp) {
9472                createCopyFile();
9473            } else {
9474                /*
9475                 * Pre-emptively destroy the container since it's destroyed if
9476                 * copying fails due to it existing anyway.
9477                 */
9478                PackageHelper.destroySdDir(cid);
9479            }
9480
9481            final String newCachePath = imcs.copyResourceToContainer(fromFile.getAbsolutePath(),
9482                    cid, getEncryptKey(), RES_FILE_NAME, PUBLIC_RES_FILE_NAME, isExternal(),
9483                    isFwdLocked(), abiOverride);
9484
9485            if (newCachePath != null) {
9486                setCachePath(newCachePath);
9487                return PackageManager.INSTALL_SUCCEEDED;
9488            } else {
9489                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9490            }
9491        }
9492
9493        @Override
9494        String getCodePath() {
9495            return packagePath;
9496        }
9497
9498        @Override
9499        String getResourcePath() {
9500            return resourcePath;
9501        }
9502
9503        @Override
9504        String getNativeLibraryPath() {
9505            return libraryPath;
9506        }
9507
9508        int doPreInstall(int status) {
9509            if (status != PackageManager.INSTALL_SUCCEEDED) {
9510                // Destroy container
9511                PackageHelper.destroySdDir(cid);
9512            } else {
9513                boolean mounted = PackageHelper.isContainerMounted(cid);
9514                if (!mounted) {
9515                    String newCachePath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9516                            Process.SYSTEM_UID);
9517                    if (newCachePath != null) {
9518                        setCachePath(newCachePath);
9519                    } else {
9520                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9521                    }
9522                }
9523            }
9524            return status;
9525        }
9526
9527        boolean doRename(int status, final String pkgName,
9528                String oldCodePath) {
9529            String newCacheId = getNextCodePath(oldCodePath, pkgName, "/" + RES_FILE_NAME);
9530            String newCachePath = null;
9531            if (PackageHelper.isContainerMounted(cid)) {
9532                // Unmount the container
9533                if (!PackageHelper.unMountSdDir(cid)) {
9534                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9535                    return false;
9536                }
9537            }
9538            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9539                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9540                        " which might be stale. Will try to clean up.");
9541                // Clean up the stale container and proceed to recreate.
9542                if (!PackageHelper.destroySdDir(newCacheId)) {
9543                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9544                    return false;
9545                }
9546                // Successfully cleaned up stale container. Try to rename again.
9547                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9548                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9549                            + " inspite of cleaning it up.");
9550                    return false;
9551                }
9552            }
9553            if (!PackageHelper.isContainerMounted(newCacheId)) {
9554                Slog.w(TAG, "Mounting container " + newCacheId);
9555                newCachePath = PackageHelper.mountSdDir(newCacheId,
9556                        getEncryptKey(), Process.SYSTEM_UID);
9557            } else {
9558                newCachePath = PackageHelper.getSdDir(newCacheId);
9559            }
9560            if (newCachePath == null) {
9561                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9562                return false;
9563            }
9564            Log.i(TAG, "Succesfully renamed " + cid +
9565                    " to " + newCacheId +
9566                    " at new path: " + newCachePath);
9567            cid = newCacheId;
9568            setCachePath(newCachePath);
9569            return true;
9570        }
9571
9572        private void setCachePath(String newCachePath) {
9573            File cachePath = new File(newCachePath);
9574            libraryPath = new File(cachePath, LIB_DIR_NAME).getPath();
9575            packagePath = new File(cachePath, RES_FILE_NAME).getPath();
9576
9577            if (isFwdLocked()) {
9578                resourcePath = new File(cachePath, PUBLIC_RES_FILE_NAME).getPath();
9579            } else {
9580                resourcePath = packagePath;
9581            }
9582        }
9583
9584        int doPostInstall(int status, int uid) {
9585            if (status != PackageManager.INSTALL_SUCCEEDED) {
9586                cleanUp();
9587            } else {
9588                final int groupOwner;
9589                final String protectedFile;
9590                if (isFwdLocked()) {
9591                    groupOwner = UserHandle.getSharedAppGid(uid);
9592                    protectedFile = RES_FILE_NAME;
9593                } else {
9594                    groupOwner = -1;
9595                    protectedFile = null;
9596                }
9597
9598                if (uid < Process.FIRST_APPLICATION_UID
9599                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9600                    Slog.e(TAG, "Failed to finalize " + cid);
9601                    PackageHelper.destroySdDir(cid);
9602                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9603                }
9604
9605                boolean mounted = PackageHelper.isContainerMounted(cid);
9606                if (!mounted) {
9607                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9608                }
9609            }
9610            return status;
9611        }
9612
9613        private void cleanUp() {
9614            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9615
9616            // Destroy secure container
9617            PackageHelper.destroySdDir(cid);
9618        }
9619
9620        void cleanUpResourcesLI() {
9621            String sourceFile = getCodePath();
9622            // Remove dex file
9623            if (instructionSet == null) {
9624                throw new IllegalStateException("instructionSet == null");
9625            }
9626            int retCode = mInstaller.rmdex(sourceFile, instructionSet);
9627            if (retCode < 0) {
9628                Slog.w(TAG, "Couldn't remove dex file for package: "
9629                        + " at location "
9630                        + sourceFile.toString() + ", retcode=" + retCode);
9631                // we don't consider this to be a failure of the core package deletion
9632            }
9633            cleanUp();
9634        }
9635
9636        boolean matchContainer(String app) {
9637            if (cid.startsWith(app)) {
9638                return true;
9639            }
9640            return false;
9641        }
9642
9643        String getPackageName() {
9644            return getAsecPackageName(cid);
9645        }
9646
9647        boolean doPostDeleteLI(boolean delete) {
9648            boolean ret = false;
9649            boolean mounted = PackageHelper.isContainerMounted(cid);
9650            if (mounted) {
9651                // Unmount first
9652                ret = PackageHelper.unMountSdDir(cid);
9653            }
9654            if (ret && delete) {
9655                cleanUpResourcesLI();
9656            }
9657            return ret;
9658        }
9659
9660        @Override
9661        int doPreCopy() {
9662            if (isFwdLocked()) {
9663                if (!PackageHelper.fixSdPermissions(cid,
9664                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9665                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9666                }
9667            }
9668
9669            return PackageManager.INSTALL_SUCCEEDED;
9670        }
9671
9672        @Override
9673        int doPostCopy(int uid) {
9674            if (isFwdLocked()) {
9675                if (uid < Process.FIRST_APPLICATION_UID
9676                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9677                                RES_FILE_NAME)) {
9678                    Slog.e(TAG, "Failed to finalize " + cid);
9679                    PackageHelper.destroySdDir(cid);
9680                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9681                }
9682            }
9683
9684            return PackageManager.INSTALL_SUCCEEDED;
9685        }
9686    }
9687
9688    static String getAsecPackageName(String packageCid) {
9689        int idx = packageCid.lastIndexOf("-");
9690        if (idx == -1) {
9691            return packageCid;
9692        }
9693        return packageCid.substring(0, idx);
9694    }
9695
9696    // Utility method used to create code paths based on package name and available index.
9697    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9698        String idxStr = "";
9699        int idx = 1;
9700        // Fall back to default value of idx=1 if prefix is not
9701        // part of oldCodePath
9702        if (oldCodePath != null) {
9703            String subStr = oldCodePath;
9704            // Drop the suffix right away
9705            if (subStr.endsWith(suffix)) {
9706                subStr = subStr.substring(0, subStr.length() - suffix.length());
9707            }
9708            // If oldCodePath already contains prefix find out the
9709            // ending index to either increment or decrement.
9710            int sidx = subStr.lastIndexOf(prefix);
9711            if (sidx != -1) {
9712                subStr = subStr.substring(sidx + prefix.length());
9713                if (subStr != null) {
9714                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9715                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9716                    }
9717                    try {
9718                        idx = Integer.parseInt(subStr);
9719                        if (idx <= 1) {
9720                            idx++;
9721                        } else {
9722                            idx--;
9723                        }
9724                    } catch(NumberFormatException e) {
9725                    }
9726                }
9727            }
9728        }
9729        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9730        return prefix + idxStr;
9731    }
9732
9733    // Utility method used to ignore ADD/REMOVE events
9734    // by directory observer.
9735    private static boolean ignoreCodePath(String fullPathStr) {
9736        String apkName = getApkName(fullPathStr);
9737        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9738        if (idx != -1 && ((idx+1) < apkName.length())) {
9739            // Make sure the package ends with a numeral
9740            String version = apkName.substring(idx+1);
9741            try {
9742                Integer.parseInt(version);
9743                return true;
9744            } catch (NumberFormatException e) {}
9745        }
9746        return false;
9747    }
9748
9749    // Utility method that returns the relative package path with respect
9750    // to the installation directory. Like say for /data/data/com.test-1.apk
9751    // string com.test-1 is returned.
9752    static String getApkName(String codePath) {
9753        if (codePath == null) {
9754            return null;
9755        }
9756        int sidx = codePath.lastIndexOf("/");
9757        int eidx = codePath.lastIndexOf(".");
9758        if (eidx == -1) {
9759            eidx = codePath.length();
9760        } else if (eidx == 0) {
9761            Slog.w(TAG, " Invalid code path, "+ codePath + " Not a valid apk name");
9762            return null;
9763        }
9764        return codePath.substring(sidx+1, eidx);
9765    }
9766
9767    private static String[] deriveSplitResPaths(String[] splitCodePaths) {
9768        String[] splitResPaths = null;
9769        if (!ArrayUtils.isEmpty(splitCodePaths)) {
9770            splitResPaths = new String[splitCodePaths.length];
9771            for (int i = 0; i < splitCodePaths.length; i++) {
9772                final String splitCodePath = splitCodePaths[i];
9773                final String resName = getApkName(splitCodePath) + ".zip";
9774                splitResPaths[i] = new File(new File(splitCodePath).getParentFile(),
9775                        resName).getAbsolutePath();
9776            }
9777        }
9778        return splitResPaths;
9779    }
9780
9781    class PackageInstalledInfo {
9782        String name;
9783        int uid;
9784        // The set of users that originally had this package installed.
9785        int[] origUsers;
9786        // The set of users that now have this package installed.
9787        int[] newUsers;
9788        PackageParser.Package pkg;
9789        int returnCode;
9790        PackageRemovedInfo removedInfo;
9791
9792        // In some error cases we want to convey more info back to the observer
9793        String origPackage;
9794        String origPermission;
9795    }
9796
9797    /*
9798     * Install a non-existing package.
9799     */
9800    private void installNewPackageLI(PackageParser.Package pkg,
9801            int parseFlags, int scanMode, UserHandle user,
9802            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9803        // Remember this for later, in case we need to rollback this install
9804        String pkgName = pkg.packageName;
9805
9806        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9807        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9808        synchronized(mPackages) {
9809            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9810                // A package with the same name is already installed, though
9811                // it has been renamed to an older name.  The package we
9812                // are trying to install should be installed as an update to
9813                // the existing one, but that has not been requested, so bail.
9814                Slog.w(TAG, "Attempt to re-install " + pkgName
9815                        + " without first uninstalling package running as "
9816                        + mSettings.mRenamedPackages.get(pkgName));
9817                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9818                return;
9819            }
9820            if (mPackages.containsKey(pkgName) || mAppDirs.containsKey(pkg.codePath)) {
9821                // Don't allow installation over an existing package with the same name.
9822                Slog.w(TAG, "Attempt to re-install " + pkgName
9823                        + " without first uninstalling.");
9824                res.returnCode = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
9825                return;
9826            }
9827        }
9828        mLastScanError = PackageManager.INSTALL_SUCCEEDED;
9829        PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanMode,
9830                System.currentTimeMillis(), user, abiOverride);
9831        if (newPackage == null) {
9832            Slog.w(TAG, "Package couldn't be installed in " + pkg.codePath);
9833            if ((res.returnCode=mLastScanError) == PackageManager.INSTALL_SUCCEEDED) {
9834                res.returnCode = PackageManager.INSTALL_FAILED_INVALID_APK;
9835            }
9836        } else {
9837            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9838            // delete the partially installed application. the data directory will have to be
9839            // restored if it was already existing
9840            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9841                // remove package from internal structures.  Note that we want deletePackageX to
9842                // delete the package data and cache directories that it created in
9843                // scanPackageLocked, unless those directories existed before we even tried to
9844                // install.
9845                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9846                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9847                                res.removedInfo, true);
9848            }
9849        }
9850    }
9851
9852    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9853        // Upgrade keysets are being used.  Determine if new package has a superset of the
9854        // required keys.
9855        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9856        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9857        Set<Long> newSigningKeyIds = new ArraySet<Long>();
9858        for (PublicKey pk : newPkg.mSigningKeys) {
9859            newSigningKeyIds.add(ksms.getIdForPublicKey(pk));
9860        }
9861        //remove PUBLIC_KEY_NOT_FOUND, although not necessary
9862        newSigningKeyIds.remove(ksms.PUBLIC_KEY_NOT_FOUND);
9863        for (int i = 0; i < upgradeKeySets.length; i++) {
9864            if (newSigningKeyIds.containsAll(ksms.mKeySetMapping.get(upgradeKeySets[i]))) {
9865                return true;
9866            }
9867        }
9868        return false;
9869    }
9870
9871    private void replacePackageLI(PackageParser.Package pkg,
9872            int parseFlags, int scanMode, UserHandle user,
9873            String installerPackageName, PackageInstalledInfo res, String abiOverride) {
9874        PackageParser.Package oldPackage;
9875        String pkgName = pkg.packageName;
9876        int[] allUsers;
9877        boolean[] perUserInstalled;
9878
9879        // First find the old package info and check signatures
9880        synchronized(mPackages) {
9881            oldPackage = mPackages.get(pkgName);
9882            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9883            PackageSetting ps = mSettings.mPackages.get(pkgName);
9884            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9885                // default to original signature matching
9886                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9887                    != PackageManager.SIGNATURE_MATCH) {
9888                    Slog.w(TAG, "New package has a different signature: " + pkgName);
9889                    res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9890                    return;
9891                }
9892            } else {
9893                if(!checkUpgradeKeySetLP(ps, pkg)) {
9894                    Slog.w(TAG, "New package not signed by keys specified by upgrade-keysets: "
9895                           + pkgName);
9896                    res.returnCode = PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
9897                    return;
9898                }
9899            }
9900
9901            // In case of rollback, remember per-user/profile install state
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 = createInstallArgsForExisting(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.baseCodePath,
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.baseCodePath, 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, boolean newInstall, PackageInstalledInfo res) {
10190        int pFlags = args.flags;
10191        String installerPackageName = args.installerPackageName;
10192        File tmpPackageFile = new File(args.getCodePath());
10193        boolean forwardLocked = ((pFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10194        boolean onSd = ((pFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10195        boolean replace = false;
10196        int scanMode = (onSd ? 0 : SCAN_MONITOR) | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE
10197                | (newInstall ? SCAN_NEW_INSTALL : 0);
10198        // Result object to be returned
10199        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10200
10201        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10202        // Retrieve PackageSettings and parse package
10203        int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10204                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10205                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10206        PackageParser pp = new PackageParser();
10207        pp.setSeparateProcesses(mSeparateProcesses);
10208        pp.setDisplayMetrics(mMetrics);
10209
10210        final PackageParser.Package pkg;
10211        try {
10212            pkg = pp.parseMonolithicPackage(tmpPackageFile, parseFlags);
10213        } catch (PackageParserException e) {
10214            res.returnCode = e.error;
10215            return;
10216        }
10217
10218        String pkgName = res.name = pkg.packageName;
10219        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10220            if ((pFlags&PackageManager.INSTALL_ALLOW_TEST) == 0) {
10221                res.returnCode = PackageManager.INSTALL_FAILED_TEST_ONLY;
10222                return;
10223            }
10224        }
10225
10226        try {
10227            pp.collectCertificates(pkg, parseFlags);
10228            pp.collectManifestDigest(pkg);
10229        } catch (PackageParserException e) {
10230            res.returnCode = e.error;
10231            return;
10232        }
10233
10234        /* If the installer passed in a manifest digest, compare it now. */
10235        if (args.manifestDigest != null) {
10236            if (DEBUG_INSTALL) {
10237                final String parsedManifest = pkg.manifestDigest == null ? "null"
10238                        : pkg.manifestDigest.toString();
10239                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10240                        + parsedManifest);
10241            }
10242
10243            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10244                res.returnCode = PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
10245                return;
10246            }
10247        } else if (DEBUG_INSTALL) {
10248            final String parsedManifest = pkg.manifestDigest == null
10249                    ? "null" : pkg.manifestDigest.toString();
10250            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10251        }
10252
10253        // Get rid of all references to package scan path via parser.
10254        pp = null;
10255        String oldCodePath = null;
10256        boolean systemApp = false;
10257        synchronized (mPackages) {
10258            // Check whether the newly-scanned package wants to define an already-defined perm
10259            int N = pkg.permissions.size();
10260            for (int i = N-1; i >= 0; i--) {
10261                PackageParser.Permission perm = pkg.permissions.get(i);
10262                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10263                if (bp != null) {
10264                    // If the defining package is signed with our cert, it's okay.  This
10265                    // also includes the "updating the same package" case, of course.
10266                    if (compareSignatures(bp.packageSetting.signatures.mSignatures,
10267                            pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
10268                        // If the owning package is the system itself, we log but allow
10269                        // install to proceed; we fail the install on all other permission
10270                        // redefinitions.
10271                        if (!bp.sourcePackage.equals("android")) {
10272                            Slog.w(TAG, "Package " + pkg.packageName
10273                                    + " attempting to redeclare permission " + perm.info.name
10274                                    + " already owned by " + bp.sourcePackage);
10275                            res.returnCode = PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
10276                            res.origPermission = perm.info.name;
10277                            res.origPackage = bp.sourcePackage;
10278                            return;
10279                        } else {
10280                            Slog.w(TAG, "Package " + pkg.packageName
10281                                    + " attempting to redeclare system permission "
10282                                    + perm.info.name + "; ignoring new declaration");
10283                            pkg.permissions.remove(i);
10284                        }
10285                    }
10286                }
10287            }
10288
10289            // Check if installing already existing package
10290            if ((pFlags&PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10291                String oldName = mSettings.mRenamedPackages.get(pkgName);
10292                if (pkg.mOriginalPackages != null
10293                        && pkg.mOriginalPackages.contains(oldName)
10294                        && mPackages.containsKey(oldName)) {
10295                    // This package is derived from an original package,
10296                    // and this device has been updating from that original
10297                    // name.  We must continue using the original name, so
10298                    // rename the new package here.
10299                    pkg.setPackageName(oldName);
10300                    pkgName = pkg.packageName;
10301                    replace = true;
10302                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10303                            + oldName + " pkgName=" + pkgName);
10304                } else if (mPackages.containsKey(pkgName)) {
10305                    // This package, under its official name, already exists
10306                    // on the device; we should replace it.
10307                    replace = true;
10308                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10309                }
10310            }
10311            PackageSetting ps = mSettings.mPackages.get(pkgName);
10312            if (ps != null) {
10313                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10314                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10315                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10316                    systemApp = (ps.pkg.applicationInfo.flags &
10317                            ApplicationInfo.FLAG_SYSTEM) != 0;
10318                }
10319                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10320            }
10321        }
10322
10323        if (systemApp && onSd) {
10324            // Disable updates to system apps on sdcard
10325            Slog.w(TAG, "Cannot install updates to system apps on sdcard");
10326            res.returnCode = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
10327            return;
10328        }
10329
10330        if (!args.doRename(res.returnCode, pkgName, oldCodePath)) {
10331            res.returnCode = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
10332            return;
10333        }
10334
10335        // Set application objects path explicitly after the rename
10336        // TODO: derive split paths from original scan after rename
10337        pkg.codePath = args.getCodePath();
10338        pkg.baseCodePath = args.getCodePath();
10339        pkg.splitCodePaths = null;
10340        pkg.applicationInfo.sourceDir = args.getCodePath();
10341        pkg.applicationInfo.publicSourceDir = args.getResourcePath();
10342        pkg.applicationInfo.splitSourceDirs = null;
10343        pkg.applicationInfo.splitPublicSourceDirs = null;
10344        pkg.applicationInfo.nativeLibraryDir = args.getNativeLibraryPath();
10345
10346        if (replace) {
10347            replacePackageLI(pkg, parseFlags, scanMode, args.user,
10348                    installerPackageName, res, args.abiOverride);
10349        } else {
10350            installNewPackageLI(pkg, parseFlags, scanMode | SCAN_DELETE_DATA_ON_FAILURES, args.user,
10351                    installerPackageName, res, args.abiOverride);
10352        }
10353        synchronized (mPackages) {
10354            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10355            if (ps != null) {
10356                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10357            }
10358        }
10359    }
10360
10361    private static boolean isForwardLocked(PackageParser.Package pkg) {
10362        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10363    }
10364
10365
10366    private boolean isForwardLocked(PackageSetting ps) {
10367        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10368    }
10369
10370    private static boolean isExternal(PackageParser.Package pkg) {
10371        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10372    }
10373
10374    private static boolean isExternal(PackageSetting ps) {
10375        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10376    }
10377
10378    private static boolean isSystemApp(PackageParser.Package pkg) {
10379        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10380    }
10381
10382    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10383        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10384    }
10385
10386    private static boolean isSystemApp(ApplicationInfo info) {
10387        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10388    }
10389
10390    private static boolean isSystemApp(PackageSetting ps) {
10391        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10392    }
10393
10394    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10395        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10396    }
10397
10398    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10399        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10400    }
10401
10402    private int packageFlagsToInstallFlags(PackageSetting ps) {
10403        int installFlags = 0;
10404        if (isExternal(ps)) {
10405            installFlags |= PackageManager.INSTALL_EXTERNAL;
10406        }
10407        if (isForwardLocked(ps)) {
10408            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10409        }
10410        return installFlags;
10411    }
10412
10413    private void deleteTempPackageFiles() {
10414        final FilenameFilter filter = new FilenameFilter() {
10415            public boolean accept(File dir, String name) {
10416                return name.startsWith("vmdl") && name.endsWith(".tmp");
10417            }
10418        };
10419        deleteTempPackageFilesInDirectory(mAppInstallDir, filter);
10420        deleteTempPackageFilesInDirectory(mDrmAppPrivateInstallDir, filter);
10421    }
10422
10423    private static final void deleteTempPackageFilesInDirectory(File directory,
10424            FilenameFilter filter) {
10425        final String[] tmpFilesList = directory.list(filter);
10426        if (tmpFilesList == null) {
10427            return;
10428        }
10429        for (int i = 0; i < tmpFilesList.length; i++) {
10430            final File tmpFile = new File(directory, tmpFilesList[i]);
10431            tmpFile.delete();
10432        }
10433    }
10434
10435    private File createTempPackageFile(File installDir) {
10436        File tmpPackageFile;
10437        try {
10438            tmpPackageFile = File.createTempFile("vmdl", ".tmp", installDir);
10439        } catch (IOException e) {
10440            Slog.e(TAG, "Couldn't create temp file for downloaded package file.");
10441            return null;
10442        }
10443        try {
10444            FileUtils.setPermissions(
10445                    tmpPackageFile.getCanonicalPath(), FileUtils.S_IRUSR|FileUtils.S_IWUSR,
10446                    -1, -1);
10447            if (!SELinux.restorecon(tmpPackageFile)) {
10448                return null;
10449            }
10450        } catch (IOException e) {
10451            Slog.e(TAG, "Trouble getting the canoncical path for a temp file.");
10452            return null;
10453        }
10454        return tmpPackageFile;
10455    }
10456
10457    @Override
10458    public void deletePackageAsUser(final String packageName,
10459                                    final IPackageDeleteObserver observer,
10460                                    final int userId, final int flags) {
10461        mContext.enforceCallingOrSelfPermission(
10462                android.Manifest.permission.DELETE_PACKAGES, null);
10463        final int uid = Binder.getCallingUid();
10464        if (UserHandle.getUserId(uid) != userId) {
10465            mContext.enforceCallingPermission(
10466                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10467                    "deletePackage for user " + userId);
10468        }
10469        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10470            try {
10471                observer.packageDeleted(packageName, PackageManager.DELETE_FAILED_USER_RESTRICTED);
10472            } catch (RemoteException re) {
10473            }
10474            return;
10475        }
10476
10477        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10478        // Queue up an async operation since the package deletion may take a little while.
10479        mHandler.post(new Runnable() {
10480            public void run() {
10481                mHandler.removeCallbacks(this);
10482                final int returnCode = deletePackageX(packageName, userId, flags);
10483                if (observer != null) {
10484                    try {
10485                        observer.packageDeleted(packageName, returnCode);
10486                    } catch (RemoteException e) {
10487                        Log.i(TAG, "Observer no longer exists.");
10488                    } //end catch
10489                } //end if
10490            } //end run
10491        });
10492    }
10493
10494    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10495        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10496                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10497        try {
10498            if (dpm != null && (dpm.packageHasActiveAdmins(packageName, userId)
10499                    || dpm.isDeviceOwner(packageName))) {
10500                return true;
10501            }
10502        } catch (RemoteException e) {
10503        }
10504        return false;
10505    }
10506
10507    /**
10508     *  This method is an internal method that could be get invoked either
10509     *  to delete an installed package or to clean up a failed installation.
10510     *  After deleting an installed package, a broadcast is sent to notify any
10511     *  listeners that the package has been installed. For cleaning up a failed
10512     *  installation, the broadcast is not necessary since the package's
10513     *  installation wouldn't have sent the initial broadcast either
10514     *  The key steps in deleting a package are
10515     *  deleting the package information in internal structures like mPackages,
10516     *  deleting the packages base directories through installd
10517     *  updating mSettings to reflect current status
10518     *  persisting settings for later use
10519     *  sending a broadcast if necessary
10520     */
10521    private int deletePackageX(String packageName, int userId, int flags) {
10522        final PackageRemovedInfo info = new PackageRemovedInfo();
10523        final boolean res;
10524
10525        if (isPackageDeviceAdmin(packageName, userId)) {
10526            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10527            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10528        }
10529
10530        boolean removedForAllUsers = false;
10531        boolean systemUpdate = false;
10532
10533        // for the uninstall-updates case and restricted profiles, remember the per-
10534        // userhandle installed state
10535        int[] allUsers;
10536        boolean[] perUserInstalled;
10537        synchronized (mPackages) {
10538            PackageSetting ps = mSettings.mPackages.get(packageName);
10539            allUsers = sUserManager.getUserIds();
10540            perUserInstalled = new boolean[allUsers.length];
10541            for (int i = 0; i < allUsers.length; i++) {
10542                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10543            }
10544        }
10545
10546        synchronized (mInstallLock) {
10547            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10548            res = deletePackageLI(packageName,
10549                    (flags & PackageManager.DELETE_ALL_USERS) != 0
10550                            ? UserHandle.ALL : new UserHandle(userId),
10551                    true, allUsers, perUserInstalled,
10552                    flags | REMOVE_CHATTY, info, true);
10553            systemUpdate = info.isRemovedPackageSystemUpdate;
10554            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10555                removedForAllUsers = true;
10556            }
10557            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10558                    + " removedForAllUsers=" + removedForAllUsers);
10559        }
10560
10561        if (res) {
10562            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10563
10564            // If the removed package was a system update, the old system package
10565            // was re-enabled; we need to broadcast this information
10566            if (systemUpdate) {
10567                Bundle extras = new Bundle(1);
10568                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10569                        ? info.removedAppId : info.uid);
10570                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10571
10572                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10573                        extras, null, null, null);
10574                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10575                        extras, null, null, null);
10576                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10577                        null, packageName, null, null);
10578            }
10579        }
10580        // Force a gc here.
10581        Runtime.getRuntime().gc();
10582        // Delete the resources here after sending the broadcast to let
10583        // other processes clean up before deleting resources.
10584        if (info.args != null) {
10585            synchronized (mInstallLock) {
10586                info.args.doPostDeleteLI(true);
10587            }
10588        }
10589
10590        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10591    }
10592
10593    static class PackageRemovedInfo {
10594        String removedPackage;
10595        int uid = -1;
10596        int removedAppId = -1;
10597        int[] removedUsers = null;
10598        boolean isRemovedPackageSystemUpdate = false;
10599        // Clean up resources deleted packages.
10600        InstallArgs args = null;
10601
10602        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10603            Bundle extras = new Bundle(1);
10604            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10605            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10606            if (replacing) {
10607                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10608            }
10609            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10610            if (removedPackage != null) {
10611                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10612                        extras, null, null, removedUsers);
10613                if (fullRemove && !replacing) {
10614                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10615                            extras, null, null, removedUsers);
10616                }
10617            }
10618            if (removedAppId >= 0) {
10619                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10620                        removedUsers);
10621            }
10622        }
10623    }
10624
10625    /*
10626     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10627     * flag is not set, the data directory is removed as well.
10628     * make sure this flag is set for partially installed apps. If not its meaningless to
10629     * delete a partially installed application.
10630     */
10631    private void removePackageDataLI(PackageSetting ps,
10632            int[] allUserHandles, boolean[] perUserInstalled,
10633            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10634        String packageName = ps.name;
10635        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10636        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10637        // Retrieve object to delete permissions for shared user later on
10638        final PackageSetting deletedPs;
10639        // reader
10640        synchronized (mPackages) {
10641            deletedPs = mSettings.mPackages.get(packageName);
10642            if (outInfo != null) {
10643                outInfo.removedPackage = packageName;
10644                outInfo.removedUsers = deletedPs != null
10645                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10646                        : null;
10647            }
10648        }
10649        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10650            removeDataDirsLI(packageName);
10651            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10652        }
10653        // writer
10654        synchronized (mPackages) {
10655            if (deletedPs != null) {
10656                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10657                    if (outInfo != null) {
10658                        mSettings.mKeySetManagerService.removeAppKeySetData(packageName);
10659                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10660                    }
10661                    if (deletedPs != null) {
10662                        updatePermissionsLPw(deletedPs.name, null, 0);
10663                        if (deletedPs.sharedUser != null) {
10664                            // remove permissions associated with package
10665                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10666                        }
10667                    }
10668                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10669                }
10670                // make sure to preserve per-user disabled state if this removal was just
10671                // a downgrade of a system app to the factory package
10672                if (allUserHandles != null && perUserInstalled != null) {
10673                    if (DEBUG_REMOVE) {
10674                        Slog.d(TAG, "Propagating install state across downgrade");
10675                    }
10676                    for (int i = 0; i < allUserHandles.length; i++) {
10677                        if (DEBUG_REMOVE) {
10678                            Slog.d(TAG, "    user " + allUserHandles[i]
10679                                    + " => " + perUserInstalled[i]);
10680                        }
10681                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10682                    }
10683                }
10684            }
10685            // can downgrade to reader
10686            if (writeSettings) {
10687                // Save settings now
10688                mSettings.writeLPr();
10689            }
10690        }
10691        if (outInfo != null) {
10692            // A user ID was deleted here. Go through all users and remove it
10693            // from KeyStore.
10694            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10695        }
10696    }
10697
10698    static boolean locationIsPrivileged(File path) {
10699        try {
10700            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10701                    .getCanonicalPath();
10702            return path.getCanonicalPath().startsWith(privilegedAppDir);
10703        } catch (IOException e) {
10704            Slog.e(TAG, "Unable to access code path " + path);
10705        }
10706        return false;
10707    }
10708
10709    /*
10710     * Tries to delete system package.
10711     */
10712    private boolean deleteSystemPackageLI(PackageSetting newPs,
10713            int[] allUserHandles, boolean[] perUserInstalled,
10714            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10715        final boolean applyUserRestrictions
10716                = (allUserHandles != null) && (perUserInstalled != null);
10717        PackageSetting disabledPs = null;
10718        // Confirm if the system package has been updated
10719        // An updated system app can be deleted. This will also have to restore
10720        // the system pkg from system partition
10721        // reader
10722        synchronized (mPackages) {
10723            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10724        }
10725        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10726                + " disabledPs=" + disabledPs);
10727        if (disabledPs == null) {
10728            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10729            return false;
10730        } else if (DEBUG_REMOVE) {
10731            Slog.d(TAG, "Deleting system pkg from data partition");
10732        }
10733        if (DEBUG_REMOVE) {
10734            if (applyUserRestrictions) {
10735                Slog.d(TAG, "Remembering install states:");
10736                for (int i = 0; i < allUserHandles.length; i++) {
10737                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10738                }
10739            }
10740        }
10741        // Delete the updated package
10742        outInfo.isRemovedPackageSystemUpdate = true;
10743        if (disabledPs.versionCode < newPs.versionCode) {
10744            // Delete data for downgrades
10745            flags &= ~PackageManager.DELETE_KEEP_DATA;
10746        } else {
10747            // Preserve data by setting flag
10748            flags |= PackageManager.DELETE_KEEP_DATA;
10749        }
10750        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10751                allUserHandles, perUserInstalled, outInfo, writeSettings);
10752        if (!ret) {
10753            return false;
10754        }
10755        // writer
10756        synchronized (mPackages) {
10757            // Reinstate the old system package
10758            mSettings.enableSystemPackageLPw(newPs.name);
10759            // Remove any native libraries from the upgraded package.
10760            NativeLibraryHelper.removeNativeBinariesLI(newPs.nativeLibraryPathString);
10761        }
10762        // Install the system package
10763        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10764        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10765        if (locationIsPrivileged(disabledPs.codePath)) {
10766            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10767        }
10768        PackageParser.Package newPkg = scanPackageLI(disabledPs.codePath,
10769                parseFlags, SCAN_MONITOR | SCAN_NO_PATHS, 0, null, null);
10770
10771        if (newPkg == null) {
10772            Slog.w(TAG, "Failed to restore system package:" + newPs.name
10773                    + " with error:" + mLastScanError);
10774            return false;
10775        }
10776        // writer
10777        synchronized (mPackages) {
10778            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10779            setInternalAppNativeLibraryPath(newPkg, ps);
10780            updatePermissionsLPw(newPkg.packageName, newPkg,
10781                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10782            if (applyUserRestrictions) {
10783                if (DEBUG_REMOVE) {
10784                    Slog.d(TAG, "Propagating install state across reinstall");
10785                }
10786                for (int i = 0; i < allUserHandles.length; i++) {
10787                    if (DEBUG_REMOVE) {
10788                        Slog.d(TAG, "    user " + allUserHandles[i]
10789                                + " => " + perUserInstalled[i]);
10790                    }
10791                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10792                }
10793                // Regardless of writeSettings we need to ensure that this restriction
10794                // state propagation is persisted
10795                mSettings.writeAllUsersPackageRestrictionsLPr();
10796            }
10797            // can downgrade to reader here
10798            if (writeSettings) {
10799                mSettings.writeLPr();
10800            }
10801        }
10802        return true;
10803    }
10804
10805    private boolean deleteInstalledPackageLI(PackageSetting ps,
10806            boolean deleteCodeAndResources, int flags,
10807            int[] allUserHandles, boolean[] perUserInstalled,
10808            PackageRemovedInfo outInfo, boolean writeSettings) {
10809        if (outInfo != null) {
10810            outInfo.uid = ps.appId;
10811        }
10812
10813        // Delete package data from internal structures and also remove data if flag is set
10814        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10815
10816        // Delete application code and resources
10817        if (deleteCodeAndResources && (outInfo != null)) {
10818            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10819                    ps.codePathString, ps.resourcePathString, ps.nativeLibraryPathString,
10820                    getAppInstructionSetFromSettings(ps));
10821        }
10822        return true;
10823    }
10824
10825    @Override
10826    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10827            int userId) {
10828        mContext.enforceCallingOrSelfPermission(
10829                android.Manifest.permission.DELETE_PACKAGES, null);
10830        synchronized (mPackages) {
10831            PackageSetting ps = mSettings.mPackages.get(packageName);
10832            if (ps == null) {
10833                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10834                return false;
10835            }
10836            if (!ps.getInstalled(userId)) {
10837                // Can't block uninstall for an app that is not installed or enabled.
10838                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10839                return false;
10840            }
10841            ps.setBlockUninstall(blockUninstall, userId);
10842            mSettings.writePackageRestrictionsLPr(userId);
10843        }
10844        return true;
10845    }
10846
10847    @Override
10848    public boolean getBlockUninstallForUser(String packageName, int userId) {
10849        synchronized (mPackages) {
10850            PackageSetting ps = mSettings.mPackages.get(packageName);
10851            if (ps == null) {
10852                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10853                return false;
10854            }
10855            return ps.getBlockUninstall(userId);
10856        }
10857    }
10858
10859    /*
10860     * This method handles package deletion in general
10861     */
10862    private boolean deletePackageLI(String packageName, UserHandle user,
10863            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10864            int flags, PackageRemovedInfo outInfo,
10865            boolean writeSettings) {
10866        if (packageName == null) {
10867            Slog.w(TAG, "Attempt to delete null packageName.");
10868            return false;
10869        }
10870        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10871        PackageSetting ps;
10872        boolean dataOnly = false;
10873        int removeUser = -1;
10874        int appId = -1;
10875        synchronized (mPackages) {
10876            ps = mSettings.mPackages.get(packageName);
10877            if (ps == null) {
10878                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10879                return false;
10880            }
10881            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10882                    && user.getIdentifier() != UserHandle.USER_ALL) {
10883                // The caller is asking that the package only be deleted for a single
10884                // user.  To do this, we just mark its uninstalled state and delete
10885                // its data.  If this is a system app, we only allow this to happen if
10886                // they have set the special DELETE_SYSTEM_APP which requests different
10887                // semantics than normal for uninstalling system apps.
10888                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10889                ps.setUserState(user.getIdentifier(),
10890                        COMPONENT_ENABLED_STATE_DEFAULT,
10891                        false, //installed
10892                        true,  //stopped
10893                        true,  //notLaunched
10894                        false, //blocked
10895                        null, null, null,
10896                        false // blockUninstall
10897                        );
10898                if (!isSystemApp(ps)) {
10899                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10900                        // Other user still have this package installed, so all
10901                        // we need to do is clear this user's data and save that
10902                        // it is uninstalled.
10903                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10904                        removeUser = user.getIdentifier();
10905                        appId = ps.appId;
10906                        mSettings.writePackageRestrictionsLPr(removeUser);
10907                    } else {
10908                        // We need to set it back to 'installed' so the uninstall
10909                        // broadcasts will be sent correctly.
10910                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10911                        ps.setInstalled(true, user.getIdentifier());
10912                    }
10913                } else {
10914                    // This is a system app, so we assume that the
10915                    // other users still have this package installed, so all
10916                    // we need to do is clear this user's data and save that
10917                    // it is uninstalled.
10918                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10919                    removeUser = user.getIdentifier();
10920                    appId = ps.appId;
10921                    mSettings.writePackageRestrictionsLPr(removeUser);
10922                }
10923            }
10924        }
10925
10926        if (removeUser >= 0) {
10927            // From above, we determined that we are deleting this only
10928            // for a single user.  Continue the work here.
10929            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10930            if (outInfo != null) {
10931                outInfo.removedPackage = packageName;
10932                outInfo.removedAppId = appId;
10933                outInfo.removedUsers = new int[] {removeUser};
10934            }
10935            mInstaller.clearUserData(packageName, removeUser);
10936            removeKeystoreDataIfNeeded(removeUser, appId);
10937            schedulePackageCleaning(packageName, removeUser, false);
10938            return true;
10939        }
10940
10941        if (dataOnly) {
10942            // Delete application data first
10943            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10944            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10945            return true;
10946        }
10947
10948        boolean ret = false;
10949        if (isSystemApp(ps)) {
10950            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10951            // When an updated system application is deleted we delete the existing resources as well and
10952            // fall back to existing code in system partition
10953            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10954                    flags, outInfo, writeSettings);
10955        } else {
10956            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10957            // Kill application pre-emptively especially for apps on sd.
10958            killApplication(packageName, ps.appId, "uninstall pkg");
10959            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10960                    allUserHandles, perUserInstalled,
10961                    outInfo, writeSettings);
10962        }
10963
10964        return ret;
10965    }
10966
10967    private final class ClearStorageConnection implements ServiceConnection {
10968        IMediaContainerService mContainerService;
10969
10970        @Override
10971        public void onServiceConnected(ComponentName name, IBinder service) {
10972            synchronized (this) {
10973                mContainerService = IMediaContainerService.Stub.asInterface(service);
10974                notifyAll();
10975            }
10976        }
10977
10978        @Override
10979        public void onServiceDisconnected(ComponentName name) {
10980        }
10981    }
10982
10983    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10984        final boolean mounted;
10985        if (Environment.isExternalStorageEmulated()) {
10986            mounted = true;
10987        } else {
10988            final String status = Environment.getExternalStorageState();
10989
10990            mounted = status.equals(Environment.MEDIA_MOUNTED)
10991                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10992        }
10993
10994        if (!mounted) {
10995            return;
10996        }
10997
10998        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10999        int[] users;
11000        if (userId == UserHandle.USER_ALL) {
11001            users = sUserManager.getUserIds();
11002        } else {
11003            users = new int[] { userId };
11004        }
11005        final ClearStorageConnection conn = new ClearStorageConnection();
11006        if (mContext.bindServiceAsUser(
11007                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11008            try {
11009                for (int curUser : users) {
11010                    long timeout = SystemClock.uptimeMillis() + 5000;
11011                    synchronized (conn) {
11012                        long now = SystemClock.uptimeMillis();
11013                        while (conn.mContainerService == null && now < timeout) {
11014                            try {
11015                                conn.wait(timeout - now);
11016                            } catch (InterruptedException e) {
11017                            }
11018                        }
11019                    }
11020                    if (conn.mContainerService == null) {
11021                        return;
11022                    }
11023
11024                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11025                    clearDirectory(conn.mContainerService,
11026                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11027                    if (allData) {
11028                        clearDirectory(conn.mContainerService,
11029                                userEnv.buildExternalStorageAppDataDirs(packageName));
11030                        clearDirectory(conn.mContainerService,
11031                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11032                    }
11033                }
11034            } finally {
11035                mContext.unbindService(conn);
11036            }
11037        }
11038    }
11039
11040    @Override
11041    public void clearApplicationUserData(final String packageName,
11042            final IPackageDataObserver observer, final int userId) {
11043        mContext.enforceCallingOrSelfPermission(
11044                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11045        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, "clear application data");
11046        // Queue up an async operation since the package deletion may take a little while.
11047        mHandler.post(new Runnable() {
11048            public void run() {
11049                mHandler.removeCallbacks(this);
11050                final boolean succeeded;
11051                synchronized (mInstallLock) {
11052                    succeeded = clearApplicationUserDataLI(packageName, userId);
11053                }
11054                clearExternalStorageDataSync(packageName, userId, true);
11055                if (succeeded) {
11056                    // invoke DeviceStorageMonitor's update method to clear any notifications
11057                    DeviceStorageMonitorInternal
11058                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11059                    if (dsm != null) {
11060                        dsm.checkMemory();
11061                    }
11062                }
11063                if(observer != null) {
11064                    try {
11065                        observer.onRemoveCompleted(packageName, succeeded);
11066                    } catch (RemoteException e) {
11067                        Log.i(TAG, "Observer no longer exists.");
11068                    }
11069                } //end if observer
11070            } //end run
11071        });
11072    }
11073
11074    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11075        if (packageName == null) {
11076            Slog.w(TAG, "Attempt to delete null packageName.");
11077            return false;
11078        }
11079        PackageParser.Package p;
11080        boolean dataOnly = false;
11081        final int appId;
11082        synchronized (mPackages) {
11083            p = mPackages.get(packageName);
11084            if (p == null) {
11085                dataOnly = true;
11086                PackageSetting ps = mSettings.mPackages.get(packageName);
11087                if ((ps == null) || (ps.pkg == null)) {
11088                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11089                    return false;
11090                }
11091                p = ps.pkg;
11092            }
11093            if (!dataOnly) {
11094                // need to check this only for fully installed applications
11095                if (p == null) {
11096                    Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11097                    return false;
11098                }
11099                final ApplicationInfo applicationInfo = p.applicationInfo;
11100                if (applicationInfo == null) {
11101                    Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11102                    return false;
11103                }
11104            }
11105            if (p != null && p.applicationInfo != null) {
11106                appId = p.applicationInfo.uid;
11107            } else {
11108                appId = -1;
11109            }
11110        }
11111        int retCode = mInstaller.clearUserData(packageName, userId);
11112        if (retCode < 0) {
11113            Slog.w(TAG, "Couldn't remove cache files for package: "
11114                    + packageName);
11115            return false;
11116        }
11117        removeKeystoreDataIfNeeded(userId, appId);
11118        return true;
11119    }
11120
11121    /**
11122     * Remove entries from the keystore daemon. Will only remove it if the
11123     * {@code appId} is valid.
11124     */
11125    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11126        if (appId < 0) {
11127            return;
11128        }
11129
11130        final KeyStore keyStore = KeyStore.getInstance();
11131        if (keyStore != null) {
11132            if (userId == UserHandle.USER_ALL) {
11133                for (final int individual : sUserManager.getUserIds()) {
11134                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11135                }
11136            } else {
11137                keyStore.clearUid(UserHandle.getUid(userId, appId));
11138            }
11139        } else {
11140            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11141        }
11142    }
11143
11144    @Override
11145    public void deleteApplicationCacheFiles(final String packageName,
11146            final IPackageDataObserver observer) {
11147        mContext.enforceCallingOrSelfPermission(
11148                android.Manifest.permission.DELETE_CACHE_FILES, null);
11149        // Queue up an async operation since the package deletion may take a little while.
11150        final int userId = UserHandle.getCallingUserId();
11151        mHandler.post(new Runnable() {
11152            public void run() {
11153                mHandler.removeCallbacks(this);
11154                final boolean succeded;
11155                synchronized (mInstallLock) {
11156                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11157                }
11158                clearExternalStorageDataSync(packageName, userId, false);
11159                if(observer != null) {
11160                    try {
11161                        observer.onRemoveCompleted(packageName, succeded);
11162                    } catch (RemoteException e) {
11163                        Log.i(TAG, "Observer no longer exists.");
11164                    }
11165                } //end if observer
11166            } //end run
11167        });
11168    }
11169
11170    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11171        if (packageName == null) {
11172            Slog.w(TAG, "Attempt to delete null packageName.");
11173            return false;
11174        }
11175        PackageParser.Package p;
11176        synchronized (mPackages) {
11177            p = mPackages.get(packageName);
11178        }
11179        if (p == null) {
11180            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11181            return false;
11182        }
11183        final ApplicationInfo applicationInfo = p.applicationInfo;
11184        if (applicationInfo == null) {
11185            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11186            return false;
11187        }
11188        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11189        if (retCode < 0) {
11190            Slog.w(TAG, "Couldn't remove cache files for package: "
11191                       + packageName + " u" + userId);
11192            return false;
11193        }
11194        return true;
11195    }
11196
11197    @Override
11198    public void getPackageSizeInfo(final String packageName, int userHandle,
11199            final IPackageStatsObserver observer) {
11200        mContext.enforceCallingOrSelfPermission(
11201                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11202        if (packageName == null) {
11203            throw new IllegalArgumentException("Attempt to get size of null packageName");
11204        }
11205
11206        PackageStats stats = new PackageStats(packageName, userHandle);
11207
11208        /*
11209         * Queue up an async operation since the package measurement may take a
11210         * little while.
11211         */
11212        Message msg = mHandler.obtainMessage(INIT_COPY);
11213        msg.obj = new MeasureParams(stats, observer);
11214        mHandler.sendMessage(msg);
11215    }
11216
11217    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11218            PackageStats pStats) {
11219        if (packageName == null) {
11220            Slog.w(TAG, "Attempt to get size of null packageName.");
11221            return false;
11222        }
11223        PackageParser.Package p;
11224        boolean dataOnly = false;
11225        String libDirPath = null;
11226        String asecPath = null;
11227        PackageSetting ps = null;
11228        synchronized (mPackages) {
11229            p = mPackages.get(packageName);
11230            ps = mSettings.mPackages.get(packageName);
11231            if(p == null) {
11232                dataOnly = true;
11233                if((ps == null) || (ps.pkg == null)) {
11234                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11235                    return false;
11236                }
11237                p = ps.pkg;
11238            }
11239            if (ps != null) {
11240                libDirPath = ps.nativeLibraryPathString;
11241            }
11242            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11243                String secureContainerId = cidFromCodePath(p.applicationInfo.sourceDir);
11244                if (secureContainerId != null) {
11245                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11246                }
11247            }
11248        }
11249        String publicSrcDir = null;
11250        if(!dataOnly) {
11251            final ApplicationInfo applicationInfo = p.applicationInfo;
11252            if (applicationInfo == null) {
11253                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11254                return false;
11255            }
11256            if (isForwardLocked(p)) {
11257                publicSrcDir = applicationInfo.publicSourceDir;
11258            }
11259        }
11260        // TODO: extend to measure size of split APKs
11261        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirPath,
11262                publicSrcDir, asecPath, getAppInstructionSetFromSettings(ps),
11263                pStats);
11264        if (res < 0) {
11265            return false;
11266        }
11267
11268        // Fix-up for forward-locked applications in ASEC containers.
11269        if (!isExternal(p)) {
11270            pStats.codeSize += pStats.externalCodeSize;
11271            pStats.externalCodeSize = 0L;
11272        }
11273
11274        return true;
11275    }
11276
11277
11278    @Override
11279    public void addPackageToPreferred(String packageName) {
11280        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11281    }
11282
11283    @Override
11284    public void removePackageFromPreferred(String packageName) {
11285        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11286    }
11287
11288    @Override
11289    public List<PackageInfo> getPreferredPackages(int flags) {
11290        return new ArrayList<PackageInfo>();
11291    }
11292
11293    private int getUidTargetSdkVersionLockedLPr(int uid) {
11294        Object obj = mSettings.getUserIdLPr(uid);
11295        if (obj instanceof SharedUserSetting) {
11296            final SharedUserSetting sus = (SharedUserSetting) obj;
11297            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11298            final Iterator<PackageSetting> it = sus.packages.iterator();
11299            while (it.hasNext()) {
11300                final PackageSetting ps = it.next();
11301                if (ps.pkg != null) {
11302                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11303                    if (v < vers) vers = v;
11304                }
11305            }
11306            return vers;
11307        } else if (obj instanceof PackageSetting) {
11308            final PackageSetting ps = (PackageSetting) obj;
11309            if (ps.pkg != null) {
11310                return ps.pkg.applicationInfo.targetSdkVersion;
11311            }
11312        }
11313        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11314    }
11315
11316    @Override
11317    public void addPreferredActivity(IntentFilter filter, int match,
11318            ComponentName[] set, ComponentName activity, int userId) {
11319        addPreferredActivityInternal(filter, match, set, activity, true, userId);
11320    }
11321
11322    private void addPreferredActivityInternal(IntentFilter filter, int match,
11323            ComponentName[] set, ComponentName activity, boolean always, int userId) {
11324        // writer
11325        int callingUid = Binder.getCallingUid();
11326        enforceCrossUserPermission(callingUid, userId, true, "add preferred activity");
11327        if (filter.countActions() == 0) {
11328            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11329            return;
11330        }
11331        synchronized (mPackages) {
11332            if (mContext.checkCallingOrSelfPermission(
11333                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11334                    != PackageManager.PERMISSION_GRANTED) {
11335                if (getUidTargetSdkVersionLockedLPr(callingUid)
11336                        < Build.VERSION_CODES.FROYO) {
11337                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11338                            + callingUid);
11339                    return;
11340                }
11341                mContext.enforceCallingOrSelfPermission(
11342                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11343            }
11344
11345            Slog.i(TAG, "Adding preferred activity " + activity + " for user " + userId + " :");
11346            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11347            mSettings.editPreferredActivitiesLPw(userId).addFilter(
11348                    new PreferredActivity(filter, match, set, activity, always));
11349            mSettings.writePackageRestrictionsLPr(userId);
11350        }
11351    }
11352
11353    @Override
11354    public void replacePreferredActivity(IntentFilter filter, int match,
11355            ComponentName[] set, ComponentName activity) {
11356        if (filter.countActions() != 1) {
11357            throw new IllegalArgumentException(
11358                    "replacePreferredActivity expects filter to have only 1 action.");
11359        }
11360        if (filter.countDataAuthorities() != 0
11361                || filter.countDataPaths() != 0
11362                || filter.countDataSchemes() > 1
11363                || filter.countDataTypes() != 0) {
11364            throw new IllegalArgumentException(
11365                    "replacePreferredActivity expects filter to have no data authorities, " +
11366                    "paths, or types; and at most one scheme.");
11367        }
11368        synchronized (mPackages) {
11369            if (mContext.checkCallingOrSelfPermission(
11370                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11371                    != PackageManager.PERMISSION_GRANTED) {
11372                if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11373                        < Build.VERSION_CODES.FROYO) {
11374                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11375                            + Binder.getCallingUid());
11376                    return;
11377                }
11378                mContext.enforceCallingOrSelfPermission(
11379                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11380            }
11381
11382            final int callingUserId = UserHandle.getCallingUserId();
11383            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(callingUserId);
11384            if (pir != null) {
11385                Intent intent = new Intent(filter.getAction(0)).addCategory(filter.getCategory(0));
11386                if (filter.countDataSchemes() == 1) {
11387                    Uri.Builder builder = new Uri.Builder();
11388                    builder.scheme(filter.getDataScheme(0));
11389                    intent.setData(builder.build());
11390                }
11391                List<PreferredActivity> matches = pir.queryIntent(
11392                        intent, null, true, callingUserId);
11393                if (DEBUG_PREFERRED) {
11394                    Slog.i(TAG, matches.size() + " preferred matches for " + intent);
11395                }
11396                for (int i = 0; i < matches.size(); i++) {
11397                    PreferredActivity pa = matches.get(i);
11398                    if (DEBUG_PREFERRED) {
11399                        Slog.i(TAG, "Removing preferred activity "
11400                                + pa.mPref.mComponent + ":");
11401                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11402                    }
11403                    pir.removeFilter(pa);
11404                }
11405            }
11406            addPreferredActivityInternal(filter, match, set, activity, true, callingUserId);
11407        }
11408    }
11409
11410    @Override
11411    public void clearPackagePreferredActivities(String packageName) {
11412        final int uid = Binder.getCallingUid();
11413        // writer
11414        synchronized (mPackages) {
11415            PackageParser.Package pkg = mPackages.get(packageName);
11416            if (pkg == null || pkg.applicationInfo.uid != uid) {
11417                if (mContext.checkCallingOrSelfPermission(
11418                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11419                        != PackageManager.PERMISSION_GRANTED) {
11420                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11421                            < Build.VERSION_CODES.FROYO) {
11422                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11423                                + Binder.getCallingUid());
11424                        return;
11425                    }
11426                    mContext.enforceCallingOrSelfPermission(
11427                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11428                }
11429            }
11430
11431            int user = UserHandle.getCallingUserId();
11432            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11433                mSettings.writePackageRestrictionsLPr(user);
11434                scheduleWriteSettingsLocked();
11435            }
11436        }
11437    }
11438
11439    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11440    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11441        ArrayList<PreferredActivity> removed = null;
11442        boolean changed = false;
11443        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11444            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11445            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11446            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11447                continue;
11448            }
11449            Iterator<PreferredActivity> it = pir.filterIterator();
11450            while (it.hasNext()) {
11451                PreferredActivity pa = it.next();
11452                // Mark entry for removal only if it matches the package name
11453                // and the entry is of type "always".
11454                if (packageName == null ||
11455                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11456                                && pa.mPref.mAlways)) {
11457                    if (removed == null) {
11458                        removed = new ArrayList<PreferredActivity>();
11459                    }
11460                    removed.add(pa);
11461                }
11462            }
11463            if (removed != null) {
11464                for (int j=0; j<removed.size(); j++) {
11465                    PreferredActivity pa = removed.get(j);
11466                    pir.removeFilter(pa);
11467                }
11468                changed = true;
11469            }
11470        }
11471        return changed;
11472    }
11473
11474    @Override
11475    public void resetPreferredActivities(int userId) {
11476        mContext.enforceCallingOrSelfPermission(
11477                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11478        // writer
11479        synchronized (mPackages) {
11480            int user = UserHandle.getCallingUserId();
11481            clearPackagePreferredActivitiesLPw(null, user);
11482            mSettings.readDefaultPreferredAppsLPw(this, user);
11483            mSettings.writePackageRestrictionsLPr(user);
11484            scheduleWriteSettingsLocked();
11485        }
11486    }
11487
11488    @Override
11489    public int getPreferredActivities(List<IntentFilter> outFilters,
11490            List<ComponentName> outActivities, String packageName) {
11491
11492        int num = 0;
11493        final int userId = UserHandle.getCallingUserId();
11494        // reader
11495        synchronized (mPackages) {
11496            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11497            if (pir != null) {
11498                final Iterator<PreferredActivity> it = pir.filterIterator();
11499                while (it.hasNext()) {
11500                    final PreferredActivity pa = it.next();
11501                    if (packageName == null
11502                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11503                                    && pa.mPref.mAlways)) {
11504                        if (outFilters != null) {
11505                            outFilters.add(new IntentFilter(pa));
11506                        }
11507                        if (outActivities != null) {
11508                            outActivities.add(pa.mPref.mComponent);
11509                        }
11510                    }
11511                }
11512            }
11513        }
11514
11515        return num;
11516    }
11517
11518    @Override
11519    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11520            int userId) {
11521        int callingUid = Binder.getCallingUid();
11522        if (callingUid != Process.SYSTEM_UID) {
11523            throw new SecurityException(
11524                    "addPersistentPreferredActivity can only be run by the system");
11525        }
11526        if (filter.countActions() == 0) {
11527            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11528            return;
11529        }
11530        synchronized (mPackages) {
11531            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11532                    " :");
11533            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11534            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11535                    new PersistentPreferredActivity(filter, activity));
11536            mSettings.writePackageRestrictionsLPr(userId);
11537        }
11538    }
11539
11540    @Override
11541    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11542        int callingUid = Binder.getCallingUid();
11543        if (callingUid != Process.SYSTEM_UID) {
11544            throw new SecurityException(
11545                    "clearPackagePersistentPreferredActivities can only be run by the system");
11546        }
11547        ArrayList<PersistentPreferredActivity> removed = null;
11548        boolean changed = false;
11549        synchronized (mPackages) {
11550            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11551                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11552                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11553                        .valueAt(i);
11554                if (userId != thisUserId) {
11555                    continue;
11556                }
11557                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11558                while (it.hasNext()) {
11559                    PersistentPreferredActivity ppa = it.next();
11560                    // Mark entry for removal only if it matches the package name.
11561                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11562                        if (removed == null) {
11563                            removed = new ArrayList<PersistentPreferredActivity>();
11564                        }
11565                        removed.add(ppa);
11566                    }
11567                }
11568                if (removed != null) {
11569                    for (int j=0; j<removed.size(); j++) {
11570                        PersistentPreferredActivity ppa = removed.get(j);
11571                        ppir.removeFilter(ppa);
11572                    }
11573                    changed = true;
11574                }
11575            }
11576
11577            if (changed) {
11578                mSettings.writePackageRestrictionsLPr(userId);
11579            }
11580        }
11581    }
11582
11583    @Override
11584    public void addCrossProfileIntentFilter(IntentFilter intentFilter, int sourceUserId,
11585            int targetUserId, int flags) {
11586        mContext.enforceCallingOrSelfPermission(
11587                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11588        if (intentFilter.countActions() == 0) {
11589            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11590            return;
11591        }
11592        synchronized (mPackages) {
11593            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11594                    targetUserId, flags);
11595            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11596            mSettings.writePackageRestrictionsLPr(sourceUserId);
11597        }
11598    }
11599
11600    public void addCrossProfileIntentsForPackage(String packageName,
11601            int sourceUserId, int targetUserId) {
11602        mContext.enforceCallingOrSelfPermission(
11603                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11604        mSettings.addCrossProfilePackage(packageName, sourceUserId, targetUserId);
11605        mSettings.writePackageRestrictionsLPr(sourceUserId);
11606    }
11607
11608    public void removeCrossProfileIntentsForPackage(String packageName,
11609            int sourceUserId, int targetUserId) {
11610        mContext.enforceCallingOrSelfPermission(
11611                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11612        mSettings.removeCrossProfilePackage(packageName, sourceUserId, targetUserId);
11613        mSettings.writePackageRestrictionsLPr(sourceUserId);
11614    }
11615
11616    @Override
11617    public void clearCrossProfileIntentFilters(int sourceUserId) {
11618        mContext.enforceCallingOrSelfPermission(
11619                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11620        synchronized (mPackages) {
11621            CrossProfileIntentResolver resolver =
11622                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11623            HashSet<CrossProfileIntentFilter> set =
11624                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11625            for (CrossProfileIntentFilter filter : set) {
11626                if ((filter.getFlags() & PackageManager.SET_BY_PROFILE_OWNER) != 0) {
11627                    resolver.removeFilter(filter);
11628                }
11629            }
11630            mSettings.writePackageRestrictionsLPr(sourceUserId);
11631        }
11632    }
11633
11634    @Override
11635    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11636        Intent intent = new Intent(Intent.ACTION_MAIN);
11637        intent.addCategory(Intent.CATEGORY_HOME);
11638
11639        final int callingUserId = UserHandle.getCallingUserId();
11640        List<ResolveInfo> list = queryIntentActivities(intent, null,
11641                PackageManager.GET_META_DATA, callingUserId);
11642        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11643                true, false, false, callingUserId);
11644
11645        allHomeCandidates.clear();
11646        if (list != null) {
11647            for (ResolveInfo ri : list) {
11648                allHomeCandidates.add(ri);
11649            }
11650        }
11651        return (preferred == null || preferred.activityInfo == null)
11652                ? null
11653                : new ComponentName(preferred.activityInfo.packageName,
11654                        preferred.activityInfo.name);
11655    }
11656
11657    @Override
11658    public void setApplicationEnabledSetting(String appPackageName,
11659            int newState, int flags, int userId, String callingPackage) {
11660        if (!sUserManager.exists(userId)) return;
11661        if (callingPackage == null) {
11662            callingPackage = Integer.toString(Binder.getCallingUid());
11663        }
11664        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11665    }
11666
11667    @Override
11668    public void setComponentEnabledSetting(ComponentName componentName,
11669            int newState, int flags, int userId) {
11670        if (!sUserManager.exists(userId)) return;
11671        setEnabledSetting(componentName.getPackageName(),
11672                componentName.getClassName(), newState, flags, userId, null);
11673    }
11674
11675    private void setEnabledSetting(final String packageName, String className, int newState,
11676            final int flags, int userId, String callingPackage) {
11677        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11678              || newState == COMPONENT_ENABLED_STATE_ENABLED
11679              || newState == COMPONENT_ENABLED_STATE_DISABLED
11680              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11681              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11682            throw new IllegalArgumentException("Invalid new component state: "
11683                    + newState);
11684        }
11685        PackageSetting pkgSetting;
11686        final int uid = Binder.getCallingUid();
11687        final int permission = mContext.checkCallingOrSelfPermission(
11688                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11689        enforceCrossUserPermission(uid, userId, false, "set enabled");
11690        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11691        boolean sendNow = false;
11692        boolean isApp = (className == null);
11693        String componentName = isApp ? packageName : className;
11694        int packageUid = -1;
11695        ArrayList<String> components;
11696
11697        // writer
11698        synchronized (mPackages) {
11699            pkgSetting = mSettings.mPackages.get(packageName);
11700            if (pkgSetting == null) {
11701                if (className == null) {
11702                    throw new IllegalArgumentException(
11703                            "Unknown package: " + packageName);
11704                }
11705                throw new IllegalArgumentException(
11706                        "Unknown component: " + packageName
11707                        + "/" + className);
11708            }
11709            // Allow root and verify that userId is not being specified by a different user
11710            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11711                throw new SecurityException(
11712                        "Permission Denial: attempt to change component state from pid="
11713                        + Binder.getCallingPid()
11714                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11715            }
11716            if (className == null) {
11717                // We're dealing with an application/package level state change
11718                if (pkgSetting.getEnabled(userId) == newState) {
11719                    // Nothing to do
11720                    return;
11721                }
11722                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11723                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11724                    // Don't care about who enables an app.
11725                    callingPackage = null;
11726                }
11727                pkgSetting.setEnabled(newState, userId, callingPackage);
11728                // pkgSetting.pkg.mSetEnabled = newState;
11729            } else {
11730                // We're dealing with a component level state change
11731                // First, verify that this is a valid class name.
11732                PackageParser.Package pkg = pkgSetting.pkg;
11733                if (pkg == null || !pkg.hasComponentClassName(className)) {
11734                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11735                        throw new IllegalArgumentException("Component class " + className
11736                                + " does not exist in " + packageName);
11737                    } else {
11738                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11739                                + className + " does not exist in " + packageName);
11740                    }
11741                }
11742                switch (newState) {
11743                case COMPONENT_ENABLED_STATE_ENABLED:
11744                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11745                        return;
11746                    }
11747                    break;
11748                case COMPONENT_ENABLED_STATE_DISABLED:
11749                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11750                        return;
11751                    }
11752                    break;
11753                case COMPONENT_ENABLED_STATE_DEFAULT:
11754                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11755                        return;
11756                    }
11757                    break;
11758                default:
11759                    Slog.e(TAG, "Invalid new component state: " + newState);
11760                    return;
11761                }
11762            }
11763            mSettings.writePackageRestrictionsLPr(userId);
11764            components = mPendingBroadcasts.get(userId, packageName);
11765            final boolean newPackage = components == null;
11766            if (newPackage) {
11767                components = new ArrayList<String>();
11768            }
11769            if (!components.contains(componentName)) {
11770                components.add(componentName);
11771            }
11772            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11773                sendNow = true;
11774                // Purge entry from pending broadcast list if another one exists already
11775                // since we are sending one right away.
11776                mPendingBroadcasts.remove(userId, packageName);
11777            } else {
11778                if (newPackage) {
11779                    mPendingBroadcasts.put(userId, packageName, components);
11780                }
11781                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11782                    // Schedule a message
11783                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11784                }
11785            }
11786        }
11787
11788        long callingId = Binder.clearCallingIdentity();
11789        try {
11790            if (sendNow) {
11791                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11792                sendPackageChangedBroadcast(packageName,
11793                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11794            }
11795        } finally {
11796            Binder.restoreCallingIdentity(callingId);
11797        }
11798    }
11799
11800    private void sendPackageChangedBroadcast(String packageName,
11801            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11802        if (DEBUG_INSTALL)
11803            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11804                    + componentNames);
11805        Bundle extras = new Bundle(4);
11806        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11807        String nameList[] = new String[componentNames.size()];
11808        componentNames.toArray(nameList);
11809        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11810        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11811        extras.putInt(Intent.EXTRA_UID, packageUid);
11812        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11813                new int[] {UserHandle.getUserId(packageUid)});
11814    }
11815
11816    @Override
11817    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11818        if (!sUserManager.exists(userId)) return;
11819        final int uid = Binder.getCallingUid();
11820        final int permission = mContext.checkCallingOrSelfPermission(
11821                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11822        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11823        enforceCrossUserPermission(uid, userId, true, "stop package");
11824        // writer
11825        synchronized (mPackages) {
11826            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11827                    uid, userId)) {
11828                scheduleWritePackageRestrictionsLocked(userId);
11829            }
11830        }
11831    }
11832
11833    @Override
11834    public String getInstallerPackageName(String packageName) {
11835        // reader
11836        synchronized (mPackages) {
11837            return mSettings.getInstallerPackageNameLPr(packageName);
11838        }
11839    }
11840
11841    @Override
11842    public int getApplicationEnabledSetting(String packageName, int userId) {
11843        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11844        int uid = Binder.getCallingUid();
11845        enforceCrossUserPermission(uid, userId, false, "get enabled");
11846        // reader
11847        synchronized (mPackages) {
11848            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11849        }
11850    }
11851
11852    @Override
11853    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11854        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11855        int uid = Binder.getCallingUid();
11856        enforceCrossUserPermission(uid, userId, false, "get component enabled");
11857        // reader
11858        synchronized (mPackages) {
11859            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11860        }
11861    }
11862
11863    @Override
11864    public void enterSafeMode() {
11865        enforceSystemOrRoot("Only the system can request entering safe mode");
11866
11867        if (!mSystemReady) {
11868            mSafeMode = true;
11869        }
11870    }
11871
11872    @Override
11873    public void systemReady() {
11874        mSystemReady = true;
11875
11876        // Read the compatibilty setting when the system is ready.
11877        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11878                mContext.getContentResolver(),
11879                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11880        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11881        if (DEBUG_SETTINGS) {
11882            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11883        }
11884
11885        synchronized (mPackages) {
11886            // Verify that all of the preferred activity components actually
11887            // exist.  It is possible for applications to be updated and at
11888            // that point remove a previously declared activity component that
11889            // had been set as a preferred activity.  We try to clean this up
11890            // the next time we encounter that preferred activity, but it is
11891            // possible for the user flow to never be able to return to that
11892            // situation so here we do a sanity check to make sure we haven't
11893            // left any junk around.
11894            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11895            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11896                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11897                removed.clear();
11898                for (PreferredActivity pa : pir.filterSet()) {
11899                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11900                        removed.add(pa);
11901                    }
11902                }
11903                if (removed.size() > 0) {
11904                    for (int r=0; r<removed.size(); r++) {
11905                        PreferredActivity pa = removed.get(r);
11906                        Slog.w(TAG, "Removing dangling preferred activity: "
11907                                + pa.mPref.mComponent);
11908                        pir.removeFilter(pa);
11909                    }
11910                    mSettings.writePackageRestrictionsLPr(
11911                            mSettings.mPreferredActivities.keyAt(i));
11912                }
11913            }
11914        }
11915        sUserManager.systemReady();
11916    }
11917
11918    @Override
11919    public boolean isSafeMode() {
11920        return mSafeMode;
11921    }
11922
11923    @Override
11924    public boolean hasSystemUidErrors() {
11925        return mHasSystemUidErrors;
11926    }
11927
11928    static String arrayToString(int[] array) {
11929        StringBuffer buf = new StringBuffer(128);
11930        buf.append('[');
11931        if (array != null) {
11932            for (int i=0; i<array.length; i++) {
11933                if (i > 0) buf.append(", ");
11934                buf.append(array[i]);
11935            }
11936        }
11937        buf.append(']');
11938        return buf.toString();
11939    }
11940
11941    static class DumpState {
11942        public static final int DUMP_LIBS = 1 << 0;
11943
11944        public static final int DUMP_FEATURES = 1 << 1;
11945
11946        public static final int DUMP_RESOLVERS = 1 << 2;
11947
11948        public static final int DUMP_PERMISSIONS = 1 << 3;
11949
11950        public static final int DUMP_PACKAGES = 1 << 4;
11951
11952        public static final int DUMP_SHARED_USERS = 1 << 5;
11953
11954        public static final int DUMP_MESSAGES = 1 << 6;
11955
11956        public static final int DUMP_PROVIDERS = 1 << 7;
11957
11958        public static final int DUMP_VERIFIERS = 1 << 8;
11959
11960        public static final int DUMP_PREFERRED = 1 << 9;
11961
11962        public static final int DUMP_PREFERRED_XML = 1 << 10;
11963
11964        public static final int DUMP_KEYSETS = 1 << 11;
11965
11966        public static final int DUMP_VERSION = 1 << 12;
11967
11968        public static final int OPTION_SHOW_FILTERS = 1 << 0;
11969
11970        private int mTypes;
11971
11972        private int mOptions;
11973
11974        private boolean mTitlePrinted;
11975
11976        private SharedUserSetting mSharedUser;
11977
11978        public boolean isDumping(int type) {
11979            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
11980                return true;
11981            }
11982
11983            return (mTypes & type) != 0;
11984        }
11985
11986        public void setDump(int type) {
11987            mTypes |= type;
11988        }
11989
11990        public boolean isOptionEnabled(int option) {
11991            return (mOptions & option) != 0;
11992        }
11993
11994        public void setOptionEnabled(int option) {
11995            mOptions |= option;
11996        }
11997
11998        public boolean onTitlePrinted() {
11999            final boolean printed = mTitlePrinted;
12000            mTitlePrinted = true;
12001            return printed;
12002        }
12003
12004        public boolean getTitlePrinted() {
12005            return mTitlePrinted;
12006        }
12007
12008        public void setTitlePrinted(boolean enabled) {
12009            mTitlePrinted = enabled;
12010        }
12011
12012        public SharedUserSetting getSharedUser() {
12013            return mSharedUser;
12014        }
12015
12016        public void setSharedUser(SharedUserSetting user) {
12017            mSharedUser = user;
12018        }
12019    }
12020
12021    @Override
12022    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12023        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12024                != PackageManager.PERMISSION_GRANTED) {
12025            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12026                    + Binder.getCallingPid()
12027                    + ", uid=" + Binder.getCallingUid()
12028                    + " without permission "
12029                    + android.Manifest.permission.DUMP);
12030            return;
12031        }
12032
12033        DumpState dumpState = new DumpState();
12034        boolean fullPreferred = false;
12035        boolean checkin = false;
12036
12037        String packageName = null;
12038
12039        int opti = 0;
12040        while (opti < args.length) {
12041            String opt = args[opti];
12042            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12043                break;
12044            }
12045            opti++;
12046            if ("-a".equals(opt)) {
12047                // Right now we only know how to print all.
12048            } else if ("-h".equals(opt)) {
12049                pw.println("Package manager dump options:");
12050                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12051                pw.println("    --checkin: dump for a checkin");
12052                pw.println("    -f: print details of intent filters");
12053                pw.println("    -h: print this help");
12054                pw.println("  cmd may be one of:");
12055                pw.println("    l[ibraries]: list known shared libraries");
12056                pw.println("    f[ibraries]: list device features");
12057                pw.println("    k[eysets]: print known keysets");
12058                pw.println("    r[esolvers]: dump intent resolvers");
12059                pw.println("    perm[issions]: dump permissions");
12060                pw.println("    pref[erred]: print preferred package settings");
12061                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12062                pw.println("    prov[iders]: dump content providers");
12063                pw.println("    p[ackages]: dump installed packages");
12064                pw.println("    s[hared-users]: dump shared user IDs");
12065                pw.println("    m[essages]: print collected runtime messages");
12066                pw.println("    v[erifiers]: print package verifier info");
12067                pw.println("    version: print database version info");
12068                pw.println("    write: write current settings now");
12069                pw.println("    <package.name>: info about given package");
12070                return;
12071            } else if ("--checkin".equals(opt)) {
12072                checkin = true;
12073            } else if ("-f".equals(opt)) {
12074                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12075            } else {
12076                pw.println("Unknown argument: " + opt + "; use -h for help");
12077            }
12078        }
12079
12080        // Is the caller requesting to dump a particular piece of data?
12081        if (opti < args.length) {
12082            String cmd = args[opti];
12083            opti++;
12084            // Is this a package name?
12085            if ("android".equals(cmd) || cmd.contains(".")) {
12086                packageName = cmd;
12087                // When dumping a single package, we always dump all of its
12088                // filter information since the amount of data will be reasonable.
12089                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12090            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12091                dumpState.setDump(DumpState.DUMP_LIBS);
12092            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12093                dumpState.setDump(DumpState.DUMP_FEATURES);
12094            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12095                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12096            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12097                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12098            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12099                dumpState.setDump(DumpState.DUMP_PREFERRED);
12100            } else if ("preferred-xml".equals(cmd)) {
12101                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12102                if (opti < args.length && "--full".equals(args[opti])) {
12103                    fullPreferred = true;
12104                    opti++;
12105                }
12106            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12107                dumpState.setDump(DumpState.DUMP_PACKAGES);
12108            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12109                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12110            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12111                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12112            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12113                dumpState.setDump(DumpState.DUMP_MESSAGES);
12114            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12115                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12116            } else if ("version".equals(cmd)) {
12117                dumpState.setDump(DumpState.DUMP_VERSION);
12118            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12119                dumpState.setDump(DumpState.DUMP_KEYSETS);
12120            } else if ("write".equals(cmd)) {
12121                synchronized (mPackages) {
12122                    mSettings.writeLPr();
12123                    pw.println("Settings written.");
12124                    return;
12125                }
12126            }
12127        }
12128
12129        if (checkin) {
12130            pw.println("vers,1");
12131        }
12132
12133        // reader
12134        synchronized (mPackages) {
12135            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12136                if (!checkin) {
12137                    if (dumpState.onTitlePrinted())
12138                        pw.println();
12139                    pw.println("Database versions:");
12140                    pw.print("  SDK Version:");
12141                    pw.print(" internal=");
12142                    pw.print(mSettings.mInternalSdkPlatform);
12143                    pw.print(" external=");
12144                    pw.println(mSettings.mExternalSdkPlatform);
12145                    pw.print("  DB Version:");
12146                    pw.print(" internal=");
12147                    pw.print(mSettings.mInternalDatabaseVersion);
12148                    pw.print(" external=");
12149                    pw.println(mSettings.mExternalDatabaseVersion);
12150                }
12151            }
12152
12153            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12154                if (!checkin) {
12155                    if (dumpState.onTitlePrinted())
12156                        pw.println();
12157                    pw.println("Verifiers:");
12158                    pw.print("  Required: ");
12159                    pw.print(mRequiredVerifierPackage);
12160                    pw.print(" (uid=");
12161                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12162                    pw.println(")");
12163                } else if (mRequiredVerifierPackage != null) {
12164                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12165                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12166                }
12167            }
12168
12169            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12170                boolean printedHeader = false;
12171                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12172                while (it.hasNext()) {
12173                    String name = it.next();
12174                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12175                    if (!checkin) {
12176                        if (!printedHeader) {
12177                            if (dumpState.onTitlePrinted())
12178                                pw.println();
12179                            pw.println("Libraries:");
12180                            printedHeader = true;
12181                        }
12182                        pw.print("  ");
12183                    } else {
12184                        pw.print("lib,");
12185                    }
12186                    pw.print(name);
12187                    if (!checkin) {
12188                        pw.print(" -> ");
12189                    }
12190                    if (ent.path != null) {
12191                        if (!checkin) {
12192                            pw.print("(jar) ");
12193                            pw.print(ent.path);
12194                        } else {
12195                            pw.print(",jar,");
12196                            pw.print(ent.path);
12197                        }
12198                    } else {
12199                        if (!checkin) {
12200                            pw.print("(apk) ");
12201                            pw.print(ent.apk);
12202                        } else {
12203                            pw.print(",apk,");
12204                            pw.print(ent.apk);
12205                        }
12206                    }
12207                    pw.println();
12208                }
12209            }
12210
12211            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12212                if (dumpState.onTitlePrinted())
12213                    pw.println();
12214                if (!checkin) {
12215                    pw.println("Features:");
12216                }
12217                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12218                while (it.hasNext()) {
12219                    String name = it.next();
12220                    if (!checkin) {
12221                        pw.print("  ");
12222                    } else {
12223                        pw.print("feat,");
12224                    }
12225                    pw.println(name);
12226                }
12227            }
12228
12229            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12230                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12231                        : "Activity Resolver Table:", "  ", packageName,
12232                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12233                    dumpState.setTitlePrinted(true);
12234                }
12235                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12236                        : "Receiver Resolver Table:", "  ", packageName,
12237                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12238                    dumpState.setTitlePrinted(true);
12239                }
12240                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12241                        : "Service Resolver Table:", "  ", packageName,
12242                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12243                    dumpState.setTitlePrinted(true);
12244                }
12245                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12246                        : "Provider Resolver Table:", "  ", packageName,
12247                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12248                    dumpState.setTitlePrinted(true);
12249                }
12250            }
12251
12252            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12253                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12254                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12255                    int user = mSettings.mPreferredActivities.keyAt(i);
12256                    if (pir.dump(pw,
12257                            dumpState.getTitlePrinted()
12258                                ? "\nPreferred Activities User " + user + ":"
12259                                : "Preferred Activities User " + user + ":", "  ",
12260                            packageName, true)) {
12261                        dumpState.setTitlePrinted(true);
12262                    }
12263                }
12264            }
12265
12266            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12267                pw.flush();
12268                FileOutputStream fout = new FileOutputStream(fd);
12269                BufferedOutputStream str = new BufferedOutputStream(fout);
12270                XmlSerializer serializer = new FastXmlSerializer();
12271                try {
12272                    serializer.setOutput(str, "utf-8");
12273                    serializer.startDocument(null, true);
12274                    serializer.setFeature(
12275                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12276                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12277                    serializer.endDocument();
12278                    serializer.flush();
12279                } catch (IllegalArgumentException e) {
12280                    pw.println("Failed writing: " + e);
12281                } catch (IllegalStateException e) {
12282                    pw.println("Failed writing: " + e);
12283                } catch (IOException e) {
12284                    pw.println("Failed writing: " + e);
12285                }
12286            }
12287
12288            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12289                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12290            }
12291
12292            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12293                boolean printedSomething = false;
12294                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12295                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12296                        continue;
12297                    }
12298                    if (!printedSomething) {
12299                        if (dumpState.onTitlePrinted())
12300                            pw.println();
12301                        pw.println("Registered ContentProviders:");
12302                        printedSomething = true;
12303                    }
12304                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12305                    pw.print("    "); pw.println(p.toString());
12306                }
12307                printedSomething = false;
12308                for (Map.Entry<String, PackageParser.Provider> entry :
12309                        mProvidersByAuthority.entrySet()) {
12310                    PackageParser.Provider p = entry.getValue();
12311                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12312                        continue;
12313                    }
12314                    if (!printedSomething) {
12315                        if (dumpState.onTitlePrinted())
12316                            pw.println();
12317                        pw.println("ContentProvider Authorities:");
12318                        printedSomething = true;
12319                    }
12320                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12321                    pw.print("    "); pw.println(p.toString());
12322                    if (p.info != null && p.info.applicationInfo != null) {
12323                        final String appInfo = p.info.applicationInfo.toString();
12324                        pw.print("      applicationInfo="); pw.println(appInfo);
12325                    }
12326                }
12327            }
12328
12329            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12330                mSettings.mKeySetManagerService.dump(pw, packageName, dumpState);
12331            }
12332
12333            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12334                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12335            }
12336
12337            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12338                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12339            }
12340
12341            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12342                if (dumpState.onTitlePrinted())
12343                    pw.println();
12344                mSettings.dumpReadMessagesLPr(pw, dumpState);
12345
12346                pw.println();
12347                pw.println("Package warning messages:");
12348                final File fname = getSettingsProblemFile();
12349                FileInputStream in = null;
12350                try {
12351                    in = new FileInputStream(fname);
12352                    final int avail = in.available();
12353                    final byte[] data = new byte[avail];
12354                    in.read(data);
12355                    pw.print(new String(data));
12356                } catch (FileNotFoundException e) {
12357                } catch (IOException e) {
12358                } finally {
12359                    if (in != null) {
12360                        try {
12361                            in.close();
12362                        } catch (IOException e) {
12363                        }
12364                    }
12365                }
12366            }
12367        }
12368    }
12369
12370    // ------- apps on sdcard specific code -------
12371    static final boolean DEBUG_SD_INSTALL = false;
12372
12373    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12374
12375    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12376
12377    private boolean mMediaMounted = false;
12378
12379    private String getEncryptKey() {
12380        try {
12381            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12382                    SD_ENCRYPTION_KEYSTORE_NAME);
12383            if (sdEncKey == null) {
12384                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12385                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12386                if (sdEncKey == null) {
12387                    Slog.e(TAG, "Failed to create encryption keys");
12388                    return null;
12389                }
12390            }
12391            return sdEncKey;
12392        } catch (NoSuchAlgorithmException nsae) {
12393            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12394            return null;
12395        } catch (IOException ioe) {
12396            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12397            return null;
12398        }
12399
12400    }
12401
12402    /* package */static String getTempContainerId() {
12403        int tmpIdx = 1;
12404        String list[] = PackageHelper.getSecureContainerList();
12405        if (list != null) {
12406            for (final String name : list) {
12407                // Ignore null and non-temporary container entries
12408                if (name == null || !name.startsWith(mTempContainerPrefix)) {
12409                    continue;
12410                }
12411
12412                String subStr = name.substring(mTempContainerPrefix.length());
12413                try {
12414                    int cid = Integer.parseInt(subStr);
12415                    if (cid >= tmpIdx) {
12416                        tmpIdx = cid + 1;
12417                    }
12418                } catch (NumberFormatException e) {
12419                }
12420            }
12421        }
12422        return mTempContainerPrefix + tmpIdx;
12423    }
12424
12425    /*
12426     * Update media status on PackageManager.
12427     */
12428    @Override
12429    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12430        int callingUid = Binder.getCallingUid();
12431        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12432            throw new SecurityException("Media status can only be updated by the system");
12433        }
12434        // reader; this apparently protects mMediaMounted, but should probably
12435        // be a different lock in that case.
12436        synchronized (mPackages) {
12437            Log.i(TAG, "Updating external media status from "
12438                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12439                    + (mediaStatus ? "mounted" : "unmounted"));
12440            if (DEBUG_SD_INSTALL)
12441                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12442                        + ", mMediaMounted=" + mMediaMounted);
12443            if (mediaStatus == mMediaMounted) {
12444                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12445                        : 0, -1);
12446                mHandler.sendMessage(msg);
12447                return;
12448            }
12449            mMediaMounted = mediaStatus;
12450        }
12451        // Queue up an async operation since the package installation may take a
12452        // little while.
12453        mHandler.post(new Runnable() {
12454            public void run() {
12455                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12456            }
12457        });
12458    }
12459
12460    /**
12461     * Called by MountService when the initial ASECs to scan are available.
12462     * Should block until all the ASEC containers are finished being scanned.
12463     */
12464    public void scanAvailableAsecs() {
12465        updateExternalMediaStatusInner(true, false, false);
12466        if (mShouldRestoreconData) {
12467            SELinuxMMAC.setRestoreconDone();
12468            mShouldRestoreconData = false;
12469        }
12470    }
12471
12472    /*
12473     * Collect information of applications on external media, map them against
12474     * existing containers and update information based on current mount status.
12475     * Please note that we always have to report status if reportStatus has been
12476     * set to true especially when unloading packages.
12477     */
12478    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12479            boolean externalStorage) {
12480        // Collection of uids
12481        int uidArr[] = null;
12482        // Collection of stale containers
12483        HashSet<String> removeCids = new HashSet<String>();
12484        // Collection of packages on external media with valid containers.
12485        HashMap<AsecInstallArgs, String> processCids = new HashMap<AsecInstallArgs, String>();
12486        // Get list of secure containers.
12487        final String list[] = PackageHelper.getSecureContainerList();
12488        if (list == null || list.length == 0) {
12489            Log.i(TAG, "No secure containers on sdcard");
12490        } else {
12491            // Process list of secure containers and categorize them
12492            // as active or stale based on their package internal state.
12493            int uidList[] = new int[list.length];
12494            int num = 0;
12495            // reader
12496            synchronized (mPackages) {
12497                for (String cid : list) {
12498                    if (DEBUG_SD_INSTALL)
12499                        Log.i(TAG, "Processing container " + cid);
12500                    String pkgName = getAsecPackageName(cid);
12501                    if (pkgName == null) {
12502                        if (DEBUG_SD_INSTALL)
12503                            Log.i(TAG, "Container : " + cid + " stale");
12504                        removeCids.add(cid);
12505                        continue;
12506                    }
12507                    if (DEBUG_SD_INSTALL)
12508                        Log.i(TAG, "Looking for pkg : " + pkgName);
12509
12510                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12511                    if (ps == null) {
12512                        Log.i(TAG, "Deleting container with no matching settings " + cid);
12513                        removeCids.add(cid);
12514                        continue;
12515                    }
12516
12517                    /*
12518                     * Skip packages that are not external if we're unmounting
12519                     * external storage.
12520                     */
12521                    if (externalStorage && !isMounted && !isExternal(ps)) {
12522                        continue;
12523                    }
12524
12525                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12526                            getAppInstructionSetFromSettings(ps),
12527                            isForwardLocked(ps));
12528                    // The package status is changed only if the code path
12529                    // matches between settings and the container id.
12530                    if (ps.codePathString != null && ps.codePathString.equals(args.getCodePath())) {
12531                        if (DEBUG_SD_INSTALL) {
12532                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12533                                    + " at code path: " + ps.codePathString);
12534                        }
12535
12536                        // We do have a valid package installed on sdcard
12537                        processCids.put(args, ps.codePathString);
12538                        final int uid = ps.appId;
12539                        if (uid != -1) {
12540                            uidList[num++] = uid;
12541                        }
12542                    } else {
12543                        Log.i(TAG, "Deleting stale container for " + cid);
12544                        removeCids.add(cid);
12545                    }
12546                }
12547            }
12548
12549            if (num > 0) {
12550                // Sort uid list
12551                Arrays.sort(uidList, 0, num);
12552                // Throw away duplicates
12553                uidArr = new int[num];
12554                uidArr[0] = uidList[0];
12555                int di = 0;
12556                for (int i = 1; i < num; i++) {
12557                    if (uidList[i - 1] != uidList[i]) {
12558                        uidArr[di++] = uidList[i];
12559                    }
12560                }
12561            }
12562        }
12563        // Process packages with valid entries.
12564        if (isMounted) {
12565            if (DEBUG_SD_INSTALL)
12566                Log.i(TAG, "Loading packages");
12567            loadMediaPackages(processCids, uidArr, removeCids);
12568            startCleaningPackages();
12569        } else {
12570            if (DEBUG_SD_INSTALL)
12571                Log.i(TAG, "Unloading packages");
12572            unloadMediaPackages(processCids, uidArr, reportStatus);
12573        }
12574    }
12575
12576   private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12577           ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12578        int size = pkgList.size();
12579        if (size > 0) {
12580            // Send broadcasts here
12581            Bundle extras = new Bundle();
12582            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12583                    .toArray(new String[size]));
12584            if (uidArr != null) {
12585                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12586            }
12587            if (replacing) {
12588                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12589            }
12590            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12591                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12592            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12593        }
12594    }
12595
12596   /*
12597     * Look at potentially valid container ids from processCids If package
12598     * information doesn't match the one on record or package scanning fails,
12599     * the cid is added to list of removeCids. We currently don't delete stale
12600     * containers.
12601     */
12602   private void loadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12603            HashSet<String> removeCids) {
12604        ArrayList<String> pkgList = new ArrayList<String>();
12605        Set<AsecInstallArgs> keys = processCids.keySet();
12606        boolean doGc = false;
12607        for (AsecInstallArgs args : keys) {
12608            String codePath = processCids.get(args);
12609            if (DEBUG_SD_INSTALL)
12610                Log.i(TAG, "Loading container : " + args.cid);
12611            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12612            try {
12613                // Make sure there are no container errors first.
12614                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12615                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12616                            + " when installing from sdcard");
12617                    continue;
12618                }
12619                // Check code path here.
12620                if (codePath == null || !codePath.equals(args.getCodePath())) {
12621                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12622                            + " does not match one in settings " + codePath);
12623                    continue;
12624                }
12625                // Parse package
12626                int parseFlags = mDefParseFlags;
12627                if (args.isExternal()) {
12628                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12629                }
12630                if (args.isFwdLocked()) {
12631                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12632                }
12633
12634                doGc = true;
12635                synchronized (mInstallLock) {
12636                    final PackageParser.Package pkg = scanPackageLI(new File(codePath), parseFlags,
12637                            0, 0, null, null);
12638                    // Scan the package
12639                    if (pkg != null) {
12640                        /*
12641                         * TODO why is the lock being held? doPostInstall is
12642                         * called in other places without the lock. This needs
12643                         * to be straightened out.
12644                         */
12645                        // writer
12646                        synchronized (mPackages) {
12647                            retCode = PackageManager.INSTALL_SUCCEEDED;
12648                            pkgList.add(pkg.packageName);
12649                            // Post process args
12650                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12651                                    pkg.applicationInfo.uid);
12652                        }
12653                    } else {
12654                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12655                    }
12656                }
12657
12658            } finally {
12659                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12660                    // Don't destroy container here. Wait till gc clears things
12661                    // up.
12662                    removeCids.add(args.cid);
12663                }
12664            }
12665        }
12666        // writer
12667        synchronized (mPackages) {
12668            // If the platform SDK has changed since the last time we booted,
12669            // we need to re-grant app permission to catch any new ones that
12670            // appear. This is really a hack, and means that apps can in some
12671            // cases get permissions that the user didn't initially explicitly
12672            // allow... it would be nice to have some better way to handle
12673            // this situation.
12674            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12675            if (regrantPermissions)
12676                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12677                        + mSdkVersion + "; regranting permissions for external storage");
12678            mSettings.mExternalSdkPlatform = mSdkVersion;
12679
12680            // Make sure group IDs have been assigned, and any permission
12681            // changes in other apps are accounted for
12682            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12683                    | (regrantPermissions
12684                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12685                            : 0));
12686
12687            mSettings.updateExternalDatabaseVersion();
12688
12689            // can downgrade to reader
12690            // Persist settings
12691            mSettings.writeLPr();
12692        }
12693        // Send a broadcast to let everyone know we are done processing
12694        if (pkgList.size() > 0) {
12695            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12696        }
12697        // Force gc to avoid any stale parser references that we might have.
12698        if (doGc) {
12699            Runtime.getRuntime().gc();
12700        }
12701        // List stale containers and destroy stale temporary containers.
12702        if (removeCids != null) {
12703            for (String cid : removeCids) {
12704                if (cid.startsWith(mTempContainerPrefix)) {
12705                    Log.i(TAG, "Destroying stale temporary container " + cid);
12706                    PackageHelper.destroySdDir(cid);
12707                } else {
12708                    Log.w(TAG, "Container " + cid + " is stale");
12709               }
12710           }
12711        }
12712    }
12713
12714   /*
12715     * Utility method to unload a list of specified containers
12716     */
12717    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12718        // Just unmount all valid containers.
12719        for (AsecInstallArgs arg : cidArgs) {
12720            synchronized (mInstallLock) {
12721                arg.doPostDeleteLI(false);
12722           }
12723       }
12724   }
12725
12726    /*
12727     * Unload packages mounted on external media. This involves deleting package
12728     * data from internal structures, sending broadcasts about diabled packages,
12729     * gc'ing to free up references, unmounting all secure containers
12730     * corresponding to packages on external media, and posting a
12731     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12732     * that we always have to post this message if status has been requested no
12733     * matter what.
12734     */
12735    private void unloadMediaPackages(HashMap<AsecInstallArgs, String> processCids, int uidArr[],
12736            final boolean reportStatus) {
12737        if (DEBUG_SD_INSTALL)
12738            Log.i(TAG, "unloading media packages");
12739        ArrayList<String> pkgList = new ArrayList<String>();
12740        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12741        final Set<AsecInstallArgs> keys = processCids.keySet();
12742        for (AsecInstallArgs args : keys) {
12743            String pkgName = args.getPackageName();
12744            if (DEBUG_SD_INSTALL)
12745                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12746            // Delete package internally
12747            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12748            synchronized (mInstallLock) {
12749                boolean res = deletePackageLI(pkgName, null, false, null, null,
12750                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12751                if (res) {
12752                    pkgList.add(pkgName);
12753                } else {
12754                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12755                    failedList.add(args);
12756                }
12757            }
12758        }
12759
12760        // reader
12761        synchronized (mPackages) {
12762            // We didn't update the settings after removing each package;
12763            // write them now for all packages.
12764            mSettings.writeLPr();
12765        }
12766
12767        // We have to absolutely send UPDATED_MEDIA_STATUS only
12768        // after confirming that all the receivers processed the ordered
12769        // broadcast when packages get disabled, force a gc to clean things up.
12770        // and unload all the containers.
12771        if (pkgList.size() > 0) {
12772            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12773                    new IIntentReceiver.Stub() {
12774                public void performReceive(Intent intent, int resultCode, String data,
12775                        Bundle extras, boolean ordered, boolean sticky,
12776                        int sendingUser) throws RemoteException {
12777                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12778                            reportStatus ? 1 : 0, 1, keys);
12779                    mHandler.sendMessage(msg);
12780                }
12781            });
12782        } else {
12783            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12784                    keys);
12785            mHandler.sendMessage(msg);
12786        }
12787    }
12788
12789    /** Binder call */
12790    @Override
12791    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12792            final int flags) {
12793        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12794        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12795        int returnCode = PackageManager.MOVE_SUCCEEDED;
12796        int currFlags = 0;
12797        int newFlags = 0;
12798        // reader
12799        synchronized (mPackages) {
12800            PackageParser.Package pkg = mPackages.get(packageName);
12801            if (pkg == null) {
12802                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12803            } else {
12804                // Disable moving fwd locked apps and system packages
12805                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12806                    Slog.w(TAG, "Cannot move system application");
12807                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12808                } else if (pkg.mOperationPending) {
12809                    Slog.w(TAG, "Attempt to move package which has pending operations");
12810                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12811                } else {
12812                    // Find install location first
12813                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12814                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12815                        Slog.w(TAG, "Ambigous flags specified for move location.");
12816                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12817                    } else {
12818                        newFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0 ? PackageManager.INSTALL_EXTERNAL
12819                                : PackageManager.INSTALL_INTERNAL;
12820                        currFlags = isExternal(pkg) ? PackageManager.INSTALL_EXTERNAL
12821                                : PackageManager.INSTALL_INTERNAL;
12822
12823                        if (newFlags == currFlags) {
12824                            Slog.w(TAG, "No move required. Trying to move to same location");
12825                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12826                        } else {
12827                            if (isForwardLocked(pkg)) {
12828                                currFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12829                                newFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12830                            }
12831                        }
12832                    }
12833                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12834                        pkg.mOperationPending = true;
12835                    }
12836                }
12837            }
12838
12839            /*
12840             * TODO this next block probably shouldn't be inside the lock. We
12841             * can't guarantee these won't change after this is fired off
12842             * anyway.
12843             */
12844            if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12845                processPendingMove(new MoveParams(null, observer, 0, packageName, null,
12846                        null, -1, user),
12847                        returnCode);
12848            } else {
12849                Message msg = mHandler.obtainMessage(INIT_COPY);
12850                final String instructionSet = getAppInstructionSet(pkg.applicationInfo);
12851                InstallArgs srcArgs = createInstallArgsForExisting(currFlags,
12852                        pkg.applicationInfo.sourceDir, pkg.applicationInfo.publicSourceDir,
12853                        pkg.applicationInfo.nativeLibraryDir, instructionSet);
12854                MoveParams mp = new MoveParams(srcArgs, observer, newFlags, packageName,
12855                        pkg.applicationInfo.dataDir, instructionSet, pkg.applicationInfo.uid, user);
12856                msg.obj = mp;
12857                mHandler.sendMessage(msg);
12858            }
12859        }
12860    }
12861
12862    private void processPendingMove(final MoveParams mp, final int currentStatus) {
12863        // Queue up an async operation since the package deletion may take a
12864        // little while.
12865        mHandler.post(new Runnable() {
12866            public void run() {
12867                // TODO fix this; this does nothing.
12868                mHandler.removeCallbacks(this);
12869                int returnCode = currentStatus;
12870                if (currentStatus == PackageManager.MOVE_SUCCEEDED) {
12871                    int uidArr[] = null;
12872                    ArrayList<String> pkgList = null;
12873                    synchronized (mPackages) {
12874                        PackageParser.Package pkg = mPackages.get(mp.packageName);
12875                        if (pkg == null) {
12876                            Slog.w(TAG, " Package " + mp.packageName
12877                                    + " doesn't exist. Aborting move");
12878                            returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12879                        } else if (!mp.srcArgs.getCodePath().equals(pkg.applicationInfo.sourceDir)) {
12880                            Slog.w(TAG, "Package " + mp.packageName + " code path changed from "
12881                                    + mp.srcArgs.getCodePath() + " to "
12882                                    + pkg.applicationInfo.sourceDir
12883                                    + " Aborting move and returning error");
12884                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12885                        } else {
12886                            uidArr = new int[] {
12887                                pkg.applicationInfo.uid
12888                            };
12889                            pkgList = new ArrayList<String>();
12890                            pkgList.add(mp.packageName);
12891                        }
12892                    }
12893                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12894                        // Send resources unavailable broadcast
12895                        sendResourcesChangedBroadcast(false, true, pkgList, uidArr, null);
12896                        // Update package code and resource paths
12897                        synchronized (mInstallLock) {
12898                            synchronized (mPackages) {
12899                                PackageParser.Package pkg = mPackages.get(mp.packageName);
12900                                // Recheck for package again.
12901                                if (pkg == null) {
12902                                    Slog.w(TAG, " Package " + mp.packageName
12903                                            + " doesn't exist. Aborting move");
12904                                    returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12905                                } else if (!mp.srcArgs.getCodePath().equals(
12906                                        pkg.applicationInfo.sourceDir)) {
12907                                    Slog.w(TAG, "Package " + mp.packageName
12908                                            + " code path changed from " + mp.srcArgs.getCodePath()
12909                                            + " to " + pkg.applicationInfo.sourceDir
12910                                            + " Aborting move and returning error");
12911                                    returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12912                                } else {
12913                                    final String oldCodePath = pkg.codePath;
12914                                    final String newCodePath = mp.targetArgs.getCodePath();
12915                                    final String newResPath = mp.targetArgs.getResourcePath();
12916                                    final String newNativePath = mp.targetArgs
12917                                            .getNativeLibraryPath();
12918
12919                                    final File newNativeDir = new File(newNativePath);
12920
12921                                    if (!isForwardLocked(pkg) && !isExternal(pkg)) {
12922                                        NativeLibraryHelper.Handle handle = null;
12923                                        try {
12924                                            handle = NativeLibraryHelper.Handle.create(
12925                                                    new File(newCodePath));
12926                                            final int abi = NativeLibraryHelper.findSupportedAbi(
12927                                                    handle, Build.SUPPORTED_ABIS);
12928                                            if (abi >= 0) {
12929                                                NativeLibraryHelper.copyNativeBinariesIfNeededLI(
12930                                                        handle, newNativeDir, Build.SUPPORTED_ABIS[abi]);
12931                                            }
12932                                        } catch (IOException ioe) {
12933                                            Slog.w(TAG, "Unable to extract native libs for package :"
12934                                                    + mp.packageName, ioe);
12935                                            returnCode = PackageManager.MOVE_FAILED_INTERNAL_ERROR;
12936                                        } finally {
12937                                            IoUtils.closeQuietly(handle);
12938                                        }
12939                                    }
12940                                    final int[] users = sUserManager.getUserIds();
12941                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12942                                        for (int user : users) {
12943                                            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName,
12944                                                    newNativePath, user) < 0) {
12945                                                returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12946                                            }
12947                                        }
12948                                    }
12949
12950                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12951                                        pkg.codePath = newCodePath;
12952                                        pkg.baseCodePath = newCodePath;
12953                                        // Move dex files around
12954                                        if (moveDexFilesLI(oldCodePath, pkg) != PackageManager.INSTALL_SUCCEEDED) {
12955                                            // Moving of dex files failed. Set
12956                                            // error code and abort move.
12957                                            pkg.codePath = oldCodePath;
12958                                            pkg.baseCodePath = oldCodePath;
12959                                            returnCode = PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE;
12960                                        }
12961                                    }
12962
12963                                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12964                                        pkg.applicationInfo.sourceDir = newCodePath;
12965                                        pkg.applicationInfo.publicSourceDir = newResPath;
12966                                        pkg.applicationInfo.nativeLibraryDir = newNativePath;
12967                                        PackageSetting ps = (PackageSetting) pkg.mExtras;
12968                                        ps.codePath = new File(pkg.applicationInfo.sourceDir);
12969                                        ps.codePathString = ps.codePath.getPath();
12970                                        ps.resourcePath = new File(
12971                                                pkg.applicationInfo.publicSourceDir);
12972                                        ps.resourcePathString = ps.resourcePath.getPath();
12973                                        ps.nativeLibraryPathString = newNativePath;
12974                                        // Set the application info flag
12975                                        // correctly.
12976                                        if ((mp.flags & PackageManager.INSTALL_EXTERNAL) != 0) {
12977                                            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12978                                        } else {
12979                                            pkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_EXTERNAL_STORAGE;
12980                                        }
12981                                        ps.setFlags(pkg.applicationInfo.flags);
12982                                        mAppDirs.remove(oldCodePath);
12983                                        mAppDirs.put(newCodePath, pkg);
12984                                        // Persist settings
12985                                        mSettings.writeLPr();
12986                                    }
12987                                }
12988                            }
12989                        }
12990                        // Send resources available broadcast
12991                        sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12992                    }
12993                }
12994                if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12995                    // Clean up failed installation
12996                    if (mp.targetArgs != null) {
12997                        mp.targetArgs.doPostInstall(PackageManager.INSTALL_FAILED_INTERNAL_ERROR,
12998                                -1);
12999                    }
13000                } else {
13001                    // Force a gc to clear things up.
13002                    Runtime.getRuntime().gc();
13003                    // Delete older code
13004                    synchronized (mInstallLock) {
13005                        mp.srcArgs.doPostDeleteLI(true);
13006                    }
13007                }
13008
13009                // Allow more operations on this file if we didn't fail because
13010                // an operation was already pending for this package.
13011                if (returnCode != PackageManager.MOVE_FAILED_OPERATION_PENDING) {
13012                    synchronized (mPackages) {
13013                        PackageParser.Package pkg = mPackages.get(mp.packageName);
13014                        if (pkg != null) {
13015                            pkg.mOperationPending = false;
13016                       }
13017                   }
13018                }
13019
13020                IPackageMoveObserver observer = mp.observer;
13021                if (observer != null) {
13022                    try {
13023                        observer.packageMoved(mp.packageName, returnCode);
13024                    } catch (RemoteException e) {
13025                        Log.i(TAG, "Observer no longer exists.");
13026                    }
13027                }
13028            }
13029        });
13030    }
13031
13032    @Override
13033    public boolean setInstallLocation(int loc) {
13034        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13035                null);
13036        if (getInstallLocation() == loc) {
13037            return true;
13038        }
13039        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13040                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13041            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13042                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13043            return true;
13044        }
13045        return false;
13046   }
13047
13048    @Override
13049    public int getInstallLocation() {
13050        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13051                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13052                PackageHelper.APP_INSTALL_AUTO);
13053    }
13054
13055    /** Called by UserManagerService */
13056    void cleanUpUserLILPw(int userHandle) {
13057        mDirtyUsers.remove(userHandle);
13058        mSettings.removeUserLPr(userHandle);
13059        mPendingBroadcasts.remove(userHandle);
13060        if (mInstaller != null) {
13061            // Technically, we shouldn't be doing this with the package lock
13062            // held.  However, this is very rare, and there is already so much
13063            // other disk I/O going on, that we'll let it slide for now.
13064            mInstaller.removeUserDataDirs(userHandle);
13065        }
13066        mUserNeedsBadging.delete(userHandle);
13067    }
13068
13069    /** Called by UserManagerService */
13070    void createNewUserLILPw(int userHandle, File path) {
13071        if (mInstaller != null) {
13072            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13073        }
13074    }
13075
13076    @Override
13077    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13078        mContext.enforceCallingOrSelfPermission(
13079                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13080                "Only package verification agents can read the verifier device identity");
13081
13082        synchronized (mPackages) {
13083            return mSettings.getVerifierDeviceIdentityLPw();
13084        }
13085    }
13086
13087    @Override
13088    public void setPermissionEnforced(String permission, boolean enforced) {
13089        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13090        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13091            synchronized (mPackages) {
13092                if (mSettings.mReadExternalStorageEnforced == null
13093                        || mSettings.mReadExternalStorageEnforced != enforced) {
13094                    mSettings.mReadExternalStorageEnforced = enforced;
13095                    mSettings.writeLPr();
13096                }
13097            }
13098            // kill any non-foreground processes so we restart them and
13099            // grant/revoke the GID.
13100            final IActivityManager am = ActivityManagerNative.getDefault();
13101            if (am != null) {
13102                final long token = Binder.clearCallingIdentity();
13103                try {
13104                    am.killProcessesBelowForeground("setPermissionEnforcement");
13105                } catch (RemoteException e) {
13106                } finally {
13107                    Binder.restoreCallingIdentity(token);
13108                }
13109            }
13110        } else {
13111            throw new IllegalArgumentException("No selective enforcement for " + permission);
13112        }
13113    }
13114
13115    @Override
13116    @Deprecated
13117    public boolean isPermissionEnforced(String permission) {
13118        return true;
13119    }
13120
13121    @Override
13122    public boolean isStorageLow() {
13123        final long token = Binder.clearCallingIdentity();
13124        try {
13125            final DeviceStorageMonitorInternal
13126                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13127            if (dsm != null) {
13128                return dsm.isMemoryLow();
13129            } else {
13130                return false;
13131            }
13132        } finally {
13133            Binder.restoreCallingIdentity(token);
13134        }
13135    }
13136
13137    @Override
13138    public IPackageInstaller getPackageInstaller() {
13139        return mInstallerService;
13140    }
13141
13142    private boolean userNeedsBadging(int userId) {
13143        int index = mUserNeedsBadging.indexOfKey(userId);
13144        if (index < 0) {
13145            final UserInfo userInfo;
13146            final long token = Binder.clearCallingIdentity();
13147            try {
13148                userInfo = sUserManager.getUserInfo(userId);
13149            } finally {
13150                Binder.restoreCallingIdentity(token);
13151            }
13152            final boolean b;
13153            if (userInfo != null && userInfo.isManagedProfile()) {
13154                b = true;
13155            } else {
13156                b = false;
13157            }
13158            mUserNeedsBadging.put(userId, b);
13159            return b;
13160        }
13161        return mUserNeedsBadging.valueAt(index);
13162    }
13163}
13164