PackageManagerService.java revision 2d7576b082b84068fb9d68419b710b9bec49139b
1/*
2 * Copyright (C) 2006 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.pm;
18
19import static android.Manifest.permission.GRANT_REVOKE_PERMISSIONS;
20import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
21import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT;
22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED;
23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED;
24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER;
25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
26import static android.content.pm.PackageManager.INSTALL_EXTERNAL;
27import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
28import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER;
29import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT;
30import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE;
31import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION;
32import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
33import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
34import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK;
35import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
36import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY;
37import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED;
38import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE;
39import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE;
40import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY;
41import static android.content.pm.PackageManager.INSTALL_FAILED_UID_CHANGED;
42import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE;
43import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED;
44import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK;
45import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES;
46import static android.content.pm.PackageParser.isApkFile;
47import static android.os.Process.PACKAGE_INFO_GID;
48import static android.os.Process.SYSTEM_UID;
49import static android.system.OsConstants.O_CREAT;
50import static android.system.OsConstants.O_RDWR;
51import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE;
52import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_USER_OWNER;
53import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME;
54import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME;
55import static com.android.internal.util.ArrayUtils.appendInt;
56import static com.android.internal.util.ArrayUtils.removeInt;
57
58import android.util.ArrayMap;
59
60import com.android.internal.R;
61import com.android.internal.app.IMediaContainerService;
62import com.android.internal.app.ResolverActivity;
63import com.android.internal.content.NativeLibraryHelper;
64import com.android.internal.content.PackageHelper;
65import com.android.internal.os.IParcelFileDescriptorFactory;
66import com.android.internal.util.ArrayUtils;
67import com.android.internal.util.FastPrintWriter;
68import com.android.internal.util.FastXmlSerializer;
69import com.android.internal.util.IndentingPrintWriter;
70import com.android.server.EventLogTags;
71import com.android.server.IntentResolver;
72import com.android.server.LocalServices;
73import com.android.server.ServiceThread;
74import com.android.server.SystemConfig;
75import com.android.server.Watchdog;
76import com.android.server.pm.Settings.DatabaseVersion;
77import com.android.server.storage.DeviceStorageMonitorInternal;
78
79import org.xmlpull.v1.XmlSerializer;
80
81import android.app.ActivityManager;
82import android.app.ActivityManagerNative;
83import android.app.IActivityManager;
84import android.app.admin.IDevicePolicyManager;
85import android.app.backup.IBackupManager;
86import android.content.BroadcastReceiver;
87import android.content.ComponentName;
88import android.content.Context;
89import android.content.IIntentReceiver;
90import android.content.Intent;
91import android.content.IntentFilter;
92import android.content.IntentSender;
93import android.content.IntentSender.SendIntentException;
94import android.content.ServiceConnection;
95import android.content.pm.ActivityInfo;
96import android.content.pm.ApplicationInfo;
97import android.content.pm.FeatureInfo;
98import android.content.pm.IPackageDataObserver;
99import android.content.pm.IPackageDeleteObserver;
100import android.content.pm.IPackageDeleteObserver2;
101import android.content.pm.IPackageInstallObserver2;
102import android.content.pm.IPackageInstaller;
103import android.content.pm.IPackageManager;
104import android.content.pm.IPackageMoveObserver;
105import android.content.pm.IPackageStatsObserver;
106import android.content.pm.InstrumentationInfo;
107import android.content.pm.KeySet;
108import android.content.pm.ManifestDigest;
109import android.content.pm.PackageCleanItem;
110import android.content.pm.PackageInfo;
111import android.content.pm.PackageInfoLite;
112import android.content.pm.PackageInstaller;
113import android.content.pm.PackageManager;
114import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
115import android.content.pm.PackageParser.ActivityIntentInfo;
116import android.content.pm.PackageParser.PackageLite;
117import android.content.pm.PackageParser.PackageParserException;
118import android.content.pm.PackageParser;
119import android.content.pm.PackageStats;
120import android.content.pm.PackageUserState;
121import android.content.pm.ParceledListSlice;
122import android.content.pm.PermissionGroupInfo;
123import android.content.pm.PermissionInfo;
124import android.content.pm.ProviderInfo;
125import android.content.pm.ResolveInfo;
126import android.content.pm.ServiceInfo;
127import android.content.pm.Signature;
128import android.content.pm.UserInfo;
129import android.content.pm.VerificationParams;
130import android.content.pm.VerifierDeviceIdentity;
131import android.content.pm.VerifierInfo;
132import android.content.res.Resources;
133import android.hardware.display.DisplayManager;
134import android.net.Uri;
135import android.os.Binder;
136import android.os.Build;
137import android.os.Bundle;
138import android.os.Environment;
139import android.os.Environment.UserEnvironment;
140import android.os.storage.StorageManager;
141import android.os.Debug;
142import android.os.FileUtils;
143import android.os.Handler;
144import android.os.IBinder;
145import android.os.Looper;
146import android.os.Message;
147import android.os.Parcel;
148import android.os.ParcelFileDescriptor;
149import android.os.Process;
150import android.os.RemoteException;
151import android.os.SELinux;
152import android.os.ServiceManager;
153import android.os.SystemClock;
154import android.os.SystemProperties;
155import android.os.UserHandle;
156import android.os.UserManager;
157import android.security.KeyStore;
158import android.security.SystemKeyStore;
159import android.system.ErrnoException;
160import android.system.Os;
161import android.system.StructStat;
162import android.text.TextUtils;
163import android.util.ArraySet;
164import android.util.AtomicFile;
165import android.util.DisplayMetrics;
166import android.util.EventLog;
167import android.util.ExceptionUtils;
168import android.util.Log;
169import android.util.LogPrinter;
170import android.util.PrintStreamPrinter;
171import android.util.Slog;
172import android.util.SparseArray;
173import android.util.SparseBooleanArray;
174import android.view.Display;
175
176import java.io.BufferedInputStream;
177import java.io.BufferedOutputStream;
178import java.io.File;
179import java.io.FileDescriptor;
180import java.io.FileInputStream;
181import java.io.FileNotFoundException;
182import java.io.FileOutputStream;
183import java.io.FilenameFilter;
184import java.io.IOException;
185import java.io.InputStream;
186import java.io.PrintWriter;
187import java.nio.charset.StandardCharsets;
188import java.security.NoSuchAlgorithmException;
189import java.security.PublicKey;
190import java.security.cert.CertificateEncodingException;
191import java.security.cert.CertificateException;
192import java.text.SimpleDateFormat;
193import java.util.ArrayList;
194import java.util.Arrays;
195import java.util.Collection;
196import java.util.Collections;
197import java.util.Comparator;
198import java.util.Date;
199import java.util.HashMap;
200import java.util.HashSet;
201import java.util.Iterator;
202import java.util.List;
203import java.util.Map;
204import java.util.Objects;
205import java.util.Set;
206import java.util.concurrent.atomic.AtomicBoolean;
207import java.util.concurrent.atomic.AtomicLong;
208
209import dalvik.system.DexFile;
210import dalvik.system.StaleDexCacheError;
211import dalvik.system.VMRuntime;
212
213import libcore.io.IoUtils;
214import libcore.util.EmptyArray;
215
216/**
217 * Keep track of all those .apks everywhere.
218 *
219 * This is very central to the platform's security; please run the unit
220 * tests whenever making modifications here:
221 *
222mmm frameworks/base/tests/AndroidTests
223adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
224adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
225 *
226 * {@hide}
227 */
228public class PackageManagerService extends IPackageManager.Stub {
229    static final String TAG = "PackageManager";
230    static final boolean DEBUG_SETTINGS = false;
231    static final boolean DEBUG_PREFERRED = false;
232    static final boolean DEBUG_UPGRADE = false;
233    private static final boolean DEBUG_INSTALL = false;
234    private static final boolean DEBUG_REMOVE = false;
235    private static final boolean DEBUG_BROADCASTS = false;
236    private static final boolean DEBUG_SHOW_INFO = false;
237    private static final boolean DEBUG_PACKAGE_INFO = false;
238    private static final boolean DEBUG_INTENT_MATCHING = false;
239    private static final boolean DEBUG_PACKAGE_SCANNING = false;
240    private static final boolean DEBUG_VERIFY = false;
241    private static final boolean DEBUG_DEXOPT = false;
242    private static final boolean DEBUG_ABI_SELECTION = false;
243
244    private static final int RADIO_UID = Process.PHONE_UID;
245    private static final int LOG_UID = Process.LOG_UID;
246    private static final int NFC_UID = Process.NFC_UID;
247    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
248    private static final int SHELL_UID = Process.SHELL_UID;
249
250    // Cap the size of permission trees that 3rd party apps can define
251    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
252
253    // Suffix used during package installation when copying/moving
254    // package apks to install directory.
255    private static final String INSTALL_PACKAGE_SUFFIX = "-";
256
257    static final int SCAN_NO_DEX = 1<<1;
258    static final int SCAN_FORCE_DEX = 1<<2;
259    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
260    static final int SCAN_NEW_INSTALL = 1<<4;
261    static final int SCAN_NO_PATHS = 1<<5;
262    static final int SCAN_UPDATE_TIME = 1<<6;
263    static final int SCAN_DEFER_DEX = 1<<7;
264    static final int SCAN_BOOTING = 1<<8;
265    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
266    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
267    static final int SCAN_REPLACING = 1<<11;
268
269    static final int REMOVE_CHATTY = 1<<16;
270
271    /**
272     * Timeout (in milliseconds) after which the watchdog should declare that
273     * our handler thread is wedged.  The usual default for such things is one
274     * minute but we sometimes do very lengthy I/O operations on this thread,
275     * such as installing multi-gigabyte applications, so ours needs to be longer.
276     */
277    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
278
279    /**
280     * Whether verification is enabled by default.
281     */
282    private static final boolean DEFAULT_VERIFY_ENABLE = true;
283
284    /**
285     * The default maximum time to wait for the verification agent to return in
286     * milliseconds.
287     */
288    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
289
290    /**
291     * The default response for package verification timeout.
292     *
293     * This can be either PackageManager.VERIFICATION_ALLOW or
294     * PackageManager.VERIFICATION_REJECT.
295     */
296    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
297
298    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
299
300    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
301            DEFAULT_CONTAINER_PACKAGE,
302            "com.android.defcontainer.DefaultContainerService");
303
304    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
305
306    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
307
308    private static String sPreferredInstructionSet;
309
310    final ServiceThread mHandlerThread;
311
312    private static final String IDMAP_PREFIX = "/data/resource-cache/";
313    private static final String IDMAP_SUFFIX = "@idmap";
314
315    final PackageHandler mHandler;
316
317    /**
318     * Messages for {@link #mHandler} that need to wait for system ready before
319     * being dispatched.
320     */
321    private ArrayList<Message> mPostSystemReadyMessages;
322
323    final int mSdkVersion = Build.VERSION.SDK_INT;
324
325    final Context mContext;
326    final boolean mFactoryTest;
327    final boolean mOnlyCore;
328    final boolean mLazyDexOpt;
329    final DisplayMetrics mMetrics;
330    final int mDefParseFlags;
331    final String[] mSeparateProcesses;
332
333    // This is where all application persistent data goes.
334    final File mAppDataDir;
335
336    // This is where all application persistent data goes for secondary users.
337    final File mUserAppDataDir;
338
339    /** The location for ASEC container files on internal storage. */
340    final String mAsecInternalPath;
341
342    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
343    // LOCK HELD.  Can be called with mInstallLock held.
344    final Installer mInstaller;
345
346    /** Directory where installed third-party apps stored */
347    final File mAppInstallDir;
348
349    /**
350     * Directory to which applications installed internally have their
351     * 32 bit native libraries copied.
352     */
353    private File mAppLib32InstallDir;
354
355    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
356    // apps.
357    final File mDrmAppPrivateInstallDir;
358
359    // ----------------------------------------------------------------
360
361    // Lock for state used when installing and doing other long running
362    // operations.  Methods that must be called with this lock held have
363    // the suffix "LI".
364    final Object mInstallLock = new Object();
365
366    // ----------------------------------------------------------------
367
368    // Keys are String (package name), values are Package.  This also serves
369    // as the lock for the global state.  Methods that must be called with
370    // this lock held have the prefix "LP".
371    final HashMap<String, PackageParser.Package> mPackages =
372            new HashMap<String, PackageParser.Package>();
373
374    // Tracks available target package names -> overlay package paths.
375    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
376        new HashMap<String, HashMap<String, PackageParser.Package>>();
377
378    final Settings mSettings;
379    boolean mRestoredSettings;
380
381    // System configuration read by SystemConfig.
382    final int[] mGlobalGids;
383    final SparseArray<HashSet<String>> mSystemPermissions;
384    final HashMap<String, FeatureInfo> mAvailableFeatures;
385
386    // If mac_permissions.xml was found for seinfo labeling.
387    boolean mFoundPolicyFile;
388
389    // If a recursive restorecon of /data/data/<pkg> is needed.
390    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
391
392    public static final class SharedLibraryEntry {
393        public final String path;
394        public final String apk;
395
396        SharedLibraryEntry(String _path, String _apk) {
397            path = _path;
398            apk = _apk;
399        }
400    }
401
402    // Currently known shared libraries.
403    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
404            new HashMap<String, SharedLibraryEntry>();
405
406    // All available activities, for your resolving pleasure.
407    final ActivityIntentResolver mActivities =
408            new ActivityIntentResolver();
409
410    // All available receivers, for your resolving pleasure.
411    final ActivityIntentResolver mReceivers =
412            new ActivityIntentResolver();
413
414    // All available services, for your resolving pleasure.
415    final ServiceIntentResolver mServices = new ServiceIntentResolver();
416
417    // All available providers, for your resolving pleasure.
418    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
419
420    // Mapping from provider base names (first directory in content URI codePath)
421    // to the provider information.
422    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
423            new HashMap<String, PackageParser.Provider>();
424
425    // Mapping from instrumentation class names to info about them.
426    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
427            new HashMap<ComponentName, PackageParser.Instrumentation>();
428
429    // Mapping from permission names to info about them.
430    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
431            new HashMap<String, PackageParser.PermissionGroup>();
432
433    // Packages whose data we have transfered into another package, thus
434    // should no longer exist.
435    final HashSet<String> mTransferedPackages = new HashSet<String>();
436
437    // Broadcast actions that are only available to the system.
438    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
439
440    /** List of packages waiting for verification. */
441    final SparseArray<PackageVerificationState> mPendingVerification
442            = new SparseArray<PackageVerificationState>();
443
444    /** Set of packages associated with each app op permission. */
445    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
446
447    final PackageInstallerService mInstallerService;
448
449    HashSet<PackageParser.Package> mDeferredDexOpt = null;
450
451    // Cache of users who need badging.
452    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
453
454    /** Token for keys in mPendingVerification. */
455    private int mPendingVerificationToken = 0;
456
457    volatile boolean mSystemReady;
458    volatile boolean mSafeMode;
459    volatile boolean mHasSystemUidErrors;
460
461    ApplicationInfo mAndroidApplication;
462    final ActivityInfo mResolveActivity = new ActivityInfo();
463    final ResolveInfo mResolveInfo = new ResolveInfo();
464    ComponentName mResolveComponentName;
465    PackageParser.Package mPlatformPackage;
466    ComponentName mCustomResolverComponentName;
467
468    boolean mResolverReplaced = false;
469
470    // Set of pending broadcasts for aggregating enable/disable of components.
471    static class PendingPackageBroadcasts {
472        // for each user id, a map of <package name -> components within that package>
473        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
474
475        public PendingPackageBroadcasts() {
476            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
477        }
478
479        public ArrayList<String> get(int userId, String packageName) {
480            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
481            return packages.get(packageName);
482        }
483
484        public void put(int userId, String packageName, ArrayList<String> components) {
485            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
486            packages.put(packageName, components);
487        }
488
489        public void remove(int userId, String packageName) {
490            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
491            if (packages != null) {
492                packages.remove(packageName);
493            }
494        }
495
496        public void remove(int userId) {
497            mUidMap.remove(userId);
498        }
499
500        public int userIdCount() {
501            return mUidMap.size();
502        }
503
504        public int userIdAt(int n) {
505            return mUidMap.keyAt(n);
506        }
507
508        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
509            return mUidMap.get(userId);
510        }
511
512        public int size() {
513            // total number of pending broadcast entries across all userIds
514            int num = 0;
515            for (int i = 0; i< mUidMap.size(); i++) {
516                num += mUidMap.valueAt(i).size();
517            }
518            return num;
519        }
520
521        public void clear() {
522            mUidMap.clear();
523        }
524
525        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
526            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
527            if (map == null) {
528                map = new HashMap<String, ArrayList<String>>();
529                mUidMap.put(userId, map);
530            }
531            return map;
532        }
533    }
534    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
535
536    // Service Connection to remote media container service to copy
537    // package uri's from external media onto secure containers
538    // or internal storage.
539    private IMediaContainerService mContainerService = null;
540
541    static final int SEND_PENDING_BROADCAST = 1;
542    static final int MCS_BOUND = 3;
543    static final int END_COPY = 4;
544    static final int INIT_COPY = 5;
545    static final int MCS_UNBIND = 6;
546    static final int START_CLEANING_PACKAGE = 7;
547    static final int FIND_INSTALL_LOC = 8;
548    static final int POST_INSTALL = 9;
549    static final int MCS_RECONNECT = 10;
550    static final int MCS_GIVE_UP = 11;
551    static final int UPDATED_MEDIA_STATUS = 12;
552    static final int WRITE_SETTINGS = 13;
553    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
554    static final int PACKAGE_VERIFIED = 15;
555    static final int CHECK_PENDING_VERIFICATION = 16;
556
557    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
558
559    // Delay time in millisecs
560    static final int BROADCAST_DELAY = 10 * 1000;
561
562    static UserManagerService sUserManager;
563
564    // Stores a list of users whose package restrictions file needs to be updated
565    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
566
567    final private DefaultContainerConnection mDefContainerConn =
568            new DefaultContainerConnection();
569    class DefaultContainerConnection implements ServiceConnection {
570        public void onServiceConnected(ComponentName name, IBinder service) {
571            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
572            IMediaContainerService imcs =
573                IMediaContainerService.Stub.asInterface(service);
574            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
575        }
576
577        public void onServiceDisconnected(ComponentName name) {
578            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
579        }
580    };
581
582    // Recordkeeping of restore-after-install operations that are currently in flight
583    // between the Package Manager and the Backup Manager
584    class PostInstallData {
585        public InstallArgs args;
586        public PackageInstalledInfo res;
587
588        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
589            args = _a;
590            res = _r;
591        }
592    };
593    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
594    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
595
596    private final String mRequiredVerifierPackage;
597
598    private final PackageUsage mPackageUsage = new PackageUsage();
599
600    private class PackageUsage {
601        private static final int WRITE_INTERVAL
602            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
603
604        private final Object mFileLock = new Object();
605        private final AtomicLong mLastWritten = new AtomicLong(0);
606        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
607
608        private boolean mIsHistoricalPackageUsageAvailable = true;
609
610        boolean isHistoricalPackageUsageAvailable() {
611            return mIsHistoricalPackageUsageAvailable;
612        }
613
614        void write(boolean force) {
615            if (force) {
616                writeInternal();
617                return;
618            }
619            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
620                && !DEBUG_DEXOPT) {
621                return;
622            }
623            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
624                new Thread("PackageUsage_DiskWriter") {
625                    @Override
626                    public void run() {
627                        try {
628                            writeInternal();
629                        } finally {
630                            mBackgroundWriteRunning.set(false);
631                        }
632                    }
633                }.start();
634            }
635        }
636
637        private void writeInternal() {
638            synchronized (mPackages) {
639                synchronized (mFileLock) {
640                    AtomicFile file = getFile();
641                    FileOutputStream f = null;
642                    try {
643                        f = file.startWrite();
644                        BufferedOutputStream out = new BufferedOutputStream(f);
645                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
646                        StringBuilder sb = new StringBuilder();
647                        for (PackageParser.Package pkg : mPackages.values()) {
648                            if (pkg.mLastPackageUsageTimeInMills == 0) {
649                                continue;
650                            }
651                            sb.setLength(0);
652                            sb.append(pkg.packageName);
653                            sb.append(' ');
654                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
655                            sb.append('\n');
656                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
657                        }
658                        out.flush();
659                        file.finishWrite(f);
660                    } catch (IOException e) {
661                        if (f != null) {
662                            file.failWrite(f);
663                        }
664                        Log.e(TAG, "Failed to write package usage times", e);
665                    }
666                }
667            }
668            mLastWritten.set(SystemClock.elapsedRealtime());
669        }
670
671        void readLP() {
672            synchronized (mFileLock) {
673                AtomicFile file = getFile();
674                BufferedInputStream in = null;
675                try {
676                    in = new BufferedInputStream(file.openRead());
677                    StringBuffer sb = new StringBuffer();
678                    while (true) {
679                        String packageName = readToken(in, sb, ' ');
680                        if (packageName == null) {
681                            break;
682                        }
683                        String timeInMillisString = readToken(in, sb, '\n');
684                        if (timeInMillisString == null) {
685                            throw new IOException("Failed to find last usage time for package "
686                                                  + packageName);
687                        }
688                        PackageParser.Package pkg = mPackages.get(packageName);
689                        if (pkg == null) {
690                            continue;
691                        }
692                        long timeInMillis;
693                        try {
694                            timeInMillis = Long.parseLong(timeInMillisString.toString());
695                        } catch (NumberFormatException e) {
696                            throw new IOException("Failed to parse " + timeInMillisString
697                                                  + " as a long.", e);
698                        }
699                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
700                    }
701                } catch (FileNotFoundException expected) {
702                    mIsHistoricalPackageUsageAvailable = false;
703                } catch (IOException e) {
704                    Log.w(TAG, "Failed to read package usage times", e);
705                } finally {
706                    IoUtils.closeQuietly(in);
707                }
708            }
709            mLastWritten.set(SystemClock.elapsedRealtime());
710        }
711
712        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
713                throws IOException {
714            sb.setLength(0);
715            while (true) {
716                int ch = in.read();
717                if (ch == -1) {
718                    if (sb.length() == 0) {
719                        return null;
720                    }
721                    throw new IOException("Unexpected EOF");
722                }
723                if (ch == endOfToken) {
724                    return sb.toString();
725                }
726                sb.append((char)ch);
727            }
728        }
729
730        private AtomicFile getFile() {
731            File dataDir = Environment.getDataDirectory();
732            File systemDir = new File(dataDir, "system");
733            File fname = new File(systemDir, "package-usage.list");
734            return new AtomicFile(fname);
735        }
736    }
737
738    class PackageHandler extends Handler {
739        private boolean mBound = false;
740        final ArrayList<HandlerParams> mPendingInstalls =
741            new ArrayList<HandlerParams>();
742
743        private boolean connectToService() {
744            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
745                    " DefaultContainerService");
746            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
747            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
748            if (mContext.bindServiceAsUser(service, mDefContainerConn,
749                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
750                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
751                mBound = true;
752                return true;
753            }
754            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
755            return false;
756        }
757
758        private void disconnectService() {
759            mContainerService = null;
760            mBound = false;
761            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
762            mContext.unbindService(mDefContainerConn);
763            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
764        }
765
766        PackageHandler(Looper looper) {
767            super(looper);
768        }
769
770        public void handleMessage(Message msg) {
771            try {
772                doHandleMessage(msg);
773            } finally {
774                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
775            }
776        }
777
778        void doHandleMessage(Message msg) {
779            switch (msg.what) {
780                case INIT_COPY: {
781                    HandlerParams params = (HandlerParams) msg.obj;
782                    int idx = mPendingInstalls.size();
783                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
784                    // If a bind was already initiated we dont really
785                    // need to do anything. The pending install
786                    // will be processed later on.
787                    if (!mBound) {
788                        // If this is the only one pending we might
789                        // have to bind to the service again.
790                        if (!connectToService()) {
791                            Slog.e(TAG, "Failed to bind to media container service");
792                            params.serviceError();
793                            return;
794                        } else {
795                            // Once we bind to the service, the first
796                            // pending request will be processed.
797                            mPendingInstalls.add(idx, params);
798                        }
799                    } else {
800                        mPendingInstalls.add(idx, params);
801                        // Already bound to the service. Just make
802                        // sure we trigger off processing the first request.
803                        if (idx == 0) {
804                            mHandler.sendEmptyMessage(MCS_BOUND);
805                        }
806                    }
807                    break;
808                }
809                case MCS_BOUND: {
810                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
811                    if (msg.obj != null) {
812                        mContainerService = (IMediaContainerService) msg.obj;
813                    }
814                    if (mContainerService == null) {
815                        // Something seriously wrong. Bail out
816                        Slog.e(TAG, "Cannot bind to media container service");
817                        for (HandlerParams params : mPendingInstalls) {
818                            // Indicate service bind error
819                            params.serviceError();
820                        }
821                        mPendingInstalls.clear();
822                    } else if (mPendingInstalls.size() > 0) {
823                        HandlerParams params = mPendingInstalls.get(0);
824                        if (params != null) {
825                            if (params.startCopy()) {
826                                // We are done...  look for more work or to
827                                // go idle.
828                                if (DEBUG_SD_INSTALL) Log.i(TAG,
829                                        "Checking for more work or unbind...");
830                                // Delete pending install
831                                if (mPendingInstalls.size() > 0) {
832                                    mPendingInstalls.remove(0);
833                                }
834                                if (mPendingInstalls.size() == 0) {
835                                    if (mBound) {
836                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
837                                                "Posting delayed MCS_UNBIND");
838                                        removeMessages(MCS_UNBIND);
839                                        Message ubmsg = obtainMessage(MCS_UNBIND);
840                                        // Unbind after a little delay, to avoid
841                                        // continual thrashing.
842                                        sendMessageDelayed(ubmsg, 10000);
843                                    }
844                                } else {
845                                    // There are more pending requests in queue.
846                                    // Just post MCS_BOUND message to trigger processing
847                                    // of next pending install.
848                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
849                                            "Posting MCS_BOUND for next work");
850                                    mHandler.sendEmptyMessage(MCS_BOUND);
851                                }
852                            }
853                        }
854                    } else {
855                        // Should never happen ideally.
856                        Slog.w(TAG, "Empty queue");
857                    }
858                    break;
859                }
860                case MCS_RECONNECT: {
861                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
862                    if (mPendingInstalls.size() > 0) {
863                        if (mBound) {
864                            disconnectService();
865                        }
866                        if (!connectToService()) {
867                            Slog.e(TAG, "Failed to bind to media container service");
868                            for (HandlerParams params : mPendingInstalls) {
869                                // Indicate service bind error
870                                params.serviceError();
871                            }
872                            mPendingInstalls.clear();
873                        }
874                    }
875                    break;
876                }
877                case MCS_UNBIND: {
878                    // If there is no actual work left, then time to unbind.
879                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
880
881                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
882                        if (mBound) {
883                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
884
885                            disconnectService();
886                        }
887                    } else if (mPendingInstalls.size() > 0) {
888                        // There are more pending requests in queue.
889                        // Just post MCS_BOUND message to trigger processing
890                        // of next pending install.
891                        mHandler.sendEmptyMessage(MCS_BOUND);
892                    }
893
894                    break;
895                }
896                case MCS_GIVE_UP: {
897                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
898                    mPendingInstalls.remove(0);
899                    break;
900                }
901                case SEND_PENDING_BROADCAST: {
902                    String packages[];
903                    ArrayList<String> components[];
904                    int size = 0;
905                    int uids[];
906                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
907                    synchronized (mPackages) {
908                        if (mPendingBroadcasts == null) {
909                            return;
910                        }
911                        size = mPendingBroadcasts.size();
912                        if (size <= 0) {
913                            // Nothing to be done. Just return
914                            return;
915                        }
916                        packages = new String[size];
917                        components = new ArrayList[size];
918                        uids = new int[size];
919                        int i = 0;  // filling out the above arrays
920
921                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
922                            int packageUserId = mPendingBroadcasts.userIdAt(n);
923                            Iterator<Map.Entry<String, ArrayList<String>>> it
924                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
925                                            .entrySet().iterator();
926                            while (it.hasNext() && i < size) {
927                                Map.Entry<String, ArrayList<String>> ent = it.next();
928                                packages[i] = ent.getKey();
929                                components[i] = ent.getValue();
930                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
931                                uids[i] = (ps != null)
932                                        ? UserHandle.getUid(packageUserId, ps.appId)
933                                        : -1;
934                                i++;
935                            }
936                        }
937                        size = i;
938                        mPendingBroadcasts.clear();
939                    }
940                    // Send broadcasts
941                    for (int i = 0; i < size; i++) {
942                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
943                    }
944                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
945                    break;
946                }
947                case START_CLEANING_PACKAGE: {
948                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
949                    final String packageName = (String)msg.obj;
950                    final int userId = msg.arg1;
951                    final boolean andCode = msg.arg2 != 0;
952                    synchronized (mPackages) {
953                        if (userId == UserHandle.USER_ALL) {
954                            int[] users = sUserManager.getUserIds();
955                            for (int user : users) {
956                                mSettings.addPackageToCleanLPw(
957                                        new PackageCleanItem(user, packageName, andCode));
958                            }
959                        } else {
960                            mSettings.addPackageToCleanLPw(
961                                    new PackageCleanItem(userId, packageName, andCode));
962                        }
963                    }
964                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
965                    startCleaningPackages();
966                } break;
967                case POST_INSTALL: {
968                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
969                    PostInstallData data = mRunningInstalls.get(msg.arg1);
970                    mRunningInstalls.delete(msg.arg1);
971                    boolean deleteOld = false;
972
973                    if (data != null) {
974                        InstallArgs args = data.args;
975                        PackageInstalledInfo res = data.res;
976
977                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
978                            res.removedInfo.sendBroadcast(false, true, false);
979                            Bundle extras = new Bundle(1);
980                            extras.putInt(Intent.EXTRA_UID, res.uid);
981                            // Determine the set of users who are adding this
982                            // package for the first time vs. those who are seeing
983                            // an update.
984                            int[] firstUsers;
985                            int[] updateUsers = new int[0];
986                            if (res.origUsers == null || res.origUsers.length == 0) {
987                                firstUsers = res.newUsers;
988                            } else {
989                                firstUsers = new int[0];
990                                for (int i=0; i<res.newUsers.length; i++) {
991                                    int user = res.newUsers[i];
992                                    boolean isNew = true;
993                                    for (int j=0; j<res.origUsers.length; j++) {
994                                        if (res.origUsers[j] == user) {
995                                            isNew = false;
996                                            break;
997                                        }
998                                    }
999                                    if (isNew) {
1000                                        int[] newFirst = new int[firstUsers.length+1];
1001                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1002                                                firstUsers.length);
1003                                        newFirst[firstUsers.length] = user;
1004                                        firstUsers = newFirst;
1005                                    } else {
1006                                        int[] newUpdate = new int[updateUsers.length+1];
1007                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1008                                                updateUsers.length);
1009                                        newUpdate[updateUsers.length] = user;
1010                                        updateUsers = newUpdate;
1011                                    }
1012                                }
1013                            }
1014                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1015                                    res.pkg.applicationInfo.packageName,
1016                                    extras, null, null, firstUsers);
1017                            final boolean update = res.removedInfo.removedPackage != null;
1018                            if (update) {
1019                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1020                            }
1021                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1022                                    res.pkg.applicationInfo.packageName,
1023                                    extras, null, null, updateUsers);
1024                            if (update) {
1025                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1026                                        res.pkg.applicationInfo.packageName,
1027                                        extras, null, null, updateUsers);
1028                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1029                                        null, null,
1030                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1031
1032                                // treat asec-hosted packages like removable media on upgrade
1033                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1034                                    if (DEBUG_INSTALL) {
1035                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1036                                                + " is ASEC-hosted -> AVAILABLE");
1037                                    }
1038                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1039                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1040                                    pkgList.add(res.pkg.applicationInfo.packageName);
1041                                    sendResourcesChangedBroadcast(true, true,
1042                                            pkgList,uidArray, null);
1043                                }
1044                            }
1045                            if (res.removedInfo.args != null) {
1046                                // Remove the replaced package's older resources safely now
1047                                deleteOld = true;
1048                            }
1049
1050                            // Log current value of "unknown sources" setting
1051                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1052                                getUnknownSourcesSettings());
1053                        }
1054                        // Force a gc to clear up things
1055                        Runtime.getRuntime().gc();
1056                        // We delete after a gc for applications  on sdcard.
1057                        if (deleteOld) {
1058                            synchronized (mInstallLock) {
1059                                res.removedInfo.args.doPostDeleteLI(true);
1060                            }
1061                        }
1062                        if (args.observer != null) {
1063                            try {
1064                                Bundle extras = extrasForInstallResult(res);
1065                                args.observer.onPackageInstalled(res.name, res.returnCode,
1066                                        res.returnMsg, extras);
1067                            } catch (RemoteException e) {
1068                                Slog.i(TAG, "Observer no longer exists.");
1069                            }
1070                        }
1071                    } else {
1072                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1073                    }
1074                } break;
1075                case UPDATED_MEDIA_STATUS: {
1076                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1077                    boolean reportStatus = msg.arg1 == 1;
1078                    boolean doGc = msg.arg2 == 1;
1079                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1080                    if (doGc) {
1081                        // Force a gc to clear up stale containers.
1082                        Runtime.getRuntime().gc();
1083                    }
1084                    if (msg.obj != null) {
1085                        @SuppressWarnings("unchecked")
1086                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1087                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1088                        // Unload containers
1089                        unloadAllContainers(args);
1090                    }
1091                    if (reportStatus) {
1092                        try {
1093                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1094                            PackageHelper.getMountService().finishMediaUpdate();
1095                        } catch (RemoteException e) {
1096                            Log.e(TAG, "MountService not running?");
1097                        }
1098                    }
1099                } break;
1100                case WRITE_SETTINGS: {
1101                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1102                    synchronized (mPackages) {
1103                        removeMessages(WRITE_SETTINGS);
1104                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1105                        mSettings.writeLPr();
1106                        mDirtyUsers.clear();
1107                    }
1108                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1109                } break;
1110                case WRITE_PACKAGE_RESTRICTIONS: {
1111                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1112                    synchronized (mPackages) {
1113                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1114                        for (int userId : mDirtyUsers) {
1115                            mSettings.writePackageRestrictionsLPr(userId);
1116                        }
1117                        mDirtyUsers.clear();
1118                    }
1119                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1120                } break;
1121                case CHECK_PENDING_VERIFICATION: {
1122                    final int verificationId = msg.arg1;
1123                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1124
1125                    if ((state != null) && !state.timeoutExtended()) {
1126                        final InstallArgs args = state.getInstallArgs();
1127                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1128
1129                        Slog.i(TAG, "Verification timed out for " + originUri);
1130                        mPendingVerification.remove(verificationId);
1131
1132                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1133
1134                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1135                            Slog.i(TAG, "Continuing with installation of " + originUri);
1136                            state.setVerifierResponse(Binder.getCallingUid(),
1137                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1138                            broadcastPackageVerified(verificationId, originUri,
1139                                    PackageManager.VERIFICATION_ALLOW,
1140                                    state.getInstallArgs().getUser());
1141                            try {
1142                                ret = args.copyApk(mContainerService, true);
1143                            } catch (RemoteException e) {
1144                                Slog.e(TAG, "Could not contact the ContainerService");
1145                            }
1146                        } else {
1147                            broadcastPackageVerified(verificationId, originUri,
1148                                    PackageManager.VERIFICATION_REJECT,
1149                                    state.getInstallArgs().getUser());
1150                        }
1151
1152                        processPendingInstall(args, ret);
1153                        mHandler.sendEmptyMessage(MCS_UNBIND);
1154                    }
1155                    break;
1156                }
1157                case PACKAGE_VERIFIED: {
1158                    final int verificationId = msg.arg1;
1159
1160                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1161                    if (state == null) {
1162                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1163                        break;
1164                    }
1165
1166                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1167
1168                    state.setVerifierResponse(response.callerUid, response.code);
1169
1170                    if (state.isVerificationComplete()) {
1171                        mPendingVerification.remove(verificationId);
1172
1173                        final InstallArgs args = state.getInstallArgs();
1174                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1175
1176                        int ret;
1177                        if (state.isInstallAllowed()) {
1178                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1179                            broadcastPackageVerified(verificationId, originUri,
1180                                    response.code, state.getInstallArgs().getUser());
1181                            try {
1182                                ret = args.copyApk(mContainerService, true);
1183                            } catch (RemoteException e) {
1184                                Slog.e(TAG, "Could not contact the ContainerService");
1185                            }
1186                        } else {
1187                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1188                        }
1189
1190                        processPendingInstall(args, ret);
1191
1192                        mHandler.sendEmptyMessage(MCS_UNBIND);
1193                    }
1194
1195                    break;
1196                }
1197            }
1198        }
1199    }
1200
1201    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1202        Bundle extras = null;
1203        switch (res.returnCode) {
1204            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1205                extras = new Bundle();
1206                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1207                        res.origPermission);
1208                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1209                        res.origPackage);
1210                break;
1211            }
1212        }
1213        return extras;
1214    }
1215
1216    void scheduleWriteSettingsLocked() {
1217        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1218            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1219        }
1220    }
1221
1222    void scheduleWritePackageRestrictionsLocked(int userId) {
1223        if (!sUserManager.exists(userId)) return;
1224        mDirtyUsers.add(userId);
1225        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1226            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1227        }
1228    }
1229
1230    public static final PackageManagerService main(Context context, Installer installer,
1231            boolean factoryTest, boolean onlyCore) {
1232        PackageManagerService m = new PackageManagerService(context, installer,
1233                factoryTest, onlyCore);
1234        ServiceManager.addService("package", m);
1235        return m;
1236    }
1237
1238    static String[] splitString(String str, char sep) {
1239        int count = 1;
1240        int i = 0;
1241        while ((i=str.indexOf(sep, i)) >= 0) {
1242            count++;
1243            i++;
1244        }
1245
1246        String[] res = new String[count];
1247        i=0;
1248        count = 0;
1249        int lastI=0;
1250        while ((i=str.indexOf(sep, i)) >= 0) {
1251            res[count] = str.substring(lastI, i);
1252            count++;
1253            i++;
1254            lastI = i;
1255        }
1256        res[count] = str.substring(lastI, str.length());
1257        return res;
1258    }
1259
1260    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1261        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1262                Context.DISPLAY_SERVICE);
1263        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1264    }
1265
1266    public PackageManagerService(Context context, Installer installer,
1267            boolean factoryTest, boolean onlyCore) {
1268        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1269                SystemClock.uptimeMillis());
1270
1271        if (mSdkVersion <= 0) {
1272            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1273        }
1274
1275        mContext = context;
1276        mFactoryTest = factoryTest;
1277        mOnlyCore = onlyCore;
1278        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1279        mMetrics = new DisplayMetrics();
1280        mSettings = new Settings(context);
1281        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1282                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1283        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1284                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1285        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1286                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1287        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1288                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1289        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1290                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1291        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1292                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1293
1294        String separateProcesses = SystemProperties.get("debug.separate_processes");
1295        if (separateProcesses != null && separateProcesses.length() > 0) {
1296            if ("*".equals(separateProcesses)) {
1297                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1298                mSeparateProcesses = null;
1299                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1300            } else {
1301                mDefParseFlags = 0;
1302                mSeparateProcesses = separateProcesses.split(",");
1303                Slog.w(TAG, "Running with debug.separate_processes: "
1304                        + separateProcesses);
1305            }
1306        } else {
1307            mDefParseFlags = 0;
1308            mSeparateProcesses = null;
1309        }
1310
1311        mInstaller = installer;
1312
1313        getDefaultDisplayMetrics(context, mMetrics);
1314
1315        SystemConfig systemConfig = SystemConfig.getInstance();
1316        mGlobalGids = systemConfig.getGlobalGids();
1317        mSystemPermissions = systemConfig.getSystemPermissions();
1318        mAvailableFeatures = systemConfig.getAvailableFeatures();
1319
1320        synchronized (mInstallLock) {
1321        // writer
1322        synchronized (mPackages) {
1323            mHandlerThread = new ServiceThread(TAG,
1324                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1325            mHandlerThread.start();
1326            mHandler = new PackageHandler(mHandlerThread.getLooper());
1327            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1328
1329            File dataDir = Environment.getDataDirectory();
1330            mAppDataDir = new File(dataDir, "data");
1331            mAppInstallDir = new File(dataDir, "app");
1332            mAppLib32InstallDir = new File(dataDir, "app-lib");
1333            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1334            mUserAppDataDir = new File(dataDir, "user");
1335            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1336
1337            sUserManager = new UserManagerService(context, this,
1338                    mInstallLock, mPackages);
1339
1340            // Propagate permission configuration in to package manager.
1341            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1342                    = systemConfig.getPermissions();
1343            for (int i=0; i<permConfig.size(); i++) {
1344                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1345                BasePermission bp = mSettings.mPermissions.get(perm.name);
1346                if (bp == null) {
1347                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1348                    mSettings.mPermissions.put(perm.name, bp);
1349                }
1350                if (perm.gids != null) {
1351                    bp.gids = appendInts(bp.gids, perm.gids);
1352                }
1353            }
1354
1355            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1356            for (int i=0; i<libConfig.size(); i++) {
1357                mSharedLibraries.put(libConfig.keyAt(i),
1358                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1359            }
1360
1361            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1362
1363            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1364                    mSdkVersion, mOnlyCore);
1365
1366            String customResolverActivity = Resources.getSystem().getString(
1367                    R.string.config_customResolverActivity);
1368            if (TextUtils.isEmpty(customResolverActivity)) {
1369                customResolverActivity = null;
1370            } else {
1371                mCustomResolverComponentName = ComponentName.unflattenFromString(
1372                        customResolverActivity);
1373            }
1374
1375            long startTime = SystemClock.uptimeMillis();
1376
1377            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1378                    startTime);
1379
1380            // Set flag to monitor and not change apk file paths when
1381            // scanning install directories.
1382            int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1383
1384            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1385
1386            /**
1387             * Add everything in the in the boot class path to the
1388             * list of process files because dexopt will have been run
1389             * if necessary during zygote startup.
1390             */
1391            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1392            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1393
1394            if (bootClassPath != null) {
1395                String[] bootClassPathElements = splitString(bootClassPath, ':');
1396                for (String element : bootClassPathElements) {
1397                    alreadyDexOpted.add(element);
1398                }
1399            } else {
1400                Slog.w(TAG, "No BOOTCLASSPATH found!");
1401            }
1402
1403            if (systemServerClassPath != null) {
1404                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1405                for (String element : systemServerClassPathElements) {
1406                    alreadyDexOpted.add(element);
1407                }
1408            } else {
1409                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1410            }
1411
1412            boolean didDexOptLibraryOrTool = false;
1413
1414            final List<String> allInstructionSets = getAllInstructionSets();
1415            final String[] dexCodeInstructionSets =
1416                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1417
1418            /**
1419             * Ensure all external libraries have had dexopt run on them.
1420             */
1421            if (mSharedLibraries.size() > 0) {
1422                // NOTE: For now, we're compiling these system "shared libraries"
1423                // (and framework jars) into all available architectures. It's possible
1424                // to compile them only when we come across an app that uses them (there's
1425                // already logic for that in scanPackageLI) but that adds some complexity.
1426                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1427                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1428                        final String lib = libEntry.path;
1429                        if (lib == null) {
1430                            continue;
1431                        }
1432
1433                        try {
1434                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1435                                                                                 dexCodeInstructionSet,
1436                                                                                 false);
1437                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1438                                alreadyDexOpted.add(lib);
1439
1440                                // The list of "shared libraries" we have at this point is
1441                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1442                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1443                                } else {
1444                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1445                                }
1446                                didDexOptLibraryOrTool = true;
1447                            }
1448                        } catch (FileNotFoundException e) {
1449                            Slog.w(TAG, "Library not found: " + lib);
1450                        } catch (IOException e) {
1451                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1452                                    + e.getMessage());
1453                        }
1454                    }
1455                }
1456            }
1457
1458            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1459
1460            // Gross hack for now: we know this file doesn't contain any
1461            // code, so don't dexopt it to avoid the resulting log spew.
1462            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1463
1464            // Gross hack for now: we know this file is only part of
1465            // the boot class path for art, so don't dexopt it to
1466            // avoid the resulting log spew.
1467            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1468
1469            /**
1470             * And there are a number of commands implemented in Java, which
1471             * we currently need to do the dexopt on so that they can be
1472             * run from a non-root shell.
1473             */
1474            String[] frameworkFiles = frameworkDir.list();
1475            if (frameworkFiles != null) {
1476                // TODO: We could compile these only for the most preferred ABI. We should
1477                // first double check that the dex files for these commands are not referenced
1478                // by other system apps.
1479                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1480                    for (int i=0; i<frameworkFiles.length; i++) {
1481                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1482                        String path = libPath.getPath();
1483                        // Skip the file if we already did it.
1484                        if (alreadyDexOpted.contains(path)) {
1485                            continue;
1486                        }
1487                        // Skip the file if it is not a type we want to dexopt.
1488                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1489                            continue;
1490                        }
1491                        try {
1492                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1493                                                                                 dexCodeInstructionSet,
1494                                                                                 false);
1495                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1496                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1497                                didDexOptLibraryOrTool = true;
1498                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1499                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1500                                didDexOptLibraryOrTool = true;
1501                            }
1502                        } catch (FileNotFoundException e) {
1503                            Slog.w(TAG, "Jar not found: " + path);
1504                        } catch (IOException e) {
1505                            Slog.w(TAG, "Exception reading jar: " + path, e);
1506                        }
1507                    }
1508                }
1509            }
1510
1511            // Collect vendor overlay packages.
1512            // (Do this before scanning any apps.)
1513            // For security and version matching reason, only consider
1514            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1515            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1516            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1517                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1518
1519            // Find base frameworks (resource packages without code).
1520            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1521                    | PackageParser.PARSE_IS_SYSTEM_DIR
1522                    | PackageParser.PARSE_IS_PRIVILEGED,
1523                    scanFlags | SCAN_NO_DEX, 0);
1524
1525            // Collected privileged system packages.
1526            File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1527            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1528                    | PackageParser.PARSE_IS_SYSTEM_DIR
1529                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1530
1531            // Collect ordinary system packages.
1532            File systemAppDir = new File(Environment.getRootDirectory(), "app");
1533            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1534                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1535
1536            // Collect all vendor packages.
1537            File vendorAppDir = new File("/vendor/app");
1538            try {
1539                vendorAppDir = vendorAppDir.getCanonicalFile();
1540            } catch (IOException e) {
1541                // failed to look up canonical path, continue with original one
1542            }
1543            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1544                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1545
1546            // Collect all OEM packages.
1547            File oemAppDir = new File(Environment.getOemDirectory(), "app");
1548            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1549                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1550
1551            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1552            mInstaller.moveFiles();
1553
1554            // Prune any system packages that no longer exist.
1555            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1556            if (!mOnlyCore) {
1557                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1558                while (psit.hasNext()) {
1559                    PackageSetting ps = psit.next();
1560
1561                    /*
1562                     * If this is not a system app, it can't be a
1563                     * disable system app.
1564                     */
1565                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1566                        continue;
1567                    }
1568
1569                    /*
1570                     * If the package is scanned, it's not erased.
1571                     */
1572                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1573                    if (scannedPkg != null) {
1574                        /*
1575                         * If the system app is both scanned and in the
1576                         * disabled packages list, then it must have been
1577                         * added via OTA. Remove it from the currently
1578                         * scanned package so the previously user-installed
1579                         * application can be scanned.
1580                         */
1581                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1582                            Slog.i(TAG, "Expecting better updatd system app for " + ps.name
1583                                    + "; removing system app");
1584                            removePackageLI(ps, true);
1585                        }
1586
1587                        continue;
1588                    }
1589
1590                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1591                        psit.remove();
1592                        String msg = "System package " + ps.name
1593                                + " no longer exists; wiping its data";
1594                        reportSettingsProblem(Log.WARN, msg);
1595                        removeDataDirsLI(ps.name);
1596                    } else {
1597                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1598                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1599                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1600                        }
1601                    }
1602                }
1603            }
1604
1605            //look for any incomplete package installations
1606            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1607            //clean up list
1608            for(int i = 0; i < deletePkgsList.size(); i++) {
1609                //clean up here
1610                cleanupInstallFailedPackage(deletePkgsList.get(i));
1611            }
1612            //delete tmp files
1613            deleteTempPackageFiles();
1614
1615            // Remove any shared userIDs that have no associated packages
1616            mSettings.pruneSharedUsersLPw();
1617
1618            if (!mOnlyCore) {
1619                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1620                        SystemClock.uptimeMillis());
1621                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1622
1623                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1624                        scanFlags, 0);
1625
1626                /**
1627                 * Remove disable package settings for any updated system
1628                 * apps that were removed via an OTA. If they're not a
1629                 * previously-updated app, remove them completely.
1630                 * Otherwise, just revoke their system-level permissions.
1631                 */
1632                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1633                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1634                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1635
1636                    String msg;
1637                    if (deletedPkg == null) {
1638                        msg = "Updated system package " + deletedAppName
1639                                + " no longer exists; wiping its data";
1640                        removeDataDirsLI(deletedAppName);
1641                    } else {
1642                        msg = "Updated system app + " + deletedAppName
1643                                + " no longer present; removing system privileges for "
1644                                + deletedAppName;
1645
1646                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1647
1648                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1649                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1650                    }
1651                    reportSettingsProblem(Log.WARN, msg);
1652                }
1653            }
1654
1655            // Now that we know all of the shared libraries, update all clients to have
1656            // the correct library paths.
1657            updateAllSharedLibrariesLPw();
1658
1659            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1660                // NOTE: We ignore potential failures here during a system scan (like
1661                // the rest of the commands above) because there's precious little we
1662                // can do about it. A settings error is reported, though.
1663                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1664                        false /* force dexopt */, false /* defer dexopt */);
1665            }
1666
1667            // Now that we know all the packages we are keeping,
1668            // read and update their last usage times.
1669            mPackageUsage.readLP();
1670
1671            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1672                    SystemClock.uptimeMillis());
1673            Slog.i(TAG, "Time to scan packages: "
1674                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1675                    + " seconds");
1676
1677            // If the platform SDK has changed since the last time we booted,
1678            // we need to re-grant app permission to catch any new ones that
1679            // appear.  This is really a hack, and means that apps can in some
1680            // cases get permissions that the user didn't initially explicitly
1681            // allow...  it would be nice to have some better way to handle
1682            // this situation.
1683            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1684                    != mSdkVersion;
1685            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1686                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1687                    + "; regranting permissions for internal storage");
1688            mSettings.mInternalSdkPlatform = mSdkVersion;
1689
1690            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1691                    | (regrantPermissions
1692                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1693                            : 0));
1694
1695            // If this is the first boot, and it is a normal boot, then
1696            // we need to initialize the default preferred apps.
1697            if (!mRestoredSettings && !onlyCore) {
1698                mSettings.readDefaultPreferredAppsLPw(this, 0);
1699            }
1700
1701            // If this is first boot after an OTA, and a normal boot, then
1702            // we need to clear code cache directories.
1703            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1704                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1705                for (String pkgName : mSettings.mPackages.keySet()) {
1706                    deleteCodeCacheDirsLI(pkgName);
1707                }
1708                mSettings.mFingerprint = Build.FINGERPRINT;
1709            }
1710
1711            // All the changes are done during package scanning.
1712            mSettings.updateInternalDatabaseVersion();
1713
1714            // can downgrade to reader
1715            mSettings.writeLPr();
1716
1717            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1718                    SystemClock.uptimeMillis());
1719
1720
1721            mRequiredVerifierPackage = getRequiredVerifierLPr();
1722        } // synchronized (mPackages)
1723        } // synchronized (mInstallLock)
1724
1725        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1726
1727        // Now after opening every single application zip, make sure they
1728        // are all flushed.  Not really needed, but keeps things nice and
1729        // tidy.
1730        Runtime.getRuntime().gc();
1731    }
1732
1733    @Override
1734    public boolean isFirstBoot() {
1735        return !mRestoredSettings;
1736    }
1737
1738    @Override
1739    public boolean isOnlyCoreApps() {
1740        return mOnlyCore;
1741    }
1742
1743    private String getRequiredVerifierLPr() {
1744        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1745        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1746                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1747
1748        String requiredVerifier = null;
1749
1750        final int N = receivers.size();
1751        for (int i = 0; i < N; i++) {
1752            final ResolveInfo info = receivers.get(i);
1753
1754            if (info.activityInfo == null) {
1755                continue;
1756            }
1757
1758            final String packageName = info.activityInfo.packageName;
1759
1760            final PackageSetting ps = mSettings.mPackages.get(packageName);
1761            if (ps == null) {
1762                continue;
1763            }
1764
1765            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1766            if (!gp.grantedPermissions
1767                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1768                continue;
1769            }
1770
1771            if (requiredVerifier != null) {
1772                throw new RuntimeException("There can be only one required verifier");
1773            }
1774
1775            requiredVerifier = packageName;
1776        }
1777
1778        return requiredVerifier;
1779    }
1780
1781    @Override
1782    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1783            throws RemoteException {
1784        try {
1785            return super.onTransact(code, data, reply, flags);
1786        } catch (RuntimeException e) {
1787            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1788                Slog.wtf(TAG, "Package Manager Crash", e);
1789            }
1790            throw e;
1791        }
1792    }
1793
1794    void cleanupInstallFailedPackage(PackageSetting ps) {
1795        Slog.i(TAG, "Cleaning up incompletely installed app: " + ps.name);
1796        removeDataDirsLI(ps.name);
1797        if (ps.codePath != null) {
1798            if (ps.codePath.isDirectory()) {
1799                FileUtils.deleteContents(ps.codePath);
1800            }
1801            ps.codePath.delete();
1802        }
1803        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1804            if (ps.resourcePath.isDirectory()) {
1805                FileUtils.deleteContents(ps.resourcePath);
1806            }
1807            ps.resourcePath.delete();
1808        }
1809        mSettings.removePackageLPw(ps.name);
1810    }
1811
1812    static int[] appendInts(int[] cur, int[] add) {
1813        if (add == null) return cur;
1814        if (cur == null) return add;
1815        final int N = add.length;
1816        for (int i=0; i<N; i++) {
1817            cur = appendInt(cur, add[i]);
1818        }
1819        return cur;
1820    }
1821
1822    static int[] removeInts(int[] cur, int[] rem) {
1823        if (rem == null) return cur;
1824        if (cur == null) return cur;
1825        final int N = rem.length;
1826        for (int i=0; i<N; i++) {
1827            cur = removeInt(cur, rem[i]);
1828        }
1829        return cur;
1830    }
1831
1832    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1833        if (!sUserManager.exists(userId)) return null;
1834        final PackageSetting ps = (PackageSetting) p.mExtras;
1835        if (ps == null) {
1836            return null;
1837        }
1838        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1839        final PackageUserState state = ps.readUserState(userId);
1840        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1841                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1842                state, userId);
1843    }
1844
1845    @Override
1846    public boolean isPackageAvailable(String packageName, int userId) {
1847        if (!sUserManager.exists(userId)) return false;
1848        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1849        synchronized (mPackages) {
1850            PackageParser.Package p = mPackages.get(packageName);
1851            if (p != null) {
1852                final PackageSetting ps = (PackageSetting) p.mExtras;
1853                if (ps != null) {
1854                    final PackageUserState state = ps.readUserState(userId);
1855                    if (state != null) {
1856                        return PackageParser.isAvailable(state);
1857                    }
1858                }
1859            }
1860        }
1861        return false;
1862    }
1863
1864    @Override
1865    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1866        if (!sUserManager.exists(userId)) return null;
1867        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
1868        // reader
1869        synchronized (mPackages) {
1870            PackageParser.Package p = mPackages.get(packageName);
1871            if (DEBUG_PACKAGE_INFO)
1872                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1873            if (p != null) {
1874                return generatePackageInfo(p, flags, userId);
1875            }
1876            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1877                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1878            }
1879        }
1880        return null;
1881    }
1882
1883    @Override
1884    public String[] currentToCanonicalPackageNames(String[] names) {
1885        String[] out = new String[names.length];
1886        // reader
1887        synchronized (mPackages) {
1888            for (int i=names.length-1; i>=0; i--) {
1889                PackageSetting ps = mSettings.mPackages.get(names[i]);
1890                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1891            }
1892        }
1893        return out;
1894    }
1895
1896    @Override
1897    public String[] canonicalToCurrentPackageNames(String[] names) {
1898        String[] out = new String[names.length];
1899        // reader
1900        synchronized (mPackages) {
1901            for (int i=names.length-1; i>=0; i--) {
1902                String cur = mSettings.mRenamedPackages.get(names[i]);
1903                out[i] = cur != null ? cur : names[i];
1904            }
1905        }
1906        return out;
1907    }
1908
1909    @Override
1910    public int getPackageUid(String packageName, int userId) {
1911        if (!sUserManager.exists(userId)) return -1;
1912        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
1913        // reader
1914        synchronized (mPackages) {
1915            PackageParser.Package p = mPackages.get(packageName);
1916            if(p != null) {
1917                return UserHandle.getUid(userId, p.applicationInfo.uid);
1918            }
1919            PackageSetting ps = mSettings.mPackages.get(packageName);
1920            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1921                return -1;
1922            }
1923            p = ps.pkg;
1924            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1925        }
1926    }
1927
1928    @Override
1929    public int[] getPackageGids(String packageName) {
1930        // reader
1931        synchronized (mPackages) {
1932            PackageParser.Package p = mPackages.get(packageName);
1933            if (DEBUG_PACKAGE_INFO)
1934                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1935            if (p != null) {
1936                final PackageSetting ps = (PackageSetting)p.mExtras;
1937                return ps.getGids();
1938            }
1939        }
1940        // stupid thing to indicate an error.
1941        return new int[0];
1942    }
1943
1944    static final PermissionInfo generatePermissionInfo(
1945            BasePermission bp, int flags) {
1946        if (bp.perm != null) {
1947            return PackageParser.generatePermissionInfo(bp.perm, flags);
1948        }
1949        PermissionInfo pi = new PermissionInfo();
1950        pi.name = bp.name;
1951        pi.packageName = bp.sourcePackage;
1952        pi.nonLocalizedLabel = bp.name;
1953        pi.protectionLevel = bp.protectionLevel;
1954        return pi;
1955    }
1956
1957    @Override
1958    public PermissionInfo getPermissionInfo(String name, int flags) {
1959        // reader
1960        synchronized (mPackages) {
1961            final BasePermission p = mSettings.mPermissions.get(name);
1962            if (p != null) {
1963                return generatePermissionInfo(p, flags);
1964            }
1965            return null;
1966        }
1967    }
1968
1969    @Override
1970    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
1971        // reader
1972        synchronized (mPackages) {
1973            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
1974            for (BasePermission p : mSettings.mPermissions.values()) {
1975                if (group == null) {
1976                    if (p.perm == null || p.perm.info.group == null) {
1977                        out.add(generatePermissionInfo(p, flags));
1978                    }
1979                } else {
1980                    if (p.perm != null && group.equals(p.perm.info.group)) {
1981                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
1982                    }
1983                }
1984            }
1985
1986            if (out.size() > 0) {
1987                return out;
1988            }
1989            return mPermissionGroups.containsKey(group) ? out : null;
1990        }
1991    }
1992
1993    @Override
1994    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
1995        // reader
1996        synchronized (mPackages) {
1997            return PackageParser.generatePermissionGroupInfo(
1998                    mPermissionGroups.get(name), flags);
1999        }
2000    }
2001
2002    @Override
2003    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2004        // reader
2005        synchronized (mPackages) {
2006            final int N = mPermissionGroups.size();
2007            ArrayList<PermissionGroupInfo> out
2008                    = new ArrayList<PermissionGroupInfo>(N);
2009            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2010                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2011            }
2012            return out;
2013        }
2014    }
2015
2016    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2017            int userId) {
2018        if (!sUserManager.exists(userId)) return null;
2019        PackageSetting ps = mSettings.mPackages.get(packageName);
2020        if (ps != null) {
2021            if (ps.pkg == null) {
2022                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2023                        flags, userId);
2024                if (pInfo != null) {
2025                    return pInfo.applicationInfo;
2026                }
2027                return null;
2028            }
2029            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2030                    ps.readUserState(userId), userId);
2031        }
2032        return null;
2033    }
2034
2035    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2036            int userId) {
2037        if (!sUserManager.exists(userId)) return null;
2038        PackageSetting ps = mSettings.mPackages.get(packageName);
2039        if (ps != null) {
2040            PackageParser.Package pkg = ps.pkg;
2041            if (pkg == null) {
2042                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2043                    return null;
2044                }
2045                // Only data remains, so we aren't worried about code paths
2046                pkg = new PackageParser.Package(packageName);
2047                pkg.applicationInfo.packageName = packageName;
2048                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2049                pkg.applicationInfo.dataDir =
2050                        getDataPathForPackage(packageName, 0).getPath();
2051                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2052                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2053            }
2054            return generatePackageInfo(pkg, flags, userId);
2055        }
2056        return null;
2057    }
2058
2059    @Override
2060    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2061        if (!sUserManager.exists(userId)) return null;
2062        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2063        // writer
2064        synchronized (mPackages) {
2065            PackageParser.Package p = mPackages.get(packageName);
2066            if (DEBUG_PACKAGE_INFO) Log.v(
2067                    TAG, "getApplicationInfo " + packageName
2068                    + ": " + p);
2069            if (p != null) {
2070                PackageSetting ps = mSettings.mPackages.get(packageName);
2071                if (ps == null) return null;
2072                // Note: isEnabledLP() does not apply here - always return info
2073                return PackageParser.generateApplicationInfo(
2074                        p, flags, ps.readUserState(userId), userId);
2075            }
2076            if ("android".equals(packageName)||"system".equals(packageName)) {
2077                return mAndroidApplication;
2078            }
2079            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2080                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2081            }
2082        }
2083        return null;
2084    }
2085
2086
2087    @Override
2088    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2089        mContext.enforceCallingOrSelfPermission(
2090                android.Manifest.permission.CLEAR_APP_CACHE, null);
2091        // Queue up an async operation since clearing cache may take a little while.
2092        mHandler.post(new Runnable() {
2093            public void run() {
2094                mHandler.removeCallbacks(this);
2095                int retCode = -1;
2096                synchronized (mInstallLock) {
2097                    retCode = mInstaller.freeCache(freeStorageSize);
2098                    if (retCode < 0) {
2099                        Slog.w(TAG, "Couldn't clear application caches");
2100                    }
2101                }
2102                if (observer != null) {
2103                    try {
2104                        observer.onRemoveCompleted(null, (retCode >= 0));
2105                    } catch (RemoteException e) {
2106                        Slog.w(TAG, "RemoveException when invoking call back");
2107                    }
2108                }
2109            }
2110        });
2111    }
2112
2113    @Override
2114    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2115        mContext.enforceCallingOrSelfPermission(
2116                android.Manifest.permission.CLEAR_APP_CACHE, null);
2117        // Queue up an async operation since clearing cache may take a little while.
2118        mHandler.post(new Runnable() {
2119            public void run() {
2120                mHandler.removeCallbacks(this);
2121                int retCode = -1;
2122                synchronized (mInstallLock) {
2123                    retCode = mInstaller.freeCache(freeStorageSize);
2124                    if (retCode < 0) {
2125                        Slog.w(TAG, "Couldn't clear application caches");
2126                    }
2127                }
2128                if(pi != null) {
2129                    try {
2130                        // Callback via pending intent
2131                        int code = (retCode >= 0) ? 1 : 0;
2132                        pi.sendIntent(null, code, null,
2133                                null, null);
2134                    } catch (SendIntentException e1) {
2135                        Slog.i(TAG, "Failed to send pending intent");
2136                    }
2137                }
2138            }
2139        });
2140    }
2141
2142    void freeStorage(long freeStorageSize) throws IOException {
2143        synchronized (mInstallLock) {
2144            if (mInstaller.freeCache(freeStorageSize) < 0) {
2145                throw new IOException("Failed to free enough space");
2146            }
2147        }
2148    }
2149
2150    @Override
2151    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2152        if (!sUserManager.exists(userId)) return null;
2153        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2154        synchronized (mPackages) {
2155            PackageParser.Activity a = mActivities.mActivities.get(component);
2156
2157            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2158            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2159                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2160                if (ps == null) return null;
2161                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2162                        userId);
2163            }
2164            if (mResolveComponentName.equals(component)) {
2165                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2166                        new PackageUserState(), userId);
2167            }
2168        }
2169        return null;
2170    }
2171
2172    @Override
2173    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2174            String resolvedType) {
2175        synchronized (mPackages) {
2176            PackageParser.Activity a = mActivities.mActivities.get(component);
2177            if (a == null) {
2178                return false;
2179            }
2180            for (int i=0; i<a.intents.size(); i++) {
2181                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2182                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2183                    return true;
2184                }
2185            }
2186            return false;
2187        }
2188    }
2189
2190    @Override
2191    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2192        if (!sUserManager.exists(userId)) return null;
2193        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2194        synchronized (mPackages) {
2195            PackageParser.Activity a = mReceivers.mActivities.get(component);
2196            if (DEBUG_PACKAGE_INFO) Log.v(
2197                TAG, "getReceiverInfo " + component + ": " + a);
2198            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2199                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2200                if (ps == null) return null;
2201                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2202                        userId);
2203            }
2204        }
2205        return null;
2206    }
2207
2208    @Override
2209    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2210        if (!sUserManager.exists(userId)) return null;
2211        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2212        synchronized (mPackages) {
2213            PackageParser.Service s = mServices.mServices.get(component);
2214            if (DEBUG_PACKAGE_INFO) Log.v(
2215                TAG, "getServiceInfo " + component + ": " + s);
2216            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2217                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2218                if (ps == null) return null;
2219                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2220                        userId);
2221            }
2222        }
2223        return null;
2224    }
2225
2226    @Override
2227    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2228        if (!sUserManager.exists(userId)) return null;
2229        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2230        synchronized (mPackages) {
2231            PackageParser.Provider p = mProviders.mProviders.get(component);
2232            if (DEBUG_PACKAGE_INFO) Log.v(
2233                TAG, "getProviderInfo " + component + ": " + p);
2234            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2235                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2236                if (ps == null) return null;
2237                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2238                        userId);
2239            }
2240        }
2241        return null;
2242    }
2243
2244    @Override
2245    public String[] getSystemSharedLibraryNames() {
2246        Set<String> libSet;
2247        synchronized (mPackages) {
2248            libSet = mSharedLibraries.keySet();
2249            int size = libSet.size();
2250            if (size > 0) {
2251                String[] libs = new String[size];
2252                libSet.toArray(libs);
2253                return libs;
2254            }
2255        }
2256        return null;
2257    }
2258
2259    @Override
2260    public FeatureInfo[] getSystemAvailableFeatures() {
2261        Collection<FeatureInfo> featSet;
2262        synchronized (mPackages) {
2263            featSet = mAvailableFeatures.values();
2264            int size = featSet.size();
2265            if (size > 0) {
2266                FeatureInfo[] features = new FeatureInfo[size+1];
2267                featSet.toArray(features);
2268                FeatureInfo fi = new FeatureInfo();
2269                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2270                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2271                features[size] = fi;
2272                return features;
2273            }
2274        }
2275        return null;
2276    }
2277
2278    @Override
2279    public boolean hasSystemFeature(String name) {
2280        synchronized (mPackages) {
2281            return mAvailableFeatures.containsKey(name);
2282        }
2283    }
2284
2285    private void checkValidCaller(int uid, int userId) {
2286        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2287            return;
2288
2289        throw new SecurityException("Caller uid=" + uid
2290                + " is not privileged to communicate with user=" + userId);
2291    }
2292
2293    @Override
2294    public int checkPermission(String permName, String pkgName) {
2295        synchronized (mPackages) {
2296            PackageParser.Package p = mPackages.get(pkgName);
2297            if (p != null && p.mExtras != null) {
2298                PackageSetting ps = (PackageSetting)p.mExtras;
2299                if (ps.sharedUser != null) {
2300                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2301                        return PackageManager.PERMISSION_GRANTED;
2302                    }
2303                } else if (ps.grantedPermissions.contains(permName)) {
2304                    return PackageManager.PERMISSION_GRANTED;
2305                }
2306            }
2307        }
2308        return PackageManager.PERMISSION_DENIED;
2309    }
2310
2311    @Override
2312    public int checkUidPermission(String permName, int uid) {
2313        synchronized (mPackages) {
2314            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2315            if (obj != null) {
2316                GrantedPermissions gp = (GrantedPermissions)obj;
2317                if (gp.grantedPermissions.contains(permName)) {
2318                    return PackageManager.PERMISSION_GRANTED;
2319                }
2320            } else {
2321                HashSet<String> perms = mSystemPermissions.get(uid);
2322                if (perms != null && perms.contains(permName)) {
2323                    return PackageManager.PERMISSION_GRANTED;
2324                }
2325            }
2326        }
2327        return PackageManager.PERMISSION_DENIED;
2328    }
2329
2330    /**
2331     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2332     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2333     * @param checkShell TODO(yamasani):
2334     * @param message the message to log on security exception
2335     */
2336    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2337            boolean checkShell, String message) {
2338        if (userId < 0) {
2339            throw new IllegalArgumentException("Invalid userId " + userId);
2340        }
2341        if (checkShell) {
2342            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2343        }
2344        if (userId == UserHandle.getUserId(callingUid)) return;
2345        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2346            if (requireFullPermission) {
2347                mContext.enforceCallingOrSelfPermission(
2348                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2349            } else {
2350                try {
2351                    mContext.enforceCallingOrSelfPermission(
2352                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2353                } catch (SecurityException se) {
2354                    mContext.enforceCallingOrSelfPermission(
2355                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2356                }
2357            }
2358        }
2359    }
2360
2361    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2362        if (callingUid == Process.SHELL_UID) {
2363            if (userHandle >= 0
2364                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2365                throw new SecurityException("Shell does not have permission to access user "
2366                        + userHandle);
2367            } else if (userHandle < 0) {
2368                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2369                        + Debug.getCallers(3));
2370            }
2371        }
2372    }
2373
2374    private BasePermission findPermissionTreeLP(String permName) {
2375        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2376            if (permName.startsWith(bp.name) &&
2377                    permName.length() > bp.name.length() &&
2378                    permName.charAt(bp.name.length()) == '.') {
2379                return bp;
2380            }
2381        }
2382        return null;
2383    }
2384
2385    private BasePermission checkPermissionTreeLP(String permName) {
2386        if (permName != null) {
2387            BasePermission bp = findPermissionTreeLP(permName);
2388            if (bp != null) {
2389                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2390                    return bp;
2391                }
2392                throw new SecurityException("Calling uid "
2393                        + Binder.getCallingUid()
2394                        + " is not allowed to add to permission tree "
2395                        + bp.name + " owned by uid " + bp.uid);
2396            }
2397        }
2398        throw new SecurityException("No permission tree found for " + permName);
2399    }
2400
2401    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2402        if (s1 == null) {
2403            return s2 == null;
2404        }
2405        if (s2 == null) {
2406            return false;
2407        }
2408        if (s1.getClass() != s2.getClass()) {
2409            return false;
2410        }
2411        return s1.equals(s2);
2412    }
2413
2414    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2415        if (pi1.icon != pi2.icon) return false;
2416        if (pi1.logo != pi2.logo) return false;
2417        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2418        if (!compareStrings(pi1.name, pi2.name)) return false;
2419        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2420        // We'll take care of setting this one.
2421        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2422        // These are not currently stored in settings.
2423        //if (!compareStrings(pi1.group, pi2.group)) return false;
2424        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2425        //if (pi1.labelRes != pi2.labelRes) return false;
2426        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2427        return true;
2428    }
2429
2430    int permissionInfoFootprint(PermissionInfo info) {
2431        int size = info.name.length();
2432        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2433        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2434        return size;
2435    }
2436
2437    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2438        int size = 0;
2439        for (BasePermission perm : mSettings.mPermissions.values()) {
2440            if (perm.uid == tree.uid) {
2441                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2442            }
2443        }
2444        return size;
2445    }
2446
2447    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2448        // We calculate the max size of permissions defined by this uid and throw
2449        // if that plus the size of 'info' would exceed our stated maximum.
2450        if (tree.uid != Process.SYSTEM_UID) {
2451            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2452            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2453                throw new SecurityException("Permission tree size cap exceeded");
2454            }
2455        }
2456    }
2457
2458    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2459        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2460            throw new SecurityException("Label must be specified in permission");
2461        }
2462        BasePermission tree = checkPermissionTreeLP(info.name);
2463        BasePermission bp = mSettings.mPermissions.get(info.name);
2464        boolean added = bp == null;
2465        boolean changed = true;
2466        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2467        if (added) {
2468            enforcePermissionCapLocked(info, tree);
2469            bp = new BasePermission(info.name, tree.sourcePackage,
2470                    BasePermission.TYPE_DYNAMIC);
2471        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2472            throw new SecurityException(
2473                    "Not allowed to modify non-dynamic permission "
2474                    + info.name);
2475        } else {
2476            if (bp.protectionLevel == fixedLevel
2477                    && bp.perm.owner.equals(tree.perm.owner)
2478                    && bp.uid == tree.uid
2479                    && comparePermissionInfos(bp.perm.info, info)) {
2480                changed = false;
2481            }
2482        }
2483        bp.protectionLevel = fixedLevel;
2484        info = new PermissionInfo(info);
2485        info.protectionLevel = fixedLevel;
2486        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2487        bp.perm.info.packageName = tree.perm.info.packageName;
2488        bp.uid = tree.uid;
2489        if (added) {
2490            mSettings.mPermissions.put(info.name, bp);
2491        }
2492        if (changed) {
2493            if (!async) {
2494                mSettings.writeLPr();
2495            } else {
2496                scheduleWriteSettingsLocked();
2497            }
2498        }
2499        return added;
2500    }
2501
2502    @Override
2503    public boolean addPermission(PermissionInfo info) {
2504        synchronized (mPackages) {
2505            return addPermissionLocked(info, false);
2506        }
2507    }
2508
2509    @Override
2510    public boolean addPermissionAsync(PermissionInfo info) {
2511        synchronized (mPackages) {
2512            return addPermissionLocked(info, true);
2513        }
2514    }
2515
2516    @Override
2517    public void removePermission(String name) {
2518        synchronized (mPackages) {
2519            checkPermissionTreeLP(name);
2520            BasePermission bp = mSettings.mPermissions.get(name);
2521            if (bp != null) {
2522                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2523                    throw new SecurityException(
2524                            "Not allowed to modify non-dynamic permission "
2525                            + name);
2526                }
2527                mSettings.mPermissions.remove(name);
2528                mSettings.writeLPr();
2529            }
2530        }
2531    }
2532
2533    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2534        int index = pkg.requestedPermissions.indexOf(bp.name);
2535        if (index == -1) {
2536            throw new SecurityException("Package " + pkg.packageName
2537                    + " has not requested permission " + bp.name);
2538        }
2539        boolean isNormal =
2540                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2541                        == PermissionInfo.PROTECTION_NORMAL);
2542        boolean isDangerous =
2543                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2544                        == PermissionInfo.PROTECTION_DANGEROUS);
2545        boolean isDevelopment =
2546                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2547
2548        if (!isNormal && !isDangerous && !isDevelopment) {
2549            throw new SecurityException("Permission " + bp.name
2550                    + " is not a changeable permission type");
2551        }
2552
2553        if (isNormal || isDangerous) {
2554            if (pkg.requestedPermissionsRequired.get(index)) {
2555                throw new SecurityException("Can't change " + bp.name
2556                        + ". It is required by the application");
2557            }
2558        }
2559    }
2560
2561    @Override
2562    public void grantPermission(String packageName, String permissionName) {
2563        mContext.enforceCallingOrSelfPermission(
2564                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2565        synchronized (mPackages) {
2566            final PackageParser.Package pkg = mPackages.get(packageName);
2567            if (pkg == null) {
2568                throw new IllegalArgumentException("Unknown package: " + packageName);
2569            }
2570            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2571            if (bp == null) {
2572                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2573            }
2574
2575            checkGrantRevokePermissions(pkg, bp);
2576
2577            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2578            if (ps == null) {
2579                return;
2580            }
2581            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2582            if (gp.grantedPermissions.add(permissionName)) {
2583                if (ps.haveGids) {
2584                    gp.gids = appendInts(gp.gids, bp.gids);
2585                }
2586                mSettings.writeLPr();
2587            }
2588        }
2589    }
2590
2591    @Override
2592    public void revokePermission(String packageName, String permissionName) {
2593        int changedAppId = -1;
2594
2595        synchronized (mPackages) {
2596            final PackageParser.Package pkg = mPackages.get(packageName);
2597            if (pkg == null) {
2598                throw new IllegalArgumentException("Unknown package: " + packageName);
2599            }
2600            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2601                mContext.enforceCallingOrSelfPermission(
2602                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2603            }
2604            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2605            if (bp == null) {
2606                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2607            }
2608
2609            checkGrantRevokePermissions(pkg, bp);
2610
2611            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2612            if (ps == null) {
2613                return;
2614            }
2615            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2616            if (gp.grantedPermissions.remove(permissionName)) {
2617                gp.grantedPermissions.remove(permissionName);
2618                if (ps.haveGids) {
2619                    gp.gids = removeInts(gp.gids, bp.gids);
2620                }
2621                mSettings.writeLPr();
2622                changedAppId = ps.appId;
2623            }
2624        }
2625
2626        if (changedAppId >= 0) {
2627            // We changed the perm on someone, kill its processes.
2628            IActivityManager am = ActivityManagerNative.getDefault();
2629            if (am != null) {
2630                final int callingUserId = UserHandle.getCallingUserId();
2631                final long ident = Binder.clearCallingIdentity();
2632                try {
2633                    //XXX we should only revoke for the calling user's app permissions,
2634                    // but for now we impact all users.
2635                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2636                    //        "revoke " + permissionName);
2637                    int[] users = sUserManager.getUserIds();
2638                    for (int user : users) {
2639                        am.killUid(UserHandle.getUid(user, changedAppId),
2640                                "revoke " + permissionName);
2641                    }
2642                } catch (RemoteException e) {
2643                } finally {
2644                    Binder.restoreCallingIdentity(ident);
2645                }
2646            }
2647        }
2648    }
2649
2650    @Override
2651    public boolean isProtectedBroadcast(String actionName) {
2652        synchronized (mPackages) {
2653            return mProtectedBroadcasts.contains(actionName);
2654        }
2655    }
2656
2657    @Override
2658    public int checkSignatures(String pkg1, String pkg2) {
2659        synchronized (mPackages) {
2660            final PackageParser.Package p1 = mPackages.get(pkg1);
2661            final PackageParser.Package p2 = mPackages.get(pkg2);
2662            if (p1 == null || p1.mExtras == null
2663                    || p2 == null || p2.mExtras == null) {
2664                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2665            }
2666            return compareSignatures(p1.mSignatures, p2.mSignatures);
2667        }
2668    }
2669
2670    @Override
2671    public int checkUidSignatures(int uid1, int uid2) {
2672        // Map to base uids.
2673        uid1 = UserHandle.getAppId(uid1);
2674        uid2 = UserHandle.getAppId(uid2);
2675        // reader
2676        synchronized (mPackages) {
2677            Signature[] s1;
2678            Signature[] s2;
2679            Object obj = mSettings.getUserIdLPr(uid1);
2680            if (obj != null) {
2681                if (obj instanceof SharedUserSetting) {
2682                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2683                } else if (obj instanceof PackageSetting) {
2684                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2685                } else {
2686                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2687                }
2688            } else {
2689                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2690            }
2691            obj = mSettings.getUserIdLPr(uid2);
2692            if (obj != null) {
2693                if (obj instanceof SharedUserSetting) {
2694                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2695                } else if (obj instanceof PackageSetting) {
2696                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2697                } else {
2698                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2699                }
2700            } else {
2701                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2702            }
2703            return compareSignatures(s1, s2);
2704        }
2705    }
2706
2707    /**
2708     * Compares two sets of signatures. Returns:
2709     * <br />
2710     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2711     * <br />
2712     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2713     * <br />
2714     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2715     * <br />
2716     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2717     * <br />
2718     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2719     */
2720    static int compareSignatures(Signature[] s1, Signature[] s2) {
2721        if (s1 == null) {
2722            return s2 == null
2723                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2724                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2725        }
2726
2727        if (s2 == null) {
2728            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2729        }
2730
2731        if (s1.length != s2.length) {
2732            return PackageManager.SIGNATURE_NO_MATCH;
2733        }
2734
2735        // Since both signature sets are of size 1, we can compare without HashSets.
2736        if (s1.length == 1) {
2737            return s1[0].equals(s2[0]) ?
2738                    PackageManager.SIGNATURE_MATCH :
2739                    PackageManager.SIGNATURE_NO_MATCH;
2740        }
2741
2742        HashSet<Signature> set1 = new HashSet<Signature>();
2743        for (Signature sig : s1) {
2744            set1.add(sig);
2745        }
2746        HashSet<Signature> set2 = new HashSet<Signature>();
2747        for (Signature sig : s2) {
2748            set2.add(sig);
2749        }
2750        // Make sure s2 contains all signatures in s1.
2751        if (set1.equals(set2)) {
2752            return PackageManager.SIGNATURE_MATCH;
2753        }
2754        return PackageManager.SIGNATURE_NO_MATCH;
2755    }
2756
2757    /**
2758     * If the database version for this type of package (internal storage or
2759     * external storage) is less than the version where package signatures
2760     * were updated, return true.
2761     */
2762    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2763        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2764                DatabaseVersion.SIGNATURE_END_ENTITY))
2765                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2766                        DatabaseVersion.SIGNATURE_END_ENTITY));
2767    }
2768
2769    /**
2770     * Used for backward compatibility to make sure any packages with
2771     * certificate chains get upgraded to the new style. {@code existingSigs}
2772     * will be in the old format (since they were stored on disk from before the
2773     * system upgrade) and {@code scannedSigs} will be in the newer format.
2774     */
2775    private int compareSignaturesCompat(PackageSignatures existingSigs,
2776            PackageParser.Package scannedPkg) {
2777        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2778            return PackageManager.SIGNATURE_NO_MATCH;
2779        }
2780
2781        HashSet<Signature> existingSet = new HashSet<Signature>();
2782        for (Signature sig : existingSigs.mSignatures) {
2783            existingSet.add(sig);
2784        }
2785        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2786        for (Signature sig : scannedPkg.mSignatures) {
2787            try {
2788                Signature[] chainSignatures = sig.getChainSignatures();
2789                for (Signature chainSig : chainSignatures) {
2790                    scannedCompatSet.add(chainSig);
2791                }
2792            } catch (CertificateEncodingException e) {
2793                scannedCompatSet.add(sig);
2794            }
2795        }
2796        /*
2797         * Make sure the expanded scanned set contains all signatures in the
2798         * existing one.
2799         */
2800        if (scannedCompatSet.equals(existingSet)) {
2801            // Migrate the old signatures to the new scheme.
2802            existingSigs.assignSignatures(scannedPkg.mSignatures);
2803            // The new KeySets will be re-added later in the scanning process.
2804            synchronized (mPackages) {
2805                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2806            }
2807            return PackageManager.SIGNATURE_MATCH;
2808        }
2809        return PackageManager.SIGNATURE_NO_MATCH;
2810    }
2811
2812    @Override
2813    public String[] getPackagesForUid(int uid) {
2814        uid = UserHandle.getAppId(uid);
2815        // reader
2816        synchronized (mPackages) {
2817            Object obj = mSettings.getUserIdLPr(uid);
2818            if (obj instanceof SharedUserSetting) {
2819                final SharedUserSetting sus = (SharedUserSetting) obj;
2820                final int N = sus.packages.size();
2821                final String[] res = new String[N];
2822                final Iterator<PackageSetting> it = sus.packages.iterator();
2823                int i = 0;
2824                while (it.hasNext()) {
2825                    res[i++] = it.next().name;
2826                }
2827                return res;
2828            } else if (obj instanceof PackageSetting) {
2829                final PackageSetting ps = (PackageSetting) obj;
2830                return new String[] { ps.name };
2831            }
2832        }
2833        return null;
2834    }
2835
2836    @Override
2837    public String getNameForUid(int uid) {
2838        // reader
2839        synchronized (mPackages) {
2840            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2841            if (obj instanceof SharedUserSetting) {
2842                final SharedUserSetting sus = (SharedUserSetting) obj;
2843                return sus.name + ":" + sus.userId;
2844            } else if (obj instanceof PackageSetting) {
2845                final PackageSetting ps = (PackageSetting) obj;
2846                return ps.name;
2847            }
2848        }
2849        return null;
2850    }
2851
2852    @Override
2853    public int getUidForSharedUser(String sharedUserName) {
2854        if(sharedUserName == null) {
2855            return -1;
2856        }
2857        // reader
2858        synchronized (mPackages) {
2859            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2860            if (suid == null) {
2861                return -1;
2862            }
2863            return suid.userId;
2864        }
2865    }
2866
2867    @Override
2868    public int getFlagsForUid(int uid) {
2869        synchronized (mPackages) {
2870            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2871            if (obj instanceof SharedUserSetting) {
2872                final SharedUserSetting sus = (SharedUserSetting) obj;
2873                return sus.pkgFlags;
2874            } else if (obj instanceof PackageSetting) {
2875                final PackageSetting ps = (PackageSetting) obj;
2876                return ps.pkgFlags;
2877            }
2878        }
2879        return 0;
2880    }
2881
2882    @Override
2883    public boolean isUidPrivileged(int uid) {
2884        uid = UserHandle.getAppId(uid);
2885        // reader
2886        synchronized (mPackages) {
2887            Object obj = mSettings.getUserIdLPr(uid);
2888            if (obj instanceof SharedUserSetting) {
2889                final SharedUserSetting sus = (SharedUserSetting) obj;
2890                final Iterator<PackageSetting> it = sus.packages.iterator();
2891                while (it.hasNext()) {
2892                    if (it.next().isPrivileged()) {
2893                        return true;
2894                    }
2895                }
2896            } else if (obj instanceof PackageSetting) {
2897                final PackageSetting ps = (PackageSetting) obj;
2898                return ps.isPrivileged();
2899            }
2900        }
2901        return false;
2902    }
2903
2904    @Override
2905    public String[] getAppOpPermissionPackages(String permissionName) {
2906        synchronized (mPackages) {
2907            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2908            if (pkgs == null) {
2909                return null;
2910            }
2911            return pkgs.toArray(new String[pkgs.size()]);
2912        }
2913    }
2914
2915    @Override
2916    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2917            int flags, int userId) {
2918        if (!sUserManager.exists(userId)) return null;
2919        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
2920        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2921        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2922    }
2923
2924    @Override
2925    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2926            IntentFilter filter, int match, ComponentName activity) {
2927        final int userId = UserHandle.getCallingUserId();
2928        if (DEBUG_PREFERRED) {
2929            Log.v(TAG, "setLastChosenActivity intent=" + intent
2930                + " resolvedType=" + resolvedType
2931                + " flags=" + flags
2932                + " filter=" + filter
2933                + " match=" + match
2934                + " activity=" + activity);
2935            filter.dump(new PrintStreamPrinter(System.out), "    ");
2936        }
2937        intent.setComponent(null);
2938        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2939        // Find any earlier preferred or last chosen entries and nuke them
2940        findPreferredActivity(intent, resolvedType,
2941                flags, query, 0, false, true, false, userId);
2942        // Add the new activity as the last chosen for this filter
2943        addPreferredActivityInternal(filter, match, null, activity, false, userId,
2944                "Setting last chosen");
2945    }
2946
2947    @Override
2948    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2949        final int userId = UserHandle.getCallingUserId();
2950        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2951        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2952        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2953                false, false, false, userId);
2954    }
2955
2956    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2957            int flags, List<ResolveInfo> query, int userId) {
2958        if (query != null) {
2959            final int N = query.size();
2960            if (N == 1) {
2961                return query.get(0);
2962            } else if (N > 1) {
2963                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2964                // If there is more than one activity with the same priority,
2965                // then let the user decide between them.
2966                ResolveInfo r0 = query.get(0);
2967                ResolveInfo r1 = query.get(1);
2968                if (DEBUG_INTENT_MATCHING || debug) {
2969                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2970                            + r1.activityInfo.name + "=" + r1.priority);
2971                }
2972                // If the first activity has a higher priority, or a different
2973                // default, then it is always desireable to pick it.
2974                if (r0.priority != r1.priority
2975                        || r0.preferredOrder != r1.preferredOrder
2976                        || r0.isDefault != r1.isDefault) {
2977                    return query.get(0);
2978                }
2979                // If we have saved a preference for a preferred activity for
2980                // this Intent, use that.
2981                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2982                        flags, query, r0.priority, true, false, debug, userId);
2983                if (ri != null) {
2984                    return ri;
2985                }
2986                if (userId != 0) {
2987                    ri = new ResolveInfo(mResolveInfo);
2988                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2989                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2990                            ri.activityInfo.applicationInfo);
2991                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2992                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2993                    return ri;
2994                }
2995                return mResolveInfo;
2996            }
2997        }
2998        return null;
2999    }
3000
3001    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3002            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3003        final int N = query.size();
3004        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3005                .get(userId);
3006        // Get the list of persistent preferred activities that handle the intent
3007        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3008        List<PersistentPreferredActivity> pprefs = ppir != null
3009                ? ppir.queryIntent(intent, resolvedType,
3010                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3011                : null;
3012        if (pprefs != null && pprefs.size() > 0) {
3013            final int M = pprefs.size();
3014            for (int i=0; i<M; i++) {
3015                final PersistentPreferredActivity ppa = pprefs.get(i);
3016                if (DEBUG_PREFERRED || debug) {
3017                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3018                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3019                            + "\n  component=" + ppa.mComponent);
3020                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3021                }
3022                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3023                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3024                if (DEBUG_PREFERRED || debug) {
3025                    Slog.v(TAG, "Found persistent preferred activity:");
3026                    if (ai != null) {
3027                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3028                    } else {
3029                        Slog.v(TAG, "  null");
3030                    }
3031                }
3032                if (ai == null) {
3033                    // This previously registered persistent preferred activity
3034                    // component is no longer known. Ignore it and do NOT remove it.
3035                    continue;
3036                }
3037                for (int j=0; j<N; j++) {
3038                    final ResolveInfo ri = query.get(j);
3039                    if (!ri.activityInfo.applicationInfo.packageName
3040                            .equals(ai.applicationInfo.packageName)) {
3041                        continue;
3042                    }
3043                    if (!ri.activityInfo.name.equals(ai.name)) {
3044                        continue;
3045                    }
3046                    //  Found a persistent preference that can handle the intent.
3047                    if (DEBUG_PREFERRED || debug) {
3048                        Slog.v(TAG, "Returning persistent preferred activity: " +
3049                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3050                    }
3051                    return ri;
3052                }
3053            }
3054        }
3055        return null;
3056    }
3057
3058    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3059            List<ResolveInfo> query, int priority, boolean always,
3060            boolean removeMatches, boolean debug, int userId) {
3061        if (!sUserManager.exists(userId)) return null;
3062        // writer
3063        synchronized (mPackages) {
3064            if (intent.getSelector() != null) {
3065                intent = intent.getSelector();
3066            }
3067            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3068
3069            // Try to find a matching persistent preferred activity.
3070            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3071                    debug, userId);
3072
3073            // If a persistent preferred activity matched, use it.
3074            if (pri != null) {
3075                return pri;
3076            }
3077
3078            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3079            // Get the list of preferred activities that handle the intent
3080            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3081            List<PreferredActivity> prefs = pir != null
3082                    ? pir.queryIntent(intent, resolvedType,
3083                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3084                    : null;
3085            if (prefs != null && prefs.size() > 0) {
3086                boolean changed = false;
3087                try {
3088                    // First figure out how good the original match set is.
3089                    // We will only allow preferred activities that came
3090                    // from the same match quality.
3091                    int match = 0;
3092
3093                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3094
3095                    final int N = query.size();
3096                    for (int j=0; j<N; j++) {
3097                        final ResolveInfo ri = query.get(j);
3098                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3099                                + ": 0x" + Integer.toHexString(match));
3100                        if (ri.match > match) {
3101                            match = ri.match;
3102                        }
3103                    }
3104
3105                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3106                            + Integer.toHexString(match));
3107
3108                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3109                    final int M = prefs.size();
3110                    for (int i=0; i<M; i++) {
3111                        final PreferredActivity pa = prefs.get(i);
3112                        if (DEBUG_PREFERRED || debug) {
3113                            Slog.v(TAG, "Checking PreferredActivity ds="
3114                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3115                                    + "\n  component=" + pa.mPref.mComponent);
3116                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3117                        }
3118                        if (pa.mPref.mMatch != match) {
3119                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3120                                    + Integer.toHexString(pa.mPref.mMatch));
3121                            continue;
3122                        }
3123                        // If it's not an "always" type preferred activity and that's what we're
3124                        // looking for, skip it.
3125                        if (always && !pa.mPref.mAlways) {
3126                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3127                            continue;
3128                        }
3129                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3130                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3131                        if (DEBUG_PREFERRED || debug) {
3132                            Slog.v(TAG, "Found preferred activity:");
3133                            if (ai != null) {
3134                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3135                            } else {
3136                                Slog.v(TAG, "  null");
3137                            }
3138                        }
3139                        if (ai == null) {
3140                            // This previously registered preferred activity
3141                            // component is no longer known.  Most likely an update
3142                            // to the app was installed and in the new version this
3143                            // component no longer exists.  Clean it up by removing
3144                            // it from the preferred activities list, and skip it.
3145                            Slog.w(TAG, "Removing dangling preferred activity: "
3146                                    + pa.mPref.mComponent);
3147                            pir.removeFilter(pa);
3148                            changed = true;
3149                            continue;
3150                        }
3151                        for (int j=0; j<N; j++) {
3152                            final ResolveInfo ri = query.get(j);
3153                            if (!ri.activityInfo.applicationInfo.packageName
3154                                    .equals(ai.applicationInfo.packageName)) {
3155                                continue;
3156                            }
3157                            if (!ri.activityInfo.name.equals(ai.name)) {
3158                                continue;
3159                            }
3160
3161                            if (removeMatches) {
3162                                pir.removeFilter(pa);
3163                                changed = true;
3164                                if (DEBUG_PREFERRED) {
3165                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3166                                }
3167                                break;
3168                            }
3169
3170                            // Okay we found a previously set preferred or last chosen app.
3171                            // If the result set is different from when this
3172                            // was created, we need to clear it and re-ask the
3173                            // user their preference, if we're looking for an "always" type entry.
3174                            if (always && !pa.mPref.sameSet(query, priority)) {
3175                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3176                                        + intent + " type " + resolvedType);
3177                                if (DEBUG_PREFERRED) {
3178                                    Slog.v(TAG, "Removing preferred activity since set changed "
3179                                            + pa.mPref.mComponent);
3180                                }
3181                                pir.removeFilter(pa);
3182                                // Re-add the filter as a "last chosen" entry (!always)
3183                                PreferredActivity lastChosen = new PreferredActivity(
3184                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3185                                pir.addFilter(lastChosen);
3186                                changed = true;
3187                                return null;
3188                            }
3189
3190                            // Yay! Either the set matched or we're looking for the last chosen
3191                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3192                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3193                            return ri;
3194                        }
3195                    }
3196                } finally {
3197                    if (changed) {
3198                        if (DEBUG_PREFERRED) {
3199                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3200                        }
3201                        mSettings.writePackageRestrictionsLPr(userId);
3202                    }
3203                }
3204            }
3205        }
3206        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3207        return null;
3208    }
3209
3210    /*
3211     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3212     */
3213    @Override
3214    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3215            int targetUserId) {
3216        mContext.enforceCallingOrSelfPermission(
3217                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3218        List<CrossProfileIntentFilter> matches =
3219                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3220        if (matches != null) {
3221            int size = matches.size();
3222            for (int i = 0; i < size; i++) {
3223                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3224            }
3225        }
3226        return false;
3227    }
3228
3229    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3230            String resolvedType, int userId) {
3231        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3232        if (resolver != null) {
3233            return resolver.queryIntent(intent, resolvedType, false, userId);
3234        }
3235        return null;
3236    }
3237
3238    @Override
3239    public List<ResolveInfo> queryIntentActivities(Intent intent,
3240            String resolvedType, int flags, int userId) {
3241        if (!sUserManager.exists(userId)) return Collections.emptyList();
3242        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3243        ComponentName comp = intent.getComponent();
3244        if (comp == null) {
3245            if (intent.getSelector() != null) {
3246                intent = intent.getSelector();
3247                comp = intent.getComponent();
3248            }
3249        }
3250
3251        if (comp != null) {
3252            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3253            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3254            if (ai != null) {
3255                final ResolveInfo ri = new ResolveInfo();
3256                ri.activityInfo = ai;
3257                list.add(ri);
3258            }
3259            return list;
3260        }
3261
3262        // reader
3263        synchronized (mPackages) {
3264            final String pkgName = intent.getPackage();
3265            if (pkgName == null) {
3266                List<CrossProfileIntentFilter> matchingFilters =
3267                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3268                // Check for results that need to skip the current profile.
3269                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3270                        resolvedType, flags, userId);
3271                if (resolveInfo != null) {
3272                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3273                    result.add(resolveInfo);
3274                    return result;
3275                }
3276                // Check for cross profile results.
3277                resolveInfo = queryCrossProfileIntents(
3278                        matchingFilters, intent, resolvedType, flags, userId);
3279
3280                // Check for results in the current profile.
3281                List<ResolveInfo> result = mActivities.queryIntent(
3282                        intent, resolvedType, flags, userId);
3283                if (resolveInfo != null) {
3284                    result.add(resolveInfo);
3285                    Collections.sort(result, mResolvePrioritySorter);
3286                }
3287                return result;
3288            }
3289            final PackageParser.Package pkg = mPackages.get(pkgName);
3290            if (pkg != null) {
3291                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3292                        pkg.activities, userId);
3293            }
3294            return new ArrayList<ResolveInfo>();
3295        }
3296    }
3297
3298    private ResolveInfo querySkipCurrentProfileIntents(
3299            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3300            int flags, int sourceUserId) {
3301        if (matchingFilters != null) {
3302            int size = matchingFilters.size();
3303            for (int i = 0; i < size; i ++) {
3304                CrossProfileIntentFilter filter = matchingFilters.get(i);
3305                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3306                    // Checking if there are activities in the target user that can handle the
3307                    // intent.
3308                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3309                            flags, sourceUserId);
3310                    if (resolveInfo != null) {
3311                        return resolveInfo;
3312                    }
3313                }
3314            }
3315        }
3316        return null;
3317    }
3318
3319    // Return matching ResolveInfo if any for skip current profile intent filters.
3320    private ResolveInfo queryCrossProfileIntents(
3321            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3322            int flags, int sourceUserId) {
3323        if (matchingFilters != null) {
3324            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3325            // match the same intent. For performance reasons, it is better not to
3326            // run queryIntent twice for the same userId
3327            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3328            int size = matchingFilters.size();
3329            for (int i = 0; i < size; i++) {
3330                CrossProfileIntentFilter filter = matchingFilters.get(i);
3331                int targetUserId = filter.getTargetUserId();
3332                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3333                        && !alreadyTriedUserIds.get(targetUserId)) {
3334                    // Checking if there are activities in the target user that can handle the
3335                    // intent.
3336                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3337                            flags, sourceUserId);
3338                    if (resolveInfo != null) return resolveInfo;
3339                    alreadyTriedUserIds.put(targetUserId, true);
3340                }
3341            }
3342        }
3343        return null;
3344    }
3345
3346    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3347            String resolvedType, int flags, int sourceUserId) {
3348        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3349                resolvedType, flags, filter.getTargetUserId());
3350        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3351            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3352        }
3353        return null;
3354    }
3355
3356    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3357            int sourceUserId, int targetUserId) {
3358        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3359        String className;
3360        if (targetUserId == UserHandle.USER_OWNER) {
3361            className = FORWARD_INTENT_TO_USER_OWNER;
3362        } else {
3363            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3364        }
3365        ComponentName forwardingActivityComponentName = new ComponentName(
3366                mAndroidApplication.packageName, className);
3367        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3368                sourceUserId);
3369        if (targetUserId == UserHandle.USER_OWNER) {
3370            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3371            forwardingResolveInfo.noResourceId = true;
3372        }
3373        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3374        forwardingResolveInfo.priority = 0;
3375        forwardingResolveInfo.preferredOrder = 0;
3376        forwardingResolveInfo.match = 0;
3377        forwardingResolveInfo.isDefault = true;
3378        forwardingResolveInfo.filter = filter;
3379        forwardingResolveInfo.targetUserId = targetUserId;
3380        return forwardingResolveInfo;
3381    }
3382
3383    @Override
3384    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3385            Intent[] specifics, String[] specificTypes, Intent intent,
3386            String resolvedType, int flags, int userId) {
3387        if (!sUserManager.exists(userId)) return Collections.emptyList();
3388        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3389                false, "query intent activity options");
3390        final String resultsAction = intent.getAction();
3391
3392        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3393                | PackageManager.GET_RESOLVED_FILTER, userId);
3394
3395        if (DEBUG_INTENT_MATCHING) {
3396            Log.v(TAG, "Query " + intent + ": " + results);
3397        }
3398
3399        int specificsPos = 0;
3400        int N;
3401
3402        // todo: note that the algorithm used here is O(N^2).  This
3403        // isn't a problem in our current environment, but if we start running
3404        // into situations where we have more than 5 or 10 matches then this
3405        // should probably be changed to something smarter...
3406
3407        // First we go through and resolve each of the specific items
3408        // that were supplied, taking care of removing any corresponding
3409        // duplicate items in the generic resolve list.
3410        if (specifics != null) {
3411            for (int i=0; i<specifics.length; i++) {
3412                final Intent sintent = specifics[i];
3413                if (sintent == null) {
3414                    continue;
3415                }
3416
3417                if (DEBUG_INTENT_MATCHING) {
3418                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3419                }
3420
3421                String action = sintent.getAction();
3422                if (resultsAction != null && resultsAction.equals(action)) {
3423                    // If this action was explicitly requested, then don't
3424                    // remove things that have it.
3425                    action = null;
3426                }
3427
3428                ResolveInfo ri = null;
3429                ActivityInfo ai = null;
3430
3431                ComponentName comp = sintent.getComponent();
3432                if (comp == null) {
3433                    ri = resolveIntent(
3434                        sintent,
3435                        specificTypes != null ? specificTypes[i] : null,
3436                            flags, userId);
3437                    if (ri == null) {
3438                        continue;
3439                    }
3440                    if (ri == mResolveInfo) {
3441                        // ACK!  Must do something better with this.
3442                    }
3443                    ai = ri.activityInfo;
3444                    comp = new ComponentName(ai.applicationInfo.packageName,
3445                            ai.name);
3446                } else {
3447                    ai = getActivityInfo(comp, flags, userId);
3448                    if (ai == null) {
3449                        continue;
3450                    }
3451                }
3452
3453                // Look for any generic query activities that are duplicates
3454                // of this specific one, and remove them from the results.
3455                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3456                N = results.size();
3457                int j;
3458                for (j=specificsPos; j<N; j++) {
3459                    ResolveInfo sri = results.get(j);
3460                    if ((sri.activityInfo.name.equals(comp.getClassName())
3461                            && sri.activityInfo.applicationInfo.packageName.equals(
3462                                    comp.getPackageName()))
3463                        || (action != null && sri.filter.matchAction(action))) {
3464                        results.remove(j);
3465                        if (DEBUG_INTENT_MATCHING) Log.v(
3466                            TAG, "Removing duplicate item from " + j
3467                            + " due to specific " + specificsPos);
3468                        if (ri == null) {
3469                            ri = sri;
3470                        }
3471                        j--;
3472                        N--;
3473                    }
3474                }
3475
3476                // Add this specific item to its proper place.
3477                if (ri == null) {
3478                    ri = new ResolveInfo();
3479                    ri.activityInfo = ai;
3480                }
3481                results.add(specificsPos, ri);
3482                ri.specificIndex = i;
3483                specificsPos++;
3484            }
3485        }
3486
3487        // Now we go through the remaining generic results and remove any
3488        // duplicate actions that are found here.
3489        N = results.size();
3490        for (int i=specificsPos; i<N-1; i++) {
3491            final ResolveInfo rii = results.get(i);
3492            if (rii.filter == null) {
3493                continue;
3494            }
3495
3496            // Iterate over all of the actions of this result's intent
3497            // filter...  typically this should be just one.
3498            final Iterator<String> it = rii.filter.actionsIterator();
3499            if (it == null) {
3500                continue;
3501            }
3502            while (it.hasNext()) {
3503                final String action = it.next();
3504                if (resultsAction != null && resultsAction.equals(action)) {
3505                    // If this action was explicitly requested, then don't
3506                    // remove things that have it.
3507                    continue;
3508                }
3509                for (int j=i+1; j<N; j++) {
3510                    final ResolveInfo rij = results.get(j);
3511                    if (rij.filter != null && rij.filter.hasAction(action)) {
3512                        results.remove(j);
3513                        if (DEBUG_INTENT_MATCHING) Log.v(
3514                            TAG, "Removing duplicate item from " + j
3515                            + " due to action " + action + " at " + i);
3516                        j--;
3517                        N--;
3518                    }
3519                }
3520            }
3521
3522            // If the caller didn't request filter information, drop it now
3523            // so we don't have to marshall/unmarshall it.
3524            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3525                rii.filter = null;
3526            }
3527        }
3528
3529        // Filter out the caller activity if so requested.
3530        if (caller != null) {
3531            N = results.size();
3532            for (int i=0; i<N; i++) {
3533                ActivityInfo ainfo = results.get(i).activityInfo;
3534                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3535                        && caller.getClassName().equals(ainfo.name)) {
3536                    results.remove(i);
3537                    break;
3538                }
3539            }
3540        }
3541
3542        // If the caller didn't request filter information,
3543        // drop them now so we don't have to
3544        // marshall/unmarshall it.
3545        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3546            N = results.size();
3547            for (int i=0; i<N; i++) {
3548                results.get(i).filter = null;
3549            }
3550        }
3551
3552        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3553        return results;
3554    }
3555
3556    @Override
3557    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3558            int userId) {
3559        if (!sUserManager.exists(userId)) return Collections.emptyList();
3560        ComponentName comp = intent.getComponent();
3561        if (comp == null) {
3562            if (intent.getSelector() != null) {
3563                intent = intent.getSelector();
3564                comp = intent.getComponent();
3565            }
3566        }
3567        if (comp != null) {
3568            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3569            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3570            if (ai != null) {
3571                ResolveInfo ri = new ResolveInfo();
3572                ri.activityInfo = ai;
3573                list.add(ri);
3574            }
3575            return list;
3576        }
3577
3578        // reader
3579        synchronized (mPackages) {
3580            String pkgName = intent.getPackage();
3581            if (pkgName == null) {
3582                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3583            }
3584            final PackageParser.Package pkg = mPackages.get(pkgName);
3585            if (pkg != null) {
3586                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3587                        userId);
3588            }
3589            return null;
3590        }
3591    }
3592
3593    @Override
3594    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3595        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3596        if (!sUserManager.exists(userId)) return null;
3597        if (query != null) {
3598            if (query.size() >= 1) {
3599                // If there is more than one service with the same priority,
3600                // just arbitrarily pick the first one.
3601                return query.get(0);
3602            }
3603        }
3604        return null;
3605    }
3606
3607    @Override
3608    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3609            int userId) {
3610        if (!sUserManager.exists(userId)) return Collections.emptyList();
3611        ComponentName comp = intent.getComponent();
3612        if (comp == null) {
3613            if (intent.getSelector() != null) {
3614                intent = intent.getSelector();
3615                comp = intent.getComponent();
3616            }
3617        }
3618        if (comp != null) {
3619            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3620            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3621            if (si != null) {
3622                final ResolveInfo ri = new ResolveInfo();
3623                ri.serviceInfo = si;
3624                list.add(ri);
3625            }
3626            return list;
3627        }
3628
3629        // reader
3630        synchronized (mPackages) {
3631            String pkgName = intent.getPackage();
3632            if (pkgName == null) {
3633                return mServices.queryIntent(intent, resolvedType, flags, userId);
3634            }
3635            final PackageParser.Package pkg = mPackages.get(pkgName);
3636            if (pkg != null) {
3637                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3638                        userId);
3639            }
3640            return null;
3641        }
3642    }
3643
3644    @Override
3645    public List<ResolveInfo> queryIntentContentProviders(
3646            Intent intent, String resolvedType, int flags, int userId) {
3647        if (!sUserManager.exists(userId)) return Collections.emptyList();
3648        ComponentName comp = intent.getComponent();
3649        if (comp == null) {
3650            if (intent.getSelector() != null) {
3651                intent = intent.getSelector();
3652                comp = intent.getComponent();
3653            }
3654        }
3655        if (comp != null) {
3656            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3657            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3658            if (pi != null) {
3659                final ResolveInfo ri = new ResolveInfo();
3660                ri.providerInfo = pi;
3661                list.add(ri);
3662            }
3663            return list;
3664        }
3665
3666        // reader
3667        synchronized (mPackages) {
3668            String pkgName = intent.getPackage();
3669            if (pkgName == null) {
3670                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3671            }
3672            final PackageParser.Package pkg = mPackages.get(pkgName);
3673            if (pkg != null) {
3674                return mProviders.queryIntentForPackage(
3675                        intent, resolvedType, flags, pkg.providers, userId);
3676            }
3677            return null;
3678        }
3679    }
3680
3681    @Override
3682    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3683        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3684
3685        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3686
3687        // writer
3688        synchronized (mPackages) {
3689            ArrayList<PackageInfo> list;
3690            if (listUninstalled) {
3691                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3692                for (PackageSetting ps : mSettings.mPackages.values()) {
3693                    PackageInfo pi;
3694                    if (ps.pkg != null) {
3695                        pi = generatePackageInfo(ps.pkg, flags, userId);
3696                    } else {
3697                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3698                    }
3699                    if (pi != null) {
3700                        list.add(pi);
3701                    }
3702                }
3703            } else {
3704                list = new ArrayList<PackageInfo>(mPackages.size());
3705                for (PackageParser.Package p : mPackages.values()) {
3706                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3707                    if (pi != null) {
3708                        list.add(pi);
3709                    }
3710                }
3711            }
3712
3713            return new ParceledListSlice<PackageInfo>(list);
3714        }
3715    }
3716
3717    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3718            String[] permissions, boolean[] tmp, int flags, int userId) {
3719        int numMatch = 0;
3720        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3721        for (int i=0; i<permissions.length; i++) {
3722            if (gp.grantedPermissions.contains(permissions[i])) {
3723                tmp[i] = true;
3724                numMatch++;
3725            } else {
3726                tmp[i] = false;
3727            }
3728        }
3729        if (numMatch == 0) {
3730            return;
3731        }
3732        PackageInfo pi;
3733        if (ps.pkg != null) {
3734            pi = generatePackageInfo(ps.pkg, flags, userId);
3735        } else {
3736            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3737        }
3738        // The above might return null in cases of uninstalled apps or install-state
3739        // skew across users/profiles.
3740        if (pi != null) {
3741            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3742                if (numMatch == permissions.length) {
3743                    pi.requestedPermissions = permissions;
3744                } else {
3745                    pi.requestedPermissions = new String[numMatch];
3746                    numMatch = 0;
3747                    for (int i=0; i<permissions.length; i++) {
3748                        if (tmp[i]) {
3749                            pi.requestedPermissions[numMatch] = permissions[i];
3750                            numMatch++;
3751                        }
3752                    }
3753                }
3754            }
3755            list.add(pi);
3756        }
3757    }
3758
3759    @Override
3760    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3761            String[] permissions, int flags, int userId) {
3762        if (!sUserManager.exists(userId)) return null;
3763        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3764
3765        // writer
3766        synchronized (mPackages) {
3767            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3768            boolean[] tmpBools = new boolean[permissions.length];
3769            if (listUninstalled) {
3770                for (PackageSetting ps : mSettings.mPackages.values()) {
3771                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3772                }
3773            } else {
3774                for (PackageParser.Package pkg : mPackages.values()) {
3775                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3776                    if (ps != null) {
3777                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3778                                userId);
3779                    }
3780                }
3781            }
3782
3783            return new ParceledListSlice<PackageInfo>(list);
3784        }
3785    }
3786
3787    @Override
3788    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3789        if (!sUserManager.exists(userId)) return null;
3790        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3791
3792        // writer
3793        synchronized (mPackages) {
3794            ArrayList<ApplicationInfo> list;
3795            if (listUninstalled) {
3796                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3797                for (PackageSetting ps : mSettings.mPackages.values()) {
3798                    ApplicationInfo ai;
3799                    if (ps.pkg != null) {
3800                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3801                                ps.readUserState(userId), userId);
3802                    } else {
3803                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3804                    }
3805                    if (ai != null) {
3806                        list.add(ai);
3807                    }
3808                }
3809            } else {
3810                list = new ArrayList<ApplicationInfo>(mPackages.size());
3811                for (PackageParser.Package p : mPackages.values()) {
3812                    if (p.mExtras != null) {
3813                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3814                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3815                        if (ai != null) {
3816                            list.add(ai);
3817                        }
3818                    }
3819                }
3820            }
3821
3822            return new ParceledListSlice<ApplicationInfo>(list);
3823        }
3824    }
3825
3826    public List<ApplicationInfo> getPersistentApplications(int flags) {
3827        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3828
3829        // reader
3830        synchronized (mPackages) {
3831            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3832            final int userId = UserHandle.getCallingUserId();
3833            while (i.hasNext()) {
3834                final PackageParser.Package p = i.next();
3835                if (p.applicationInfo != null
3836                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3837                        && (!mSafeMode || isSystemApp(p))) {
3838                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3839                    if (ps != null) {
3840                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3841                                ps.readUserState(userId), userId);
3842                        if (ai != null) {
3843                            finalList.add(ai);
3844                        }
3845                    }
3846                }
3847            }
3848        }
3849
3850        return finalList;
3851    }
3852
3853    @Override
3854    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3855        if (!sUserManager.exists(userId)) return null;
3856        // reader
3857        synchronized (mPackages) {
3858            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3859            PackageSetting ps = provider != null
3860                    ? mSettings.mPackages.get(provider.owner.packageName)
3861                    : null;
3862            return ps != null
3863                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3864                    && (!mSafeMode || (provider.info.applicationInfo.flags
3865                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3866                    ? PackageParser.generateProviderInfo(provider, flags,
3867                            ps.readUserState(userId), userId)
3868                    : null;
3869        }
3870    }
3871
3872    /**
3873     * @deprecated
3874     */
3875    @Deprecated
3876    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3877        // reader
3878        synchronized (mPackages) {
3879            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3880                    .entrySet().iterator();
3881            final int userId = UserHandle.getCallingUserId();
3882            while (i.hasNext()) {
3883                Map.Entry<String, PackageParser.Provider> entry = i.next();
3884                PackageParser.Provider p = entry.getValue();
3885                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3886
3887                if (ps != null && p.syncable
3888                        && (!mSafeMode || (p.info.applicationInfo.flags
3889                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3890                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3891                            ps.readUserState(userId), userId);
3892                    if (info != null) {
3893                        outNames.add(entry.getKey());
3894                        outInfo.add(info);
3895                    }
3896                }
3897            }
3898        }
3899    }
3900
3901    @Override
3902    public List<ProviderInfo> queryContentProviders(String processName,
3903            int uid, int flags) {
3904        ArrayList<ProviderInfo> finalList = null;
3905        // reader
3906        synchronized (mPackages) {
3907            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3908            final int userId = processName != null ?
3909                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3910            while (i.hasNext()) {
3911                final PackageParser.Provider p = i.next();
3912                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3913                if (ps != null && p.info.authority != null
3914                        && (processName == null
3915                                || (p.info.processName.equals(processName)
3916                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3917                        && mSettings.isEnabledLPr(p.info, flags, userId)
3918                        && (!mSafeMode
3919                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3920                    if (finalList == null) {
3921                        finalList = new ArrayList<ProviderInfo>(3);
3922                    }
3923                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3924                            ps.readUserState(userId), userId);
3925                    if (info != null) {
3926                        finalList.add(info);
3927                    }
3928                }
3929            }
3930        }
3931
3932        if (finalList != null) {
3933            Collections.sort(finalList, mProviderInitOrderSorter);
3934        }
3935
3936        return finalList;
3937    }
3938
3939    @Override
3940    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3941            int flags) {
3942        // reader
3943        synchronized (mPackages) {
3944            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3945            return PackageParser.generateInstrumentationInfo(i, flags);
3946        }
3947    }
3948
3949    @Override
3950    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3951            int flags) {
3952        ArrayList<InstrumentationInfo> finalList =
3953            new ArrayList<InstrumentationInfo>();
3954
3955        // reader
3956        synchronized (mPackages) {
3957            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3958            while (i.hasNext()) {
3959                final PackageParser.Instrumentation p = i.next();
3960                if (targetPackage == null
3961                        || targetPackage.equals(p.info.targetPackage)) {
3962                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3963                            flags);
3964                    if (ii != null) {
3965                        finalList.add(ii);
3966                    }
3967                }
3968            }
3969        }
3970
3971        return finalList;
3972    }
3973
3974    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
3975        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
3976        if (overlays == null) {
3977            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
3978            return;
3979        }
3980        for (PackageParser.Package opkg : overlays.values()) {
3981            // Not much to do if idmap fails: we already logged the error
3982            // and we certainly don't want to abort installation of pkg simply
3983            // because an overlay didn't fit properly. For these reasons,
3984            // ignore the return value of createIdmapForPackagePairLI.
3985            createIdmapForPackagePairLI(pkg, opkg);
3986        }
3987    }
3988
3989    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
3990            PackageParser.Package opkg) {
3991        if (!opkg.mTrustedOverlay) {
3992            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
3993                    opkg.baseCodePath + ": overlay not trusted");
3994            return false;
3995        }
3996        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
3997        if (overlaySet == null) {
3998            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
3999                    opkg.baseCodePath + " but target package has no known overlays");
4000            return false;
4001        }
4002        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4003        // TODO: generate idmap for split APKs
4004        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4005            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4006                    + opkg.baseCodePath);
4007            return false;
4008        }
4009        PackageParser.Package[] overlayArray =
4010            overlaySet.values().toArray(new PackageParser.Package[0]);
4011        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4012            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4013                return p1.mOverlayPriority - p2.mOverlayPriority;
4014            }
4015        };
4016        Arrays.sort(overlayArray, cmp);
4017
4018        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4019        int i = 0;
4020        for (PackageParser.Package p : overlayArray) {
4021            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4022        }
4023        return true;
4024    }
4025
4026    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4027        final File[] files = dir.listFiles();
4028        if (ArrayUtils.isEmpty(files)) {
4029            Log.d(TAG, "No files in app dir " + dir);
4030            return;
4031        }
4032
4033        if (DEBUG_PACKAGE_SCANNING) {
4034            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4035                    + " flags=0x" + Integer.toHexString(parseFlags));
4036        }
4037
4038        for (File file : files) {
4039            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4040                    && !PackageInstallerService.isStageName(file.getName());
4041            if (!isPackage) {
4042                // Ignore entries which are not packages
4043                continue;
4044            }
4045            try {
4046                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4047                        scanFlags, currentTime, null);
4048            } catch (PackageManagerException e) {
4049                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4050
4051                // Delete invalid userdata apps
4052                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4053                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4054                    Slog.w(TAG, "Deleting invalid package at " + file);
4055                    if (file.isDirectory()) {
4056                        FileUtils.deleteContents(file);
4057                    }
4058                    file.delete();
4059                }
4060            }
4061        }
4062    }
4063
4064    private static File getSettingsProblemFile() {
4065        File dataDir = Environment.getDataDirectory();
4066        File systemDir = new File(dataDir, "system");
4067        File fname = new File(systemDir, "uiderrors.txt");
4068        return fname;
4069    }
4070
4071    static void reportSettingsProblem(int priority, String msg) {
4072        try {
4073            File fname = getSettingsProblemFile();
4074            FileOutputStream out = new FileOutputStream(fname, true);
4075            PrintWriter pw = new FastPrintWriter(out);
4076            SimpleDateFormat formatter = new SimpleDateFormat();
4077            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4078            pw.println(dateString + ": " + msg);
4079            pw.close();
4080            FileUtils.setPermissions(
4081                    fname.toString(),
4082                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4083                    -1, -1);
4084        } catch (java.io.IOException e) {
4085        }
4086        Slog.println(priority, TAG, msg);
4087    }
4088
4089    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4090            PackageParser.Package pkg, File srcFile, int parseFlags)
4091            throws PackageManagerException {
4092        if (ps != null
4093                && ps.codePath.equals(srcFile)
4094                && ps.timeStamp == srcFile.lastModified()
4095                && !isCompatSignatureUpdateNeeded(pkg)) {
4096            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4097            if (ps.signatures.mSignatures != null
4098                    && ps.signatures.mSignatures.length != 0
4099                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4100                // Optimization: reuse the existing cached certificates
4101                // if the package appears to be unchanged.
4102                pkg.mSignatures = ps.signatures.mSignatures;
4103                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4104                synchronized (mPackages) {
4105                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4106                }
4107                return;
4108            }
4109
4110            Slog.w(TAG, "PackageSetting for " + ps.name
4111                    + " is missing signatures.  Collecting certs again to recover them.");
4112        } else {
4113            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4114        }
4115
4116        try {
4117            pp.collectCertificates(pkg, parseFlags);
4118            pp.collectManifestDigest(pkg);
4119        } catch (PackageParserException e) {
4120            throw PackageManagerException.from(e);
4121        }
4122    }
4123
4124    /*
4125     *  Scan a package and return the newly parsed package.
4126     *  Returns null in case of errors and the error code is stored in mLastScanError
4127     */
4128    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4129            long currentTime, UserHandle user) throws PackageManagerException {
4130        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4131        parseFlags |= mDefParseFlags;
4132        PackageParser pp = new PackageParser();
4133        pp.setSeparateProcesses(mSeparateProcesses);
4134        pp.setOnlyCoreApps(mOnlyCore);
4135        pp.setDisplayMetrics(mMetrics);
4136
4137        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4138            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4139        }
4140
4141        final PackageParser.Package pkg;
4142        try {
4143            pkg = pp.parsePackage(scanFile, parseFlags);
4144        } catch (PackageParserException e) {
4145            throw PackageManagerException.from(e);
4146        }
4147
4148        PackageSetting ps = null;
4149        PackageSetting updatedPkg;
4150        // reader
4151        synchronized (mPackages) {
4152            // Look to see if we already know about this package.
4153            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4154            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4155                // This package has been renamed to its original name.  Let's
4156                // use that.
4157                ps = mSettings.peekPackageLPr(oldName);
4158            }
4159            // If there was no original package, see one for the real package name.
4160            if (ps == null) {
4161                ps = mSettings.peekPackageLPr(pkg.packageName);
4162            }
4163            // Check to see if this package could be hiding/updating a system
4164            // package.  Must look for it either under the original or real
4165            // package name depending on our state.
4166            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4167            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4168        }
4169        boolean updatedPkgBetter = false;
4170        // First check if this is a system package that may involve an update
4171        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4172            if (ps != null && !ps.codePath.equals(scanFile)) {
4173                // The path has changed from what was last scanned...  check the
4174                // version of the new path against what we have stored to determine
4175                // what to do.
4176                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4177                if (pkg.mVersionCode < ps.versionCode) {
4178                    // The system package has been updated and the code path does not match
4179                    // Ignore entry. Skip it.
4180                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4181                            + " ignored: updated version " + ps.versionCode
4182                            + " better than this " + pkg.mVersionCode);
4183                    if (!updatedPkg.codePath.equals(scanFile)) {
4184                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4185                                + ps.name + " changing from " + updatedPkg.codePathString
4186                                + " to " + scanFile);
4187                        updatedPkg.codePath = scanFile;
4188                        updatedPkg.codePathString = scanFile.toString();
4189                        // This is the point at which we know that the system-disk APK
4190                        // for this package has moved during a reboot (e.g. due to an OTA),
4191                        // so we need to reevaluate it for privilege policy.
4192                        if (locationIsPrivileged(scanFile)) {
4193                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4194                        }
4195                    }
4196                    updatedPkg.pkg = pkg;
4197                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4198                } else {
4199                    // The current app on the system partition is better than
4200                    // what we have updated to on the data partition; switch
4201                    // back to the system partition version.
4202                    // At this point, its safely assumed that package installation for
4203                    // apps in system partition will go through. If not there won't be a working
4204                    // version of the app
4205                    // writer
4206                    synchronized (mPackages) {
4207                        // Just remove the loaded entries from package lists.
4208                        mPackages.remove(ps.name);
4209                    }
4210                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4211                            + "reverting from " + ps.codePathString
4212                            + ": new version " + pkg.mVersionCode
4213                            + " better than installed " + ps.versionCode);
4214
4215                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4216                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4217                            getAppDexInstructionSets(ps));
4218                    synchronized (mInstallLock) {
4219                        args.cleanUpResourcesLI();
4220                    }
4221                    synchronized (mPackages) {
4222                        mSettings.enableSystemPackageLPw(ps.name);
4223                    }
4224                    updatedPkgBetter = true;
4225                }
4226            }
4227        }
4228
4229        if (updatedPkg != null) {
4230            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4231            // initially
4232            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4233
4234            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4235            // flag set initially
4236            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4237                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4238            }
4239        }
4240
4241        // Verify certificates against what was last scanned
4242        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4243
4244        /*
4245         * A new system app appeared, but we already had a non-system one of the
4246         * same name installed earlier.
4247         */
4248        boolean shouldHideSystemApp = false;
4249        if (updatedPkg == null && ps != null
4250                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4251            /*
4252             * Check to make sure the signatures match first. If they don't,
4253             * wipe the installed application and its data.
4254             */
4255            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4256                    != PackageManager.SIGNATURE_MATCH) {
4257                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4258                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4259                ps = null;
4260            } else {
4261                /*
4262                 * If the newly-added system app is an older version than the
4263                 * already installed version, hide it. It will be scanned later
4264                 * and re-added like an update.
4265                 */
4266                if (pkg.mVersionCode < ps.versionCode) {
4267                    shouldHideSystemApp = true;
4268                } else {
4269                    /*
4270                     * The newly found system app is a newer version that the
4271                     * one previously installed. Simply remove the
4272                     * already-installed application and replace it with our own
4273                     * while keeping the application data.
4274                     */
4275                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4276                            + ps.codePathString + ": new version " + pkg.mVersionCode
4277                            + " better than installed " + ps.versionCode);
4278                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4279                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4280                            getAppDexInstructionSets(ps));
4281                    synchronized (mInstallLock) {
4282                        args.cleanUpResourcesLI();
4283                    }
4284                }
4285            }
4286        }
4287
4288        // The apk is forward locked (not public) if its code and resources
4289        // are kept in different files. (except for app in either system or
4290        // vendor path).
4291        // TODO grab this value from PackageSettings
4292        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4293            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4294                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4295            }
4296        }
4297
4298        // TODO: extend to support forward-locked splits
4299        String resourcePath = null;
4300        String baseResourcePath = null;
4301        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4302            if (ps != null && ps.resourcePathString != null) {
4303                resourcePath = ps.resourcePathString;
4304                baseResourcePath = ps.resourcePathString;
4305            } else {
4306                // Should not happen at all. Just log an error.
4307                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4308            }
4309        } else {
4310            resourcePath = pkg.codePath;
4311            baseResourcePath = pkg.baseCodePath;
4312        }
4313
4314        // Set application objects path explicitly.
4315        pkg.applicationInfo.setCodePath(pkg.codePath);
4316        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4317        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4318        pkg.applicationInfo.setResourcePath(resourcePath);
4319        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4320        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4321
4322        // Note that we invoke the following method only if we are about to unpack an application
4323        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4324                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4325
4326        /*
4327         * If the system app should be overridden by a previously installed
4328         * data, hide the system app now and let the /data/app scan pick it up
4329         * again.
4330         */
4331        if (shouldHideSystemApp) {
4332            synchronized (mPackages) {
4333                /*
4334                 * We have to grant systems permissions before we hide, because
4335                 * grantPermissions will assume the package update is trying to
4336                 * expand its permissions.
4337                 */
4338                grantPermissionsLPw(pkg, true, pkg.packageName);
4339                mSettings.disableSystemPackageLPw(pkg.packageName);
4340            }
4341        }
4342
4343        return scannedPkg;
4344    }
4345
4346    private static String fixProcessName(String defProcessName,
4347            String processName, int uid) {
4348        if (processName == null) {
4349            return defProcessName;
4350        }
4351        return processName;
4352    }
4353
4354    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4355            throws PackageManagerException {
4356        if (pkgSetting.signatures.mSignatures != null) {
4357            // Already existing package. Make sure signatures match
4358            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4359                    == PackageManager.SIGNATURE_MATCH;
4360            if (!match) {
4361                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4362                        == PackageManager.SIGNATURE_MATCH;
4363            }
4364            if (!match) {
4365                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4366                        + pkg.packageName + " signatures do not match the "
4367                        + "previously installed version; ignoring!");
4368            }
4369        }
4370
4371        // Check for shared user signatures
4372        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4373            // Already existing package. Make sure signatures match
4374            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4375                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4376            if (!match) {
4377                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4378                        == PackageManager.SIGNATURE_MATCH;
4379            }
4380            if (!match) {
4381                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4382                        "Package " + pkg.packageName
4383                        + " has no signatures that match those in shared user "
4384                        + pkgSetting.sharedUser.name + "; ignoring!");
4385            }
4386        }
4387    }
4388
4389    /**
4390     * Enforces that only the system UID or root's UID can call a method exposed
4391     * via Binder.
4392     *
4393     * @param message used as message if SecurityException is thrown
4394     * @throws SecurityException if the caller is not system or root
4395     */
4396    private static final void enforceSystemOrRoot(String message) {
4397        final int uid = Binder.getCallingUid();
4398        if (uid != Process.SYSTEM_UID && uid != 0) {
4399            throw new SecurityException(message);
4400        }
4401    }
4402
4403    @Override
4404    public void performBootDexOpt() {
4405        enforceSystemOrRoot("Only the system can request dexopt be performed");
4406
4407        final HashSet<PackageParser.Package> pkgs;
4408        synchronized (mPackages) {
4409            pkgs = mDeferredDexOpt;
4410            mDeferredDexOpt = null;
4411        }
4412
4413        if (pkgs != null) {
4414            // Filter out packages that aren't recently used.
4415            //
4416            // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4417            // should do a full dexopt.
4418            if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4419                // TODO: add a property to control this?
4420                long dexOptLRUThresholdInMinutes;
4421                if (mLazyDexOpt) {
4422                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4423                } else {
4424                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4425                }
4426                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4427
4428                int total = pkgs.size();
4429                int skipped = 0;
4430                long now = System.currentTimeMillis();
4431                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4432                    PackageParser.Package pkg = i.next();
4433                    long then = pkg.mLastPackageUsageTimeInMills;
4434                    if (then + dexOptLRUThresholdInMills < now) {
4435                        if (DEBUG_DEXOPT) {
4436                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4437                                  ((then == 0) ? "never" : new Date(then)));
4438                        }
4439                        i.remove();
4440                        skipped++;
4441                    }
4442                }
4443                if (DEBUG_DEXOPT) {
4444                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4445                }
4446            }
4447
4448            int i = 0;
4449            for (PackageParser.Package pkg : pkgs) {
4450                i++;
4451                if (DEBUG_DEXOPT) {
4452                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4453                          + ": " + pkg.packageName);
4454                }
4455                if (!isFirstBoot()) {
4456                    try {
4457                        ActivityManagerNative.getDefault().showBootMessage(
4458                                mContext.getResources().getString(
4459                                        R.string.android_upgrading_apk,
4460                                        i, pkgs.size()), true);
4461                    } catch (RemoteException e) {
4462                    }
4463                }
4464                PackageParser.Package p = pkg;
4465                synchronized (mInstallLock) {
4466                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4467                            true /* include dependencies */);
4468                }
4469            }
4470        }
4471    }
4472
4473    @Override
4474    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4475        return performDexOpt(packageName, instructionSet, false);
4476    }
4477
4478    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4479        if (info.primaryCpuAbi == null) {
4480            return getPreferredInstructionSet();
4481        }
4482
4483        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4484    }
4485
4486    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4487        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4488        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4489        if (!dexopt && !updateUsage) {
4490            // We aren't going to dexopt or update usage, so bail early.
4491            return false;
4492        }
4493        PackageParser.Package p;
4494        final String targetInstructionSet;
4495        synchronized (mPackages) {
4496            p = mPackages.get(packageName);
4497            if (p == null) {
4498                return false;
4499            }
4500            if (updateUsage) {
4501                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4502            }
4503            mPackageUsage.write(false);
4504            if (!dexopt) {
4505                // We aren't going to dexopt, so bail early.
4506                return false;
4507            }
4508
4509            targetInstructionSet = instructionSet != null ? instructionSet :
4510                    getPrimaryInstructionSet(p.applicationInfo);
4511            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4512                return false;
4513            }
4514        }
4515
4516        synchronized (mInstallLock) {
4517            final String[] instructionSets = new String[] { targetInstructionSet };
4518            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4519                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4520        }
4521    }
4522
4523    public HashSet<String> getPackagesThatNeedDexOpt() {
4524        HashSet<String> pkgs = null;
4525        synchronized (mPackages) {
4526            for (PackageParser.Package p : mPackages.values()) {
4527                if (DEBUG_DEXOPT) {
4528                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4529                }
4530                if (!p.mDexOptPerformed.isEmpty()) {
4531                    continue;
4532                }
4533                if (pkgs == null) {
4534                    pkgs = new HashSet<String>();
4535                }
4536                pkgs.add(p.packageName);
4537            }
4538        }
4539        return pkgs;
4540    }
4541
4542    public void shutdown() {
4543        mPackageUsage.write(true);
4544    }
4545
4546    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4547             boolean forceDex, boolean defer, HashSet<String> done) {
4548        for (int i=0; i<libs.size(); i++) {
4549            PackageParser.Package libPkg;
4550            String libName;
4551            synchronized (mPackages) {
4552                libName = libs.get(i);
4553                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4554                if (lib != null && lib.apk != null) {
4555                    libPkg = mPackages.get(lib.apk);
4556                } else {
4557                    libPkg = null;
4558                }
4559            }
4560            if (libPkg != null && !done.contains(libName)) {
4561                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4562            }
4563        }
4564    }
4565
4566    static final int DEX_OPT_SKIPPED = 0;
4567    static final int DEX_OPT_PERFORMED = 1;
4568    static final int DEX_OPT_DEFERRED = 2;
4569    static final int DEX_OPT_FAILED = -1;
4570
4571    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4572            boolean forceDex, boolean defer, HashSet<String> done) {
4573        final String[] instructionSets = targetInstructionSets != null ?
4574                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4575
4576        if (done != null) {
4577            done.add(pkg.packageName);
4578            if (pkg.usesLibraries != null) {
4579                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4580            }
4581            if (pkg.usesOptionalLibraries != null) {
4582                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4583            }
4584        }
4585
4586        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4587            return DEX_OPT_SKIPPED;
4588        }
4589
4590        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4591
4592        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4593        boolean performedDexOpt = false;
4594        // There are three basic cases here:
4595        // 1.) we need to dexopt, either because we are forced or it is needed
4596        // 2.) we are defering a needed dexopt
4597        // 3.) we are skipping an unneeded dexopt
4598        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4599        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4600            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4601                continue;
4602            }
4603
4604            for (String path : paths) {
4605                try {
4606                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4607                    // patckage or the one we find does not match the image checksum (i.e. it was
4608                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4609                    // odex file and it matches the checksum of the image but not its base address,
4610                    // meaning we need to move it.
4611                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4612                            pkg.packageName, dexCodeInstructionSet, defer);
4613                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4614                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4615                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4616                                + " vmSafeMode=" + vmSafeMode);
4617                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4618                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4619                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4620
4621                        if (ret < 0) {
4622                            // Don't bother running dexopt again if we failed, it will probably
4623                            // just result in an error again. Also, don't bother dexopting for other
4624                            // paths & ISAs.
4625                            return DEX_OPT_FAILED;
4626                        }
4627
4628                        performedDexOpt = true;
4629                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4630                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4631                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4632                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4633                                pkg.packageName, dexCodeInstructionSet);
4634
4635                        if (ret < 0) {
4636                            // Don't bother running patchoat again if we failed, it will probably
4637                            // just result in an error again. Also, don't bother dexopting for other
4638                            // paths & ISAs.
4639                            return DEX_OPT_FAILED;
4640                        }
4641
4642                        performedDexOpt = true;
4643                    }
4644
4645                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4646                    // paths and instruction sets. We'll deal with them all together when we process
4647                    // our list of deferred dexopts.
4648                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4649                        if (mDeferredDexOpt == null) {
4650                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4651                        }
4652                        mDeferredDexOpt.add(pkg);
4653                        return DEX_OPT_DEFERRED;
4654                    }
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            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4671            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4672            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4673            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4674            // it.
4675            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4676        }
4677
4678        // If we've gotten here, we're sure that no error occurred and that we haven't
4679        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4680        // we've skipped all of them because they are up to date. In both cases this
4681        // package doesn't need dexopt any longer.
4682        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4683    }
4684
4685    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4686        if (info.primaryCpuAbi != null) {
4687            if (info.secondaryCpuAbi != null) {
4688                return new String[] {
4689                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4690                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4691            } else {
4692                return new String[] {
4693                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4694            }
4695        }
4696
4697        return new String[] { getPreferredInstructionSet() };
4698    }
4699
4700    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4701        if (ps.primaryCpuAbiString != null) {
4702            if (ps.secondaryCpuAbiString != null) {
4703                return new String[] {
4704                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4705                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4706            } else {
4707                return new String[] {
4708                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4709            }
4710        }
4711
4712        return new String[] { getPreferredInstructionSet() };
4713    }
4714
4715    private static String getPreferredInstructionSet() {
4716        if (sPreferredInstructionSet == null) {
4717            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4718        }
4719
4720        return sPreferredInstructionSet;
4721    }
4722
4723    private static List<String> getAllInstructionSets() {
4724        final String[] allAbis = Build.SUPPORTED_ABIS;
4725        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4726
4727        for (String abi : allAbis) {
4728            final String instructionSet = VMRuntime.getInstructionSet(abi);
4729            if (!allInstructionSets.contains(instructionSet)) {
4730                allInstructionSets.add(instructionSet);
4731            }
4732        }
4733
4734        return allInstructionSets;
4735    }
4736
4737    /**
4738     * Returns the instruction set that should be used to compile dex code. In the presence of
4739     * a native bridge this might be different than the one shared libraries use.
4740     */
4741    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4742        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4743        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4744    }
4745
4746    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4747        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4748        for (String instructionSet : instructionSets) {
4749            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4750        }
4751        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4752    }
4753
4754    /**
4755     * Returns deduplicated list of supported instructions for dex code.
4756     */
4757    public static String[] getAllDexCodeInstructionSets() {
4758        String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length];
4759        for (int i = 0; i < supportedInstructionSets.length; i++) {
4760            String abi = Build.SUPPORTED_ABIS[i];
4761            supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi);
4762        }
4763        return getDexCodeInstructionSets(supportedInstructionSets);
4764    }
4765
4766    @Override
4767    public void forceDexOpt(String packageName) {
4768        enforceSystemOrRoot("forceDexOpt");
4769
4770        PackageParser.Package pkg;
4771        synchronized (mPackages) {
4772            pkg = mPackages.get(packageName);
4773            if (pkg == null) {
4774                throw new IllegalArgumentException("Missing package: " + packageName);
4775            }
4776        }
4777
4778        synchronized (mInstallLock) {
4779            final String[] instructionSets = new String[] {
4780                    getPrimaryInstructionSet(pkg.applicationInfo) };
4781            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4782            if (res != DEX_OPT_PERFORMED) {
4783                throw new IllegalStateException("Failed to dexopt: " + res);
4784            }
4785        }
4786    }
4787
4788    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4789                                boolean forceDex, boolean defer, boolean inclDependencies) {
4790        HashSet<String> done;
4791        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4792            done = new HashSet<String>();
4793            done.add(pkg.packageName);
4794        } else {
4795            done = null;
4796        }
4797        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4798    }
4799
4800    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4801        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4802            Slog.w(TAG, "Unable to update from " + oldPkg.name
4803                    + " to " + newPkg.packageName
4804                    + ": old package not in system partition");
4805            return false;
4806        } else if (mPackages.get(oldPkg.name) != null) {
4807            Slog.w(TAG, "Unable to update from " + oldPkg.name
4808                    + " to " + newPkg.packageName
4809                    + ": old package still exists");
4810            return false;
4811        }
4812        return true;
4813    }
4814
4815    File getDataPathForUser(int userId) {
4816        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4817    }
4818
4819    private File getDataPathForPackage(String packageName, int userId) {
4820        /*
4821         * Until we fully support multiple users, return the directory we
4822         * previously would have. The PackageManagerTests will need to be
4823         * revised when this is changed back..
4824         */
4825        if (userId == 0) {
4826            return new File(mAppDataDir, packageName);
4827        } else {
4828            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4829                + File.separator + packageName);
4830        }
4831    }
4832
4833    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4834        int[] users = sUserManager.getUserIds();
4835        int res = mInstaller.install(packageName, uid, uid, seinfo);
4836        if (res < 0) {
4837            return res;
4838        }
4839        for (int user : users) {
4840            if (user != 0) {
4841                res = mInstaller.createUserData(packageName,
4842                        UserHandle.getUid(user, uid), user, seinfo);
4843                if (res < 0) {
4844                    return res;
4845                }
4846            }
4847        }
4848        return res;
4849    }
4850
4851    private int removeDataDirsLI(String packageName) {
4852        int[] users = sUserManager.getUserIds();
4853        int res = 0;
4854        for (int user : users) {
4855            int resInner = mInstaller.remove(packageName, user);
4856            if (resInner < 0) {
4857                res = resInner;
4858            }
4859        }
4860
4861        return res;
4862    }
4863
4864    private int deleteCodeCacheDirsLI(String packageName) {
4865        int[] users = sUserManager.getUserIds();
4866        int res = 0;
4867        for (int user : users) {
4868            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4869            if (resInner < 0) {
4870                res = resInner;
4871            }
4872        }
4873        return res;
4874    }
4875
4876    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4877            PackageParser.Package changingLib) {
4878        if (file.path != null) {
4879            usesLibraryFiles.add(file.path);
4880            return;
4881        }
4882        PackageParser.Package p = mPackages.get(file.apk);
4883        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4884            // If we are doing this while in the middle of updating a library apk,
4885            // then we need to make sure to use that new apk for determining the
4886            // dependencies here.  (We haven't yet finished committing the new apk
4887            // to the package manager state.)
4888            if (p == null || p.packageName.equals(changingLib.packageName)) {
4889                p = changingLib;
4890            }
4891        }
4892        if (p != null) {
4893            usesLibraryFiles.addAll(p.getAllCodePaths());
4894        }
4895    }
4896
4897    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4898            PackageParser.Package changingLib) throws PackageManagerException {
4899        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4900            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4901            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4902            for (int i=0; i<N; i++) {
4903                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4904                if (file == null) {
4905                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4906                            "Package " + pkg.packageName + " requires unavailable shared library "
4907                            + pkg.usesLibraries.get(i) + "; failing!");
4908                }
4909                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4910            }
4911            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4912            for (int i=0; i<N; i++) {
4913                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4914                if (file == null) {
4915                    Slog.w(TAG, "Package " + pkg.packageName
4916                            + " desires unavailable shared library "
4917                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4918                } else {
4919                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4920                }
4921            }
4922            N = usesLibraryFiles.size();
4923            if (N > 0) {
4924                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4925            } else {
4926                pkg.usesLibraryFiles = null;
4927            }
4928        }
4929    }
4930
4931    private static boolean hasString(List<String> list, List<String> which) {
4932        if (list == null) {
4933            return false;
4934        }
4935        for (int i=list.size()-1; i>=0; i--) {
4936            for (int j=which.size()-1; j>=0; j--) {
4937                if (which.get(j).equals(list.get(i))) {
4938                    return true;
4939                }
4940            }
4941        }
4942        return false;
4943    }
4944
4945    private void updateAllSharedLibrariesLPw() {
4946        for (PackageParser.Package pkg : mPackages.values()) {
4947            try {
4948                updateSharedLibrariesLPw(pkg, null);
4949            } catch (PackageManagerException e) {
4950                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4951            }
4952        }
4953    }
4954
4955    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4956            PackageParser.Package changingPkg) {
4957        ArrayList<PackageParser.Package> res = null;
4958        for (PackageParser.Package pkg : mPackages.values()) {
4959            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4960                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4961                if (res == null) {
4962                    res = new ArrayList<PackageParser.Package>();
4963                }
4964                res.add(pkg);
4965                try {
4966                    updateSharedLibrariesLPw(pkg, changingPkg);
4967                } catch (PackageManagerException e) {
4968                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4969                }
4970            }
4971        }
4972        return res;
4973    }
4974
4975    /**
4976     * Derive the value of the {@code cpuAbiOverride} based on the provided
4977     * value and an optional stored value from the package settings.
4978     */
4979    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
4980        String cpuAbiOverride = null;
4981
4982        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
4983            cpuAbiOverride = null;
4984        } else if (abiOverride != null) {
4985            cpuAbiOverride = abiOverride;
4986        } else if (settings != null) {
4987            cpuAbiOverride = settings.cpuAbiOverrideString;
4988        }
4989
4990        return cpuAbiOverride;
4991    }
4992
4993    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
4994            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
4995        boolean success = false;
4996        try {
4997            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
4998                    currentTime, user);
4999            success = true;
5000            return res;
5001        } finally {
5002            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5003                removeDataDirsLI(pkg.packageName);
5004            }
5005        }
5006    }
5007
5008    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5009            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5010        final File scanFile = new File(pkg.codePath);
5011        if (pkg.applicationInfo.getCodePath() == null ||
5012                pkg.applicationInfo.getResourcePath() == null) {
5013            // Bail out. The resource and code paths haven't been set.
5014            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5015                    "Code and resource paths haven't been set correctly");
5016        }
5017
5018        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5019            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5020        }
5021
5022        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5023            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5024        }
5025
5026        if (mCustomResolverComponentName != null &&
5027                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5028            setUpCustomResolverActivity(pkg);
5029        }
5030
5031        if (pkg.packageName.equals("android")) {
5032            synchronized (mPackages) {
5033                if (mAndroidApplication != null) {
5034                    Slog.w(TAG, "*************************************************");
5035                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5036                    Slog.w(TAG, " file=" + scanFile);
5037                    Slog.w(TAG, "*************************************************");
5038                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5039                            "Core android package being redefined.  Skipping.");
5040                }
5041
5042                // Set up information for our fall-back user intent resolution activity.
5043                mPlatformPackage = pkg;
5044                pkg.mVersionCode = mSdkVersion;
5045                mAndroidApplication = pkg.applicationInfo;
5046
5047                if (!mResolverReplaced) {
5048                    mResolveActivity.applicationInfo = mAndroidApplication;
5049                    mResolveActivity.name = ResolverActivity.class.getName();
5050                    mResolveActivity.packageName = mAndroidApplication.packageName;
5051                    mResolveActivity.processName = "system:ui";
5052                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5053                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5054                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5055                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5056                    mResolveActivity.exported = true;
5057                    mResolveActivity.enabled = true;
5058                    mResolveInfo.activityInfo = mResolveActivity;
5059                    mResolveInfo.priority = 0;
5060                    mResolveInfo.preferredOrder = 0;
5061                    mResolveInfo.match = 0;
5062                    mResolveComponentName = new ComponentName(
5063                            mAndroidApplication.packageName, mResolveActivity.name);
5064                }
5065            }
5066        }
5067
5068        if (DEBUG_PACKAGE_SCANNING) {
5069            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5070                Log.d(TAG, "Scanning package " + pkg.packageName);
5071        }
5072
5073        if (mPackages.containsKey(pkg.packageName)
5074                || mSharedLibraries.containsKey(pkg.packageName)) {
5075            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5076                    "Application package " + pkg.packageName
5077                    + " already installed.  Skipping duplicate.");
5078        }
5079
5080        // Initialize package source and resource directories
5081        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5082        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5083
5084        SharedUserSetting suid = null;
5085        PackageSetting pkgSetting = null;
5086
5087        if (!isSystemApp(pkg)) {
5088            // Only system apps can use these features.
5089            pkg.mOriginalPackages = null;
5090            pkg.mRealPackage = null;
5091            pkg.mAdoptPermissions = null;
5092        }
5093
5094        // writer
5095        synchronized (mPackages) {
5096            if (pkg.mSharedUserId != null) {
5097                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5098                if (suid == null) {
5099                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5100                            "Creating application package " + pkg.packageName
5101                            + " for shared user failed");
5102                }
5103                if (DEBUG_PACKAGE_SCANNING) {
5104                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5105                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5106                                + "): packages=" + suid.packages);
5107                }
5108            }
5109
5110            // Check if we are renaming from an original package name.
5111            PackageSetting origPackage = null;
5112            String realName = null;
5113            if (pkg.mOriginalPackages != null) {
5114                // This package may need to be renamed to a previously
5115                // installed name.  Let's check on that...
5116                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5117                if (pkg.mOriginalPackages.contains(renamed)) {
5118                    // This package had originally been installed as the
5119                    // original name, and we have already taken care of
5120                    // transitioning to the new one.  Just update the new
5121                    // one to continue using the old name.
5122                    realName = pkg.mRealPackage;
5123                    if (!pkg.packageName.equals(renamed)) {
5124                        // Callers into this function may have already taken
5125                        // care of renaming the package; only do it here if
5126                        // it is not already done.
5127                        pkg.setPackageName(renamed);
5128                    }
5129
5130                } else {
5131                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5132                        if ((origPackage = mSettings.peekPackageLPr(
5133                                pkg.mOriginalPackages.get(i))) != null) {
5134                            // We do have the package already installed under its
5135                            // original name...  should we use it?
5136                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5137                                // New package is not compatible with original.
5138                                origPackage = null;
5139                                continue;
5140                            } else if (origPackage.sharedUser != null) {
5141                                // Make sure uid is compatible between packages.
5142                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5143                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5144                                            + " to " + pkg.packageName + ": old uid "
5145                                            + origPackage.sharedUser.name
5146                                            + " differs from " + pkg.mSharedUserId);
5147                                    origPackage = null;
5148                                    continue;
5149                                }
5150                            } else {
5151                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5152                                        + pkg.packageName + " to old name " + origPackage.name);
5153                            }
5154                            break;
5155                        }
5156                    }
5157                }
5158            }
5159
5160            if (mTransferedPackages.contains(pkg.packageName)) {
5161                Slog.w(TAG, "Package " + pkg.packageName
5162                        + " was transferred to another, but its .apk remains");
5163            }
5164
5165            // Just create the setting, don't add it yet. For already existing packages
5166            // the PkgSetting exists already and doesn't have to be created.
5167            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5168                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5169                    pkg.applicationInfo.primaryCpuAbi,
5170                    pkg.applicationInfo.secondaryCpuAbi,
5171                    pkg.applicationInfo.flags, user, false);
5172            if (pkgSetting == null) {
5173                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5174                        "Creating application package " + pkg.packageName + " failed");
5175            }
5176
5177            if (pkgSetting.origPackage != null) {
5178                // If we are first transitioning from an original package,
5179                // fix up the new package's name now.  We need to do this after
5180                // looking up the package under its new name, so getPackageLP
5181                // can take care of fiddling things correctly.
5182                pkg.setPackageName(origPackage.name);
5183
5184                // File a report about this.
5185                String msg = "New package " + pkgSetting.realName
5186                        + " renamed to replace old package " + pkgSetting.name;
5187                reportSettingsProblem(Log.WARN, msg);
5188
5189                // Make a note of it.
5190                mTransferedPackages.add(origPackage.name);
5191
5192                // No longer need to retain this.
5193                pkgSetting.origPackage = null;
5194            }
5195
5196            if (realName != null) {
5197                // Make a note of it.
5198                mTransferedPackages.add(pkg.packageName);
5199            }
5200
5201            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5202                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5203            }
5204
5205            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5206                // Check all shared libraries and map to their actual file path.
5207                // We only do this here for apps not on a system dir, because those
5208                // are the only ones that can fail an install due to this.  We
5209                // will take care of the system apps by updating all of their
5210                // library paths after the scan is done.
5211                updateSharedLibrariesLPw(pkg, null);
5212            }
5213
5214            if (mFoundPolicyFile) {
5215                SELinuxMMAC.assignSeinfoValue(pkg);
5216            }
5217
5218            pkg.applicationInfo.uid = pkgSetting.appId;
5219            pkg.mExtras = pkgSetting;
5220            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5221                try {
5222                    verifySignaturesLP(pkgSetting, pkg);
5223                } catch (PackageManagerException e) {
5224                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5225                        throw e;
5226                    }
5227                    // The signature has changed, but this package is in the system
5228                    // image...  let's recover!
5229                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5230                    // However...  if this package is part of a shared user, but it
5231                    // doesn't match the signature of the shared user, let's fail.
5232                    // What this means is that you can't change the signatures
5233                    // associated with an overall shared user, which doesn't seem all
5234                    // that unreasonable.
5235                    if (pkgSetting.sharedUser != null) {
5236                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5237                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5238                            throw new PackageManagerException(
5239                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5240                                            "Signature mismatch for shared user : "
5241                                            + pkgSetting.sharedUser);
5242                        }
5243                    }
5244                    // File a report about this.
5245                    String msg = "System package " + pkg.packageName
5246                        + " signature changed; retaining data.";
5247                    reportSettingsProblem(Log.WARN, msg);
5248                }
5249            } else {
5250                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5251                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5252                            + pkg.packageName + " upgrade keys do not match the "
5253                            + "previously installed version");
5254                } else {
5255                    // signatures may have changed as result of upgrade
5256                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5257                }
5258            }
5259            // Verify that this new package doesn't have any content providers
5260            // that conflict with existing packages.  Only do this if the
5261            // package isn't already installed, since we don't want to break
5262            // things that are installed.
5263            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5264                final int N = pkg.providers.size();
5265                int i;
5266                for (i=0; i<N; i++) {
5267                    PackageParser.Provider p = pkg.providers.get(i);
5268                    if (p.info.authority != null) {
5269                        String names[] = p.info.authority.split(";");
5270                        for (int j = 0; j < names.length; j++) {
5271                            if (mProvidersByAuthority.containsKey(names[j])) {
5272                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5273                                final String otherPackageName =
5274                                        ((other != null && other.getComponentName() != null) ?
5275                                                other.getComponentName().getPackageName() : "?");
5276                                throw new PackageManagerException(
5277                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5278                                                "Can't install because provider name " + names[j]
5279                                                + " (in package " + pkg.applicationInfo.packageName
5280                                                + ") is already used by " + otherPackageName);
5281                            }
5282                        }
5283                    }
5284                }
5285            }
5286
5287            if (pkg.mAdoptPermissions != null) {
5288                // This package wants to adopt ownership of permissions from
5289                // another package.
5290                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5291                    final String origName = pkg.mAdoptPermissions.get(i);
5292                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5293                    if (orig != null) {
5294                        if (verifyPackageUpdateLPr(orig, pkg)) {
5295                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5296                                    + pkg.packageName);
5297                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5298                        }
5299                    }
5300                }
5301            }
5302        }
5303
5304        final String pkgName = pkg.packageName;
5305
5306        final long scanFileTime = scanFile.lastModified();
5307        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5308        pkg.applicationInfo.processName = fixProcessName(
5309                pkg.applicationInfo.packageName,
5310                pkg.applicationInfo.processName,
5311                pkg.applicationInfo.uid);
5312
5313        File dataPath;
5314        if (mPlatformPackage == pkg) {
5315            // The system package is special.
5316            dataPath = new File(Environment.getDataDirectory(), "system");
5317
5318            pkg.applicationInfo.dataDir = dataPath.getPath();
5319
5320        } else {
5321            // This is a normal package, need to make its data directory.
5322            dataPath = getDataPathForPackage(pkg.packageName, 0);
5323
5324            boolean uidError = false;
5325            if (dataPath.exists()) {
5326                int currentUid = 0;
5327                try {
5328                    StructStat stat = Os.stat(dataPath.getPath());
5329                    currentUid = stat.st_uid;
5330                } catch (ErrnoException e) {
5331                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5332                }
5333
5334                // If we have mismatched owners for the data path, we have a problem.
5335                if (currentUid != pkg.applicationInfo.uid) {
5336                    boolean recovered = false;
5337                    if (currentUid == 0) {
5338                        // The directory somehow became owned by root.  Wow.
5339                        // This is probably because the system was stopped while
5340                        // installd was in the middle of messing with its libs
5341                        // directory.  Ask installd to fix that.
5342                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5343                                pkg.applicationInfo.uid);
5344                        if (ret >= 0) {
5345                            recovered = true;
5346                            String msg = "Package " + pkg.packageName
5347                                    + " unexpectedly changed to uid 0; recovered to " +
5348                                    + pkg.applicationInfo.uid;
5349                            reportSettingsProblem(Log.WARN, msg);
5350                        }
5351                    }
5352                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5353                            || (scanFlags&SCAN_BOOTING) != 0)) {
5354                        // If this is a system app, we can at least delete its
5355                        // current data so the application will still work.
5356                        int ret = removeDataDirsLI(pkgName);
5357                        if (ret >= 0) {
5358                            // TODO: Kill the processes first
5359                            // Old data gone!
5360                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5361                                    ? "System package " : "Third party package ";
5362                            String msg = prefix + pkg.packageName
5363                                    + " has changed from uid: "
5364                                    + currentUid + " to "
5365                                    + pkg.applicationInfo.uid + "; old data erased";
5366                            reportSettingsProblem(Log.WARN, msg);
5367                            recovered = true;
5368
5369                            // And now re-install the app.
5370                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5371                                                   pkg.applicationInfo.seinfo);
5372                            if (ret == -1) {
5373                                // Ack should not happen!
5374                                msg = prefix + pkg.packageName
5375                                        + " could not have data directory re-created after delete.";
5376                                reportSettingsProblem(Log.WARN, msg);
5377                                throw new PackageManagerException(
5378                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5379                            }
5380                        }
5381                        if (!recovered) {
5382                            mHasSystemUidErrors = true;
5383                        }
5384                    } else if (!recovered) {
5385                        // If we allow this install to proceed, we will be broken.
5386                        // Abort, abort!
5387                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5388                                "scanPackageLI");
5389                    }
5390                    if (!recovered) {
5391                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5392                            + pkg.applicationInfo.uid + "/fs_"
5393                            + currentUid;
5394                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5395                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5396                        String msg = "Package " + pkg.packageName
5397                                + " has mismatched uid: "
5398                                + currentUid + " on disk, "
5399                                + pkg.applicationInfo.uid + " in settings";
5400                        // writer
5401                        synchronized (mPackages) {
5402                            mSettings.mReadMessages.append(msg);
5403                            mSettings.mReadMessages.append('\n');
5404                            uidError = true;
5405                            if (!pkgSetting.uidError) {
5406                                reportSettingsProblem(Log.ERROR, msg);
5407                            }
5408                        }
5409                    }
5410                }
5411                pkg.applicationInfo.dataDir = dataPath.getPath();
5412                if (mShouldRestoreconData) {
5413                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5414                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5415                                pkg.applicationInfo.uid);
5416                }
5417            } else {
5418                if (DEBUG_PACKAGE_SCANNING) {
5419                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5420                        Log.v(TAG, "Want this data dir: " + dataPath);
5421                }
5422                //invoke installer to do the actual installation
5423                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5424                                           pkg.applicationInfo.seinfo);
5425                if (ret < 0) {
5426                    // Error from installer
5427                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5428                            "Unable to create data dirs [errorCode=" + ret + "]");
5429                }
5430
5431                if (dataPath.exists()) {
5432                    pkg.applicationInfo.dataDir = dataPath.getPath();
5433                } else {
5434                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5435                    pkg.applicationInfo.dataDir = null;
5436                }
5437            }
5438
5439            pkgSetting.uidError = uidError;
5440        }
5441
5442        final String path = scanFile.getPath();
5443        final String codePath = pkg.applicationInfo.getCodePath();
5444        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5445        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5446            setBundledAppAbisAndRoots(pkg, pkgSetting);
5447
5448            // If we haven't found any native libraries for the app, check if it has
5449            // renderscript code. We'll need to force the app to 32 bit if it has
5450            // renderscript bitcode.
5451            if (pkg.applicationInfo.primaryCpuAbi == null
5452                    && pkg.applicationInfo.secondaryCpuAbi == null
5453                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5454                NativeLibraryHelper.Handle handle = null;
5455                try {
5456                    handle = NativeLibraryHelper.Handle.create(scanFile);
5457                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5458                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5459                    }
5460                } catch (IOException ioe) {
5461                    Slog.w(TAG, "Error scanning system app : " + ioe);
5462                } finally {
5463                    IoUtils.closeQuietly(handle);
5464                }
5465            }
5466
5467            setNativeLibraryPaths(pkg);
5468        } else {
5469            // TODO: We can probably be smarter about this stuff. For installed apps,
5470            // we can calculate this information at install time once and for all. For
5471            // system apps, we can probably assume that this information doesn't change
5472            // after the first boot scan. As things stand, we do lots of unnecessary work.
5473
5474            // Give ourselves some initial paths; we'll come back for another
5475            // pass once we've determined ABI below.
5476            setNativeLibraryPaths(pkg);
5477
5478            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5479            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5480            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5481
5482            NativeLibraryHelper.Handle handle = null;
5483            try {
5484                handle = NativeLibraryHelper.Handle.create(scanFile);
5485                // TODO(multiArch): This can be null for apps that didn't go through the
5486                // usual installation process. We can calculate it again, like we
5487                // do during install time.
5488                //
5489                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5490                // unnecessary.
5491                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5492
5493                // Null out the abis so that they can be recalculated.
5494                pkg.applicationInfo.primaryCpuAbi = null;
5495                pkg.applicationInfo.secondaryCpuAbi = null;
5496                if (isMultiArch(pkg.applicationInfo)) {
5497                    // Warn if we've set an abiOverride for multi-lib packages..
5498                    // By definition, we need to copy both 32 and 64 bit libraries for
5499                    // such packages.
5500                    if (pkg.cpuAbiOverride != null
5501                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5502                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5503                    }
5504
5505                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5506                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5507                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5508                        if (isAsec) {
5509                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5510                        } else {
5511                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5512                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5513                                    useIsaSpecificSubdirs);
5514                        }
5515                    }
5516
5517                    maybeThrowExceptionForMultiArchCopy(
5518                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5519
5520                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5521                        if (isAsec) {
5522                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5523                        } else {
5524                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5525                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5526                                    useIsaSpecificSubdirs);
5527                        }
5528                    }
5529
5530                    maybeThrowExceptionForMultiArchCopy(
5531                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5532
5533                    if (abi64 >= 0) {
5534                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5535                    }
5536
5537                    if (abi32 >= 0) {
5538                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5539                        if (abi64 >= 0) {
5540                            pkg.applicationInfo.secondaryCpuAbi = abi;
5541                        } else {
5542                            pkg.applicationInfo.primaryCpuAbi = abi;
5543                        }
5544                    }
5545                } else {
5546                    String[] abiList = (cpuAbiOverride != null) ?
5547                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5548
5549                    // Enable gross and lame hacks for apps that are built with old
5550                    // SDK tools. We must scan their APKs for renderscript bitcode and
5551                    // not launch them if it's present. Don't bother checking on devices
5552                    // that don't have 64 bit support.
5553                    boolean needsRenderScriptOverride = false;
5554                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5555                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5556                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5557                        needsRenderScriptOverride = true;
5558                    }
5559
5560                    final int copyRet;
5561                    if (isAsec) {
5562                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5563                    } else {
5564                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5565                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5566                    }
5567
5568                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5569                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5570                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5571                    }
5572
5573                    if (copyRet >= 0) {
5574                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5575                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5576                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5577                    } else if (needsRenderScriptOverride) {
5578                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5579                    }
5580                }
5581            } catch (IOException ioe) {
5582                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5583            } finally {
5584                IoUtils.closeQuietly(handle);
5585            }
5586
5587            // Now that we've calculated the ABIs and determined if it's an internal app,
5588            // we will go ahead and populate the nativeLibraryPath.
5589            setNativeLibraryPaths(pkg);
5590
5591            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5592            final int[] userIds = sUserManager.getUserIds();
5593            synchronized (mInstallLock) {
5594                // Create a native library symlink only if we have native libraries
5595                // and if the native libraries are 32 bit libraries. We do not provide
5596                // this symlink for 64 bit libraries.
5597                if (pkg.applicationInfo.primaryCpuAbi != null &&
5598                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5599                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5600                    for (int userId : userIds) {
5601                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5602                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5603                                    "Failed linking native library dir (user=" + userId + ")");
5604                        }
5605                    }
5606                }
5607            }
5608        }
5609
5610        // This is a special case for the "system" package, where the ABI is
5611        // dictated by the zygote configuration (and init.rc). We should keep track
5612        // of this ABI so that we can deal with "normal" applications that run under
5613        // the same UID correctly.
5614        if (mPlatformPackage == pkg) {
5615            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5616                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5617        }
5618
5619        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5620        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5621        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5622        // Copy the derived override back to the parsed package, so that we can
5623        // update the package settings accordingly.
5624        pkg.cpuAbiOverride = cpuAbiOverride;
5625
5626        if (DEBUG_ABI_SELECTION) {
5627            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5628                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5629                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5630        }
5631
5632        // Push the derived path down into PackageSettings so we know what to
5633        // clean up at uninstall time.
5634        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5635
5636        if (DEBUG_ABI_SELECTION) {
5637            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5638                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5639                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5640        }
5641
5642        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5643            // We don't do this here during boot because we can do it all
5644            // at once after scanning all existing packages.
5645            //
5646            // We also do this *before* we perform dexopt on this package, so that
5647            // we can avoid redundant dexopts, and also to make sure we've got the
5648            // code and package path correct.
5649            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5650                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5651        }
5652
5653        if ((scanFlags & SCAN_NO_DEX) == 0) {
5654            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5655                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5656                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5657            }
5658        }
5659
5660        if (mFactoryTest && pkg.requestedPermissions.contains(
5661                android.Manifest.permission.FACTORY_TEST)) {
5662            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5663        }
5664
5665        ArrayList<PackageParser.Package> clientLibPkgs = null;
5666
5667        // writer
5668        synchronized (mPackages) {
5669            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5670                // Only system apps can add new shared libraries.
5671                if (pkg.libraryNames != null) {
5672                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5673                        String name = pkg.libraryNames.get(i);
5674                        boolean allowed = false;
5675                        if (isUpdatedSystemApp(pkg)) {
5676                            // New library entries can only be added through the
5677                            // system image.  This is important to get rid of a lot
5678                            // of nasty edge cases: for example if we allowed a non-
5679                            // system update of the app to add a library, then uninstalling
5680                            // the update would make the library go away, and assumptions
5681                            // we made such as through app install filtering would now
5682                            // have allowed apps on the device which aren't compatible
5683                            // with it.  Better to just have the restriction here, be
5684                            // conservative, and create many fewer cases that can negatively
5685                            // impact the user experience.
5686                            final PackageSetting sysPs = mSettings
5687                                    .getDisabledSystemPkgLPr(pkg.packageName);
5688                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5689                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5690                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5691                                        allowed = true;
5692                                        allowed = true;
5693                                        break;
5694                                    }
5695                                }
5696                            }
5697                        } else {
5698                            allowed = true;
5699                        }
5700                        if (allowed) {
5701                            if (!mSharedLibraries.containsKey(name)) {
5702                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5703                            } else if (!name.equals(pkg.packageName)) {
5704                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5705                                        + name + " already exists; skipping");
5706                            }
5707                        } else {
5708                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5709                                    + name + " that is not declared on system image; skipping");
5710                        }
5711                    }
5712                    if ((scanFlags&SCAN_BOOTING) == 0) {
5713                        // If we are not booting, we need to update any applications
5714                        // that are clients of our shared library.  If we are booting,
5715                        // this will all be done once the scan is complete.
5716                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5717                    }
5718                }
5719            }
5720        }
5721
5722        // We also need to dexopt any apps that are dependent on this library.  Note that
5723        // if these fail, we should abort the install since installing the library will
5724        // result in some apps being broken.
5725        if (clientLibPkgs != null) {
5726            if ((scanFlags & SCAN_NO_DEX) == 0) {
5727                for (int i = 0; i < clientLibPkgs.size(); i++) {
5728                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5729                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
5730                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5731                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5732                                "scanPackageLI failed to dexopt clientLibPkgs");
5733                    }
5734                }
5735            }
5736        }
5737
5738        // Request the ActivityManager to kill the process(only for existing packages)
5739        // so that we do not end up in a confused state while the user is still using the older
5740        // version of the application while the new one gets installed.
5741        if ((scanFlags & SCAN_REPLACING) != 0) {
5742            killApplication(pkg.applicationInfo.packageName,
5743                        pkg.applicationInfo.uid, "update pkg");
5744        }
5745
5746        // Also need to kill any apps that are dependent on the library.
5747        if (clientLibPkgs != null) {
5748            for (int i=0; i<clientLibPkgs.size(); i++) {
5749                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5750                killApplication(clientPkg.applicationInfo.packageName,
5751                        clientPkg.applicationInfo.uid, "update lib");
5752            }
5753        }
5754
5755        // writer
5756        synchronized (mPackages) {
5757            // We don't expect installation to fail beyond this point
5758
5759            // Add the new setting to mSettings
5760            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5761            // Add the new setting to mPackages
5762            mPackages.put(pkg.applicationInfo.packageName, pkg);
5763            // Make sure we don't accidentally delete its data.
5764            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5765            while (iter.hasNext()) {
5766                PackageCleanItem item = iter.next();
5767                if (pkgName.equals(item.packageName)) {
5768                    iter.remove();
5769                }
5770            }
5771
5772            // Take care of first install / last update times.
5773            if (currentTime != 0) {
5774                if (pkgSetting.firstInstallTime == 0) {
5775                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5776                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5777                    pkgSetting.lastUpdateTime = currentTime;
5778                }
5779            } else if (pkgSetting.firstInstallTime == 0) {
5780                // We need *something*.  Take time time stamp of the file.
5781                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5782            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5783                if (scanFileTime != pkgSetting.timeStamp) {
5784                    // A package on the system image has changed; consider this
5785                    // to be an update.
5786                    pkgSetting.lastUpdateTime = scanFileTime;
5787                }
5788            }
5789
5790            // Add the package's KeySets to the global KeySetManagerService
5791            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5792            try {
5793                // Old KeySetData no longer valid.
5794                ksms.removeAppKeySetDataLPw(pkg.packageName);
5795                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5796                if (pkg.mKeySetMapping != null) {
5797                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5798                            pkg.mKeySetMapping.entrySet()) {
5799                        if (entry.getValue() != null) {
5800                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5801                                                          entry.getValue(), entry.getKey());
5802                        }
5803                    }
5804                    if (pkg.mUpgradeKeySets != null) {
5805                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5806                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5807                        }
5808                    }
5809                }
5810            } catch (NullPointerException e) {
5811                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5812            } catch (IllegalArgumentException e) {
5813                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5814            }
5815
5816            int N = pkg.providers.size();
5817            StringBuilder r = null;
5818            int i;
5819            for (i=0; i<N; i++) {
5820                PackageParser.Provider p = pkg.providers.get(i);
5821                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5822                        p.info.processName, pkg.applicationInfo.uid);
5823                mProviders.addProvider(p);
5824                p.syncable = p.info.isSyncable;
5825                if (p.info.authority != null) {
5826                    String names[] = p.info.authority.split(";");
5827                    p.info.authority = null;
5828                    for (int j = 0; j < names.length; j++) {
5829                        if (j == 1 && p.syncable) {
5830                            // We only want the first authority for a provider to possibly be
5831                            // syncable, so if we already added this provider using a different
5832                            // authority clear the syncable flag. We copy the provider before
5833                            // changing it because the mProviders object contains a reference
5834                            // to a provider that we don't want to change.
5835                            // Only do this for the second authority since the resulting provider
5836                            // object can be the same for all future authorities for this provider.
5837                            p = new PackageParser.Provider(p);
5838                            p.syncable = false;
5839                        }
5840                        if (!mProvidersByAuthority.containsKey(names[j])) {
5841                            mProvidersByAuthority.put(names[j], p);
5842                            if (p.info.authority == null) {
5843                                p.info.authority = names[j];
5844                            } else {
5845                                p.info.authority = p.info.authority + ";" + names[j];
5846                            }
5847                            if (DEBUG_PACKAGE_SCANNING) {
5848                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5849                                    Log.d(TAG, "Registered content provider: " + names[j]
5850                                            + ", className = " + p.info.name + ", isSyncable = "
5851                                            + p.info.isSyncable);
5852                            }
5853                        } else {
5854                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5855                            Slog.w(TAG, "Skipping provider name " + names[j] +
5856                                    " (in package " + pkg.applicationInfo.packageName +
5857                                    "): name already used by "
5858                                    + ((other != null && other.getComponentName() != null)
5859                                            ? other.getComponentName().getPackageName() : "?"));
5860                        }
5861                    }
5862                }
5863                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5864                    if (r == null) {
5865                        r = new StringBuilder(256);
5866                    } else {
5867                        r.append(' ');
5868                    }
5869                    r.append(p.info.name);
5870                }
5871            }
5872            if (r != null) {
5873                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5874            }
5875
5876            N = pkg.services.size();
5877            r = null;
5878            for (i=0; i<N; i++) {
5879                PackageParser.Service s = pkg.services.get(i);
5880                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5881                        s.info.processName, pkg.applicationInfo.uid);
5882                mServices.addService(s);
5883                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5884                    if (r == null) {
5885                        r = new StringBuilder(256);
5886                    } else {
5887                        r.append(' ');
5888                    }
5889                    r.append(s.info.name);
5890                }
5891            }
5892            if (r != null) {
5893                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5894            }
5895
5896            N = pkg.receivers.size();
5897            r = null;
5898            for (i=0; i<N; i++) {
5899                PackageParser.Activity a = pkg.receivers.get(i);
5900                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5901                        a.info.processName, pkg.applicationInfo.uid);
5902                mReceivers.addActivity(a, "receiver");
5903                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5904                    if (r == null) {
5905                        r = new StringBuilder(256);
5906                    } else {
5907                        r.append(' ');
5908                    }
5909                    r.append(a.info.name);
5910                }
5911            }
5912            if (r != null) {
5913                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5914            }
5915
5916            N = pkg.activities.size();
5917            r = null;
5918            for (i=0; i<N; i++) {
5919                PackageParser.Activity a = pkg.activities.get(i);
5920                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5921                        a.info.processName, pkg.applicationInfo.uid);
5922                mActivities.addActivity(a, "activity");
5923                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5924                    if (r == null) {
5925                        r = new StringBuilder(256);
5926                    } else {
5927                        r.append(' ');
5928                    }
5929                    r.append(a.info.name);
5930                }
5931            }
5932            if (r != null) {
5933                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5934            }
5935
5936            N = pkg.permissionGroups.size();
5937            r = null;
5938            for (i=0; i<N; i++) {
5939                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5940                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5941                if (cur == null) {
5942                    mPermissionGroups.put(pg.info.name, pg);
5943                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5944                        if (r == null) {
5945                            r = new StringBuilder(256);
5946                        } else {
5947                            r.append(' ');
5948                        }
5949                        r.append(pg.info.name);
5950                    }
5951                } else {
5952                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5953                            + pg.info.packageName + " ignored: original from "
5954                            + cur.info.packageName);
5955                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5956                        if (r == null) {
5957                            r = new StringBuilder(256);
5958                        } else {
5959                            r.append(' ');
5960                        }
5961                        r.append("DUP:");
5962                        r.append(pg.info.name);
5963                    }
5964                }
5965            }
5966            if (r != null) {
5967                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5968            }
5969
5970            N = pkg.permissions.size();
5971            r = null;
5972            for (i=0; i<N; i++) {
5973                PackageParser.Permission p = pkg.permissions.get(i);
5974                HashMap<String, BasePermission> permissionMap =
5975                        p.tree ? mSettings.mPermissionTrees
5976                        : mSettings.mPermissions;
5977                p.group = mPermissionGroups.get(p.info.group);
5978                if (p.info.group == null || p.group != null) {
5979                    BasePermission bp = permissionMap.get(p.info.name);
5980
5981                    // Allow system apps to redefine non-system permissions
5982                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
5983                        final boolean currentOwnerIsSystem = (bp.perm != null
5984                                && isSystemApp(bp.perm.owner));
5985                        if (isSystemApp(p.owner)) {
5986                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
5987                                // It's a built-in permission and no owner, take ownership now
5988                                bp.packageSetting = pkgSetting;
5989                                bp.perm = p;
5990                                bp.uid = pkg.applicationInfo.uid;
5991                                bp.sourcePackage = p.info.packageName;
5992                            } else if (!currentOwnerIsSystem) {
5993                                String msg = "New decl " + p.owner + " of permission  "
5994                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
5995                                reportSettingsProblem(Log.WARN, msg);
5996                                bp = null;
5997                            }
5998                        }
5999                    }
6000
6001                    if (bp == null) {
6002                        bp = new BasePermission(p.info.name, p.info.packageName,
6003                                BasePermission.TYPE_NORMAL);
6004                        permissionMap.put(p.info.name, bp);
6005                    }
6006
6007                    if (bp.perm == null) {
6008                        if (bp.sourcePackage == null
6009                                || bp.sourcePackage.equals(p.info.packageName)) {
6010                            BasePermission tree = findPermissionTreeLP(p.info.name);
6011                            if (tree == null
6012                                    || tree.sourcePackage.equals(p.info.packageName)) {
6013                                bp.packageSetting = pkgSetting;
6014                                bp.perm = p;
6015                                bp.uid = pkg.applicationInfo.uid;
6016                                bp.sourcePackage = p.info.packageName;
6017                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6018                                    if (r == null) {
6019                                        r = new StringBuilder(256);
6020                                    } else {
6021                                        r.append(' ');
6022                                    }
6023                                    r.append(p.info.name);
6024                                }
6025                            } else {
6026                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6027                                        + p.info.packageName + " ignored: base tree "
6028                                        + tree.name + " is from package "
6029                                        + tree.sourcePackage);
6030                            }
6031                        } else {
6032                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6033                                    + p.info.packageName + " ignored: original from "
6034                                    + bp.sourcePackage);
6035                        }
6036                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6037                        if (r == null) {
6038                            r = new StringBuilder(256);
6039                        } else {
6040                            r.append(' ');
6041                        }
6042                        r.append("DUP:");
6043                        r.append(p.info.name);
6044                    }
6045                    if (bp.perm == p) {
6046                        bp.protectionLevel = p.info.protectionLevel;
6047                    }
6048                } else {
6049                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6050                            + p.info.packageName + " ignored: no group "
6051                            + p.group);
6052                }
6053            }
6054            if (r != null) {
6055                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6056            }
6057
6058            N = pkg.instrumentation.size();
6059            r = null;
6060            for (i=0; i<N; i++) {
6061                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6062                a.info.packageName = pkg.applicationInfo.packageName;
6063                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6064                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6065                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6066                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6067                a.info.dataDir = pkg.applicationInfo.dataDir;
6068
6069                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6070                // need other information about the application, like the ABI and what not ?
6071                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6072                mInstrumentation.put(a.getComponentName(), a);
6073                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6074                    if (r == null) {
6075                        r = new StringBuilder(256);
6076                    } else {
6077                        r.append(' ');
6078                    }
6079                    r.append(a.info.name);
6080                }
6081            }
6082            if (r != null) {
6083                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6084            }
6085
6086            if (pkg.protectedBroadcasts != null) {
6087                N = pkg.protectedBroadcasts.size();
6088                for (i=0; i<N; i++) {
6089                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6090                }
6091            }
6092
6093            pkgSetting.setTimeStamp(scanFileTime);
6094
6095            // Create idmap files for pairs of (packages, overlay packages).
6096            // Note: "android", ie framework-res.apk, is handled by native layers.
6097            if (pkg.mOverlayTarget != null) {
6098                // This is an overlay package.
6099                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6100                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6101                        mOverlays.put(pkg.mOverlayTarget,
6102                                new HashMap<String, PackageParser.Package>());
6103                    }
6104                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6105                    map.put(pkg.packageName, pkg);
6106                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6107                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6108                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6109                                "scanPackageLI failed to createIdmap");
6110                    }
6111                }
6112            } else if (mOverlays.containsKey(pkg.packageName) &&
6113                    !pkg.packageName.equals("android")) {
6114                // This is a regular package, with one or more known overlay packages.
6115                createIdmapsForPackageLI(pkg);
6116            }
6117        }
6118
6119        return pkg;
6120    }
6121
6122    /**
6123     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6124     * i.e, so that all packages can be run inside a single process if required.
6125     *
6126     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6127     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6128     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6129     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6130     * updating a package that belongs to a shared user.
6131     *
6132     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6133     * adds unnecessary complexity.
6134     */
6135    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6136            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6137        String requiredInstructionSet = null;
6138        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6139            requiredInstructionSet = VMRuntime.getInstructionSet(
6140                     scannedPackage.applicationInfo.primaryCpuAbi);
6141        }
6142
6143        PackageSetting requirer = null;
6144        for (PackageSetting ps : packagesForUser) {
6145            // If packagesForUser contains scannedPackage, we skip it. This will happen
6146            // when scannedPackage is an update of an existing package. Without this check,
6147            // we will never be able to change the ABI of any package belonging to a shared
6148            // user, even if it's compatible with other packages.
6149            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6150                if (ps.primaryCpuAbiString == null) {
6151                    continue;
6152                }
6153
6154                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6155                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6156                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6157                    // this but there's not much we can do.
6158                    String errorMessage = "Instruction set mismatch, "
6159                            + ((requirer == null) ? "[caller]" : requirer)
6160                            + " requires " + requiredInstructionSet + " whereas " + ps
6161                            + " requires " + instructionSet;
6162                    Slog.w(TAG, errorMessage);
6163                }
6164
6165                if (requiredInstructionSet == null) {
6166                    requiredInstructionSet = instructionSet;
6167                    requirer = ps;
6168                }
6169            }
6170        }
6171
6172        if (requiredInstructionSet != null) {
6173            String adjustedAbi;
6174            if (requirer != null) {
6175                // requirer != null implies that either scannedPackage was null or that scannedPackage
6176                // did not require an ABI, in which case we have to adjust scannedPackage to match
6177                // the ABI of the set (which is the same as requirer's ABI)
6178                adjustedAbi = requirer.primaryCpuAbiString;
6179                if (scannedPackage != null) {
6180                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6181                }
6182            } else {
6183                // requirer == null implies that we're updating all ABIs in the set to
6184                // match scannedPackage.
6185                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6186            }
6187
6188            for (PackageSetting ps : packagesForUser) {
6189                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6190                    if (ps.primaryCpuAbiString != null) {
6191                        continue;
6192                    }
6193
6194                    ps.primaryCpuAbiString = adjustedAbi;
6195                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6196                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6197                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6198
6199                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6200                                deferDexOpt, true) == DEX_OPT_FAILED) {
6201                            ps.primaryCpuAbiString = null;
6202                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6203                            return;
6204                        } else {
6205                            mInstaller.rmdex(ps.codePathString,
6206                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6207                        }
6208                    }
6209                }
6210            }
6211        }
6212    }
6213
6214    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6215        synchronized (mPackages) {
6216            mResolverReplaced = true;
6217            // Set up information for custom user intent resolution activity.
6218            mResolveActivity.applicationInfo = pkg.applicationInfo;
6219            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6220            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6221            mResolveActivity.processName = null;
6222            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6223            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6224                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6225            mResolveActivity.theme = 0;
6226            mResolveActivity.exported = true;
6227            mResolveActivity.enabled = true;
6228            mResolveInfo.activityInfo = mResolveActivity;
6229            mResolveInfo.priority = 0;
6230            mResolveInfo.preferredOrder = 0;
6231            mResolveInfo.match = 0;
6232            mResolveComponentName = mCustomResolverComponentName;
6233            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6234                    mResolveComponentName);
6235        }
6236    }
6237
6238    private static String calculateBundledApkRoot(final String codePathString) {
6239        final File codePath = new File(codePathString);
6240        final File codeRoot;
6241        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6242            codeRoot = Environment.getRootDirectory();
6243        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6244            codeRoot = Environment.getOemDirectory();
6245        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6246            codeRoot = Environment.getVendorDirectory();
6247        } else {
6248            // Unrecognized code path; take its top real segment as the apk root:
6249            // e.g. /something/app/blah.apk => /something
6250            try {
6251                File f = codePath.getCanonicalFile();
6252                File parent = f.getParentFile();    // non-null because codePath is a file
6253                File tmp;
6254                while ((tmp = parent.getParentFile()) != null) {
6255                    f = parent;
6256                    parent = tmp;
6257                }
6258                codeRoot = f;
6259                Slog.w(TAG, "Unrecognized code path "
6260                        + codePath + " - using " + codeRoot);
6261            } catch (IOException e) {
6262                // Can't canonicalize the code path -- shenanigans?
6263                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6264                return Environment.getRootDirectory().getPath();
6265            }
6266        }
6267        return codeRoot.getPath();
6268    }
6269
6270    /**
6271     * Derive and set the location of native libraries for the given package,
6272     * which varies depending on where and how the package was installed.
6273     */
6274    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6275        final ApplicationInfo info = pkg.applicationInfo;
6276        final String codePath = pkg.codePath;
6277        final File codeFile = new File(codePath);
6278        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6279        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6280
6281        info.nativeLibraryRootDir = null;
6282        info.nativeLibraryRootRequiresIsa = false;
6283        info.nativeLibraryDir = null;
6284        info.secondaryNativeLibraryDir = null;
6285
6286        if (isApkFile(codeFile)) {
6287            // Monolithic install
6288            if (bundledApp) {
6289                // If "/system/lib64/apkname" exists, assume that is the per-package
6290                // native library directory to use; otherwise use "/system/lib/apkname".
6291                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6292                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6293                        getPrimaryInstructionSet(info));
6294
6295                // This is a bundled system app so choose the path based on the ABI.
6296                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6297                // is just the default path.
6298                final String apkName = deriveCodePathName(codePath);
6299                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6300                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6301                        apkName).getAbsolutePath();
6302
6303                if (info.secondaryCpuAbi != null) {
6304                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6305                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6306                            secondaryLibDir, apkName).getAbsolutePath();
6307                }
6308            } else if (asecApp) {
6309                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6310                        .getAbsolutePath();
6311            } else {
6312                final String apkName = deriveCodePathName(codePath);
6313                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6314                        .getAbsolutePath();
6315            }
6316
6317            info.nativeLibraryRootRequiresIsa = false;
6318            info.nativeLibraryDir = info.nativeLibraryRootDir;
6319        } else {
6320            // Cluster install
6321            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6322            info.nativeLibraryRootRequiresIsa = true;
6323
6324            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6325                    getPrimaryInstructionSet(info)).getAbsolutePath();
6326
6327            if (info.secondaryCpuAbi != null) {
6328                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6329                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6330            }
6331        }
6332    }
6333
6334    /**
6335     * Calculate the abis and roots for a bundled app. These can uniquely
6336     * be determined from the contents of the system partition, i.e whether
6337     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6338     * of this information, and instead assume that the system was built
6339     * sensibly.
6340     */
6341    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6342                                           PackageSetting pkgSetting) {
6343        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6344
6345        // If "/system/lib64/apkname" exists, assume that is the per-package
6346        // native library directory to use; otherwise use "/system/lib/apkname".
6347        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6348        setBundledAppAbi(pkg, apkRoot, apkName);
6349        // pkgSetting might be null during rescan following uninstall of updates
6350        // to a bundled app, so accommodate that possibility.  The settings in
6351        // that case will be established later from the parsed package.
6352        //
6353        // If the settings aren't null, sync them up with what we've just derived.
6354        // note that apkRoot isn't stored in the package settings.
6355        if (pkgSetting != null) {
6356            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6357            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6358        }
6359    }
6360
6361    /**
6362     * Deduces the ABI of a bundled app and sets the relevant fields on the
6363     * parsed pkg object.
6364     *
6365     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6366     *        under which system libraries are installed.
6367     * @param apkName the name of the installed package.
6368     */
6369    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6370        final File codeFile = new File(pkg.codePath);
6371
6372        final boolean has64BitLibs;
6373        final boolean has32BitLibs;
6374        if (isApkFile(codeFile)) {
6375            // Monolithic install
6376            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6377            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6378        } else {
6379            // Cluster install
6380            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6381            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6382                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6383                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6384                has64BitLibs = (new File(rootDir, isa)).exists();
6385            } else {
6386                has64BitLibs = false;
6387            }
6388            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6389                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6390                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6391                has32BitLibs = (new File(rootDir, isa)).exists();
6392            } else {
6393                has32BitLibs = false;
6394            }
6395        }
6396
6397        if (has64BitLibs && !has32BitLibs) {
6398            // The package has 64 bit libs, but not 32 bit libs. Its primary
6399            // ABI should be 64 bit. We can safely assume here that the bundled
6400            // native libraries correspond to the most preferred ABI in the list.
6401
6402            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6403            pkg.applicationInfo.secondaryCpuAbi = null;
6404        } else if (has32BitLibs && !has64BitLibs) {
6405            // The package has 32 bit libs but not 64 bit libs. Its primary
6406            // ABI should be 32 bit.
6407
6408            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6409            pkg.applicationInfo.secondaryCpuAbi = null;
6410        } else if (has32BitLibs && has64BitLibs) {
6411            // The application has both 64 and 32 bit bundled libraries. We check
6412            // here that the app declares multiArch support, and warn if it doesn't.
6413            //
6414            // We will be lenient here and record both ABIs. The primary will be the
6415            // ABI that's higher on the list, i.e, a device that's configured to prefer
6416            // 64 bit apps will see a 64 bit primary ABI,
6417
6418            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6419                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6420            }
6421
6422            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6423                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6424                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6425            } else {
6426                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6427                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6428            }
6429        } else {
6430            pkg.applicationInfo.primaryCpuAbi = null;
6431            pkg.applicationInfo.secondaryCpuAbi = null;
6432        }
6433    }
6434
6435    private void killApplication(String pkgName, int appId, String reason) {
6436        // Request the ActivityManager to kill the process(only for existing packages)
6437        // so that we do not end up in a confused state while the user is still using the older
6438        // version of the application while the new one gets installed.
6439        IActivityManager am = ActivityManagerNative.getDefault();
6440        if (am != null) {
6441            try {
6442                am.killApplicationWithAppId(pkgName, appId, reason);
6443            } catch (RemoteException e) {
6444            }
6445        }
6446    }
6447
6448    void removePackageLI(PackageSetting ps, boolean chatty) {
6449        if (DEBUG_INSTALL) {
6450            if (chatty)
6451                Log.d(TAG, "Removing package " + ps.name);
6452        }
6453
6454        // writer
6455        synchronized (mPackages) {
6456            mPackages.remove(ps.name);
6457            final PackageParser.Package pkg = ps.pkg;
6458            if (pkg != null) {
6459                cleanPackageDataStructuresLILPw(pkg, chatty);
6460            }
6461        }
6462    }
6463
6464    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6465        if (DEBUG_INSTALL) {
6466            if (chatty)
6467                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6468        }
6469
6470        // writer
6471        synchronized (mPackages) {
6472            mPackages.remove(pkg.applicationInfo.packageName);
6473            cleanPackageDataStructuresLILPw(pkg, chatty);
6474        }
6475    }
6476
6477    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6478        int N = pkg.providers.size();
6479        StringBuilder r = null;
6480        int i;
6481        for (i=0; i<N; i++) {
6482            PackageParser.Provider p = pkg.providers.get(i);
6483            mProviders.removeProvider(p);
6484            if (p.info.authority == null) {
6485
6486                /* There was another ContentProvider with this authority when
6487                 * this app was installed so this authority is null,
6488                 * Ignore it as we don't have to unregister the provider.
6489                 */
6490                continue;
6491            }
6492            String names[] = p.info.authority.split(";");
6493            for (int j = 0; j < names.length; j++) {
6494                if (mProvidersByAuthority.get(names[j]) == p) {
6495                    mProvidersByAuthority.remove(names[j]);
6496                    if (DEBUG_REMOVE) {
6497                        if (chatty)
6498                            Log.d(TAG, "Unregistered content provider: " + names[j]
6499                                    + ", className = " + p.info.name + ", isSyncable = "
6500                                    + p.info.isSyncable);
6501                    }
6502                }
6503            }
6504            if (DEBUG_REMOVE && chatty) {
6505                if (r == null) {
6506                    r = new StringBuilder(256);
6507                } else {
6508                    r.append(' ');
6509                }
6510                r.append(p.info.name);
6511            }
6512        }
6513        if (r != null) {
6514            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6515        }
6516
6517        N = pkg.services.size();
6518        r = null;
6519        for (i=0; i<N; i++) {
6520            PackageParser.Service s = pkg.services.get(i);
6521            mServices.removeService(s);
6522            if (chatty) {
6523                if (r == null) {
6524                    r = new StringBuilder(256);
6525                } else {
6526                    r.append(' ');
6527                }
6528                r.append(s.info.name);
6529            }
6530        }
6531        if (r != null) {
6532            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6533        }
6534
6535        N = pkg.receivers.size();
6536        r = null;
6537        for (i=0; i<N; i++) {
6538            PackageParser.Activity a = pkg.receivers.get(i);
6539            mReceivers.removeActivity(a, "receiver");
6540            if (DEBUG_REMOVE && chatty) {
6541                if (r == null) {
6542                    r = new StringBuilder(256);
6543                } else {
6544                    r.append(' ');
6545                }
6546                r.append(a.info.name);
6547            }
6548        }
6549        if (r != null) {
6550            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6551        }
6552
6553        N = pkg.activities.size();
6554        r = null;
6555        for (i=0; i<N; i++) {
6556            PackageParser.Activity a = pkg.activities.get(i);
6557            mActivities.removeActivity(a, "activity");
6558            if (DEBUG_REMOVE && chatty) {
6559                if (r == null) {
6560                    r = new StringBuilder(256);
6561                } else {
6562                    r.append(' ');
6563                }
6564                r.append(a.info.name);
6565            }
6566        }
6567        if (r != null) {
6568            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6569        }
6570
6571        N = pkg.permissions.size();
6572        r = null;
6573        for (i=0; i<N; i++) {
6574            PackageParser.Permission p = pkg.permissions.get(i);
6575            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6576            if (bp == null) {
6577                bp = mSettings.mPermissionTrees.get(p.info.name);
6578            }
6579            if (bp != null && bp.perm == p) {
6580                bp.perm = null;
6581                if (DEBUG_REMOVE && chatty) {
6582                    if (r == null) {
6583                        r = new StringBuilder(256);
6584                    } else {
6585                        r.append(' ');
6586                    }
6587                    r.append(p.info.name);
6588                }
6589            }
6590            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6591                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6592                if (appOpPerms != null) {
6593                    appOpPerms.remove(pkg.packageName);
6594                }
6595            }
6596        }
6597        if (r != null) {
6598            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6599        }
6600
6601        N = pkg.requestedPermissions.size();
6602        r = null;
6603        for (i=0; i<N; i++) {
6604            String perm = pkg.requestedPermissions.get(i);
6605            BasePermission bp = mSettings.mPermissions.get(perm);
6606            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6607                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6608                if (appOpPerms != null) {
6609                    appOpPerms.remove(pkg.packageName);
6610                    if (appOpPerms.isEmpty()) {
6611                        mAppOpPermissionPackages.remove(perm);
6612                    }
6613                }
6614            }
6615        }
6616        if (r != null) {
6617            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6618        }
6619
6620        N = pkg.instrumentation.size();
6621        r = null;
6622        for (i=0; i<N; i++) {
6623            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6624            mInstrumentation.remove(a.getComponentName());
6625            if (DEBUG_REMOVE && chatty) {
6626                if (r == null) {
6627                    r = new StringBuilder(256);
6628                } else {
6629                    r.append(' ');
6630                }
6631                r.append(a.info.name);
6632            }
6633        }
6634        if (r != null) {
6635            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6636        }
6637
6638        r = null;
6639        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6640            // Only system apps can hold shared libraries.
6641            if (pkg.libraryNames != null) {
6642                for (i=0; i<pkg.libraryNames.size(); i++) {
6643                    String name = pkg.libraryNames.get(i);
6644                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6645                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6646                        mSharedLibraries.remove(name);
6647                        if (DEBUG_REMOVE && chatty) {
6648                            if (r == null) {
6649                                r = new StringBuilder(256);
6650                            } else {
6651                                r.append(' ');
6652                            }
6653                            r.append(name);
6654                        }
6655                    }
6656                }
6657            }
6658        }
6659        if (r != null) {
6660            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6661        }
6662    }
6663
6664    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6665        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6666            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6667                return true;
6668            }
6669        }
6670        return false;
6671    }
6672
6673    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6674    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6675    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6676
6677    private void updatePermissionsLPw(String changingPkg,
6678            PackageParser.Package pkgInfo, int flags) {
6679        // Make sure there are no dangling permission trees.
6680        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6681        while (it.hasNext()) {
6682            final BasePermission bp = it.next();
6683            if (bp.packageSetting == null) {
6684                // We may not yet have parsed the package, so just see if
6685                // we still know about its settings.
6686                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6687            }
6688            if (bp.packageSetting == null) {
6689                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6690                        + " from package " + bp.sourcePackage);
6691                it.remove();
6692            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6693                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6694                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6695                            + " from package " + bp.sourcePackage);
6696                    flags |= UPDATE_PERMISSIONS_ALL;
6697                    it.remove();
6698                }
6699            }
6700        }
6701
6702        // Make sure all dynamic permissions have been assigned to a package,
6703        // and make sure there are no dangling permissions.
6704        it = mSettings.mPermissions.values().iterator();
6705        while (it.hasNext()) {
6706            final BasePermission bp = it.next();
6707            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6708                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6709                        + bp.name + " pkg=" + bp.sourcePackage
6710                        + " info=" + bp.pendingInfo);
6711                if (bp.packageSetting == null && bp.pendingInfo != null) {
6712                    final BasePermission tree = findPermissionTreeLP(bp.name);
6713                    if (tree != null && tree.perm != null) {
6714                        bp.packageSetting = tree.packageSetting;
6715                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6716                                new PermissionInfo(bp.pendingInfo));
6717                        bp.perm.info.packageName = tree.perm.info.packageName;
6718                        bp.perm.info.name = bp.name;
6719                        bp.uid = tree.uid;
6720                    }
6721                }
6722            }
6723            if (bp.packageSetting == null) {
6724                // We may not yet have parsed the package, so just see if
6725                // we still know about its settings.
6726                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6727            }
6728            if (bp.packageSetting == null) {
6729                Slog.w(TAG, "Removing dangling permission: " + bp.name
6730                        + " from package " + bp.sourcePackage);
6731                it.remove();
6732            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6733                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6734                    Slog.i(TAG, "Removing old permission: " + bp.name
6735                            + " from package " + bp.sourcePackage);
6736                    flags |= UPDATE_PERMISSIONS_ALL;
6737                    it.remove();
6738                }
6739            }
6740        }
6741
6742        // Now update the permissions for all packages, in particular
6743        // replace the granted permissions of the system packages.
6744        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6745            for (PackageParser.Package pkg : mPackages.values()) {
6746                if (pkg != pkgInfo) {
6747                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6748                            changingPkg);
6749                }
6750            }
6751        }
6752
6753        if (pkgInfo != null) {
6754            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6755        }
6756    }
6757
6758    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6759            String packageOfInterest) {
6760        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6761        if (ps == null) {
6762            return;
6763        }
6764        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6765        HashSet<String> origPermissions = gp.grantedPermissions;
6766        boolean changedPermission = false;
6767
6768        if (replace) {
6769            ps.permissionsFixed = false;
6770            if (gp == ps) {
6771                origPermissions = new HashSet<String>(gp.grantedPermissions);
6772                gp.grantedPermissions.clear();
6773                gp.gids = mGlobalGids;
6774            }
6775        }
6776
6777        if (gp.gids == null) {
6778            gp.gids = mGlobalGids;
6779        }
6780
6781        final int N = pkg.requestedPermissions.size();
6782        for (int i=0; i<N; i++) {
6783            final String name = pkg.requestedPermissions.get(i);
6784            final boolean required = pkg.requestedPermissionsRequired.get(i);
6785            final BasePermission bp = mSettings.mPermissions.get(name);
6786            if (DEBUG_INSTALL) {
6787                if (gp != ps) {
6788                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6789                }
6790            }
6791
6792            if (bp == null || bp.packageSetting == null) {
6793                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6794                    Slog.w(TAG, "Unknown permission " + name
6795                            + " in package " + pkg.packageName);
6796                }
6797                continue;
6798            }
6799
6800            final String perm = bp.name;
6801            boolean allowed;
6802            boolean allowedSig = false;
6803            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6804                // Keep track of app op permissions.
6805                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6806                if (pkgs == null) {
6807                    pkgs = new ArraySet<>();
6808                    mAppOpPermissionPackages.put(bp.name, pkgs);
6809                }
6810                pkgs.add(pkg.packageName);
6811            }
6812            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6813            if (level == PermissionInfo.PROTECTION_NORMAL
6814                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6815                // We grant a normal or dangerous permission if any of the following
6816                // are true:
6817                // 1) The permission is required
6818                // 2) The permission is optional, but was granted in the past
6819                // 3) The permission is optional, but was requested by an
6820                //    app in /system (not /data)
6821                //
6822                // Otherwise, reject the permission.
6823                allowed = (required || origPermissions.contains(perm)
6824                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6825            } else if (bp.packageSetting == null) {
6826                // This permission is invalid; skip it.
6827                allowed = false;
6828            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6829                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6830                if (allowed) {
6831                    allowedSig = true;
6832                }
6833            } else {
6834                allowed = false;
6835            }
6836            if (DEBUG_INSTALL) {
6837                if (gp != ps) {
6838                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6839                }
6840            }
6841            if (allowed) {
6842                if (!isSystemApp(ps) && ps.permissionsFixed) {
6843                    // If this is an existing, non-system package, then
6844                    // we can't add any new permissions to it.
6845                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6846                        // Except...  if this is a permission that was added
6847                        // to the platform (note: need to only do this when
6848                        // updating the platform).
6849                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6850                    }
6851                }
6852                if (allowed) {
6853                    if (!gp.grantedPermissions.contains(perm)) {
6854                        changedPermission = true;
6855                        gp.grantedPermissions.add(perm);
6856                        gp.gids = appendInts(gp.gids, bp.gids);
6857                    } else if (!ps.haveGids) {
6858                        gp.gids = appendInts(gp.gids, bp.gids);
6859                    }
6860                } else {
6861                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6862                        Slog.w(TAG, "Not granting permission " + perm
6863                                + " to package " + pkg.packageName
6864                                + " because it was previously installed without");
6865                    }
6866                }
6867            } else {
6868                if (gp.grantedPermissions.remove(perm)) {
6869                    changedPermission = true;
6870                    gp.gids = removeInts(gp.gids, bp.gids);
6871                    Slog.i(TAG, "Un-granting permission " + perm
6872                            + " from package " + pkg.packageName
6873                            + " (protectionLevel=" + bp.protectionLevel
6874                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6875                            + ")");
6876                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6877                    // Don't print warning for app op permissions, since it is fine for them
6878                    // not to be granted, there is a UI for the user to decide.
6879                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6880                        Slog.w(TAG, "Not granting permission " + perm
6881                                + " to package " + pkg.packageName
6882                                + " (protectionLevel=" + bp.protectionLevel
6883                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6884                                + ")");
6885                    }
6886                }
6887            }
6888        }
6889
6890        if ((changedPermission || replace) && !ps.permissionsFixed &&
6891                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6892            // This is the first that we have heard about this package, so the
6893            // permissions we have now selected are fixed until explicitly
6894            // changed.
6895            ps.permissionsFixed = true;
6896        }
6897        ps.haveGids = true;
6898    }
6899
6900    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6901        boolean allowed = false;
6902        final int NP = PackageParser.NEW_PERMISSIONS.length;
6903        for (int ip=0; ip<NP; ip++) {
6904            final PackageParser.NewPermissionInfo npi
6905                    = PackageParser.NEW_PERMISSIONS[ip];
6906            if (npi.name.equals(perm)
6907                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6908                allowed = true;
6909                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6910                        + pkg.packageName);
6911                break;
6912            }
6913        }
6914        return allowed;
6915    }
6916
6917    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6918                                          BasePermission bp, HashSet<String> origPermissions) {
6919        boolean allowed;
6920        allowed = (compareSignatures(
6921                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6922                        == PackageManager.SIGNATURE_MATCH)
6923                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6924                        == PackageManager.SIGNATURE_MATCH);
6925        if (!allowed && (bp.protectionLevel
6926                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6927            if (isSystemApp(pkg)) {
6928                // For updated system applications, a system permission
6929                // is granted only if it had been defined by the original application.
6930                if (isUpdatedSystemApp(pkg)) {
6931                    final PackageSetting sysPs = mSettings
6932                            .getDisabledSystemPkgLPr(pkg.packageName);
6933                    final GrantedPermissions origGp = sysPs.sharedUser != null
6934                            ? sysPs.sharedUser : sysPs;
6935
6936                    if (origGp.grantedPermissions.contains(perm)) {
6937                        // If the original was granted this permission, we take
6938                        // that grant decision as read and propagate it to the
6939                        // update.
6940                        allowed = true;
6941                    } else {
6942                        // The system apk may have been updated with an older
6943                        // version of the one on the data partition, but which
6944                        // granted a new system permission that it didn't have
6945                        // before.  In this case we do want to allow the app to
6946                        // now get the new permission if the ancestral apk is
6947                        // privileged to get it.
6948                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6949                            for (int j=0;
6950                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6951                                if (perm.equals(
6952                                        sysPs.pkg.requestedPermissions.get(j))) {
6953                                    allowed = true;
6954                                    break;
6955                                }
6956                            }
6957                        }
6958                    }
6959                } else {
6960                    allowed = isPrivilegedApp(pkg);
6961                }
6962            }
6963        }
6964        if (!allowed && (bp.protectionLevel
6965                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6966            // For development permissions, a development permission
6967            // is granted only if it was already granted.
6968            allowed = origPermissions.contains(perm);
6969        }
6970        return allowed;
6971    }
6972
6973    final class ActivityIntentResolver
6974            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6975        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6976                boolean defaultOnly, int userId) {
6977            if (!sUserManager.exists(userId)) return null;
6978            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6979            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6980        }
6981
6982        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6983                int userId) {
6984            if (!sUserManager.exists(userId)) return null;
6985            mFlags = flags;
6986            return super.queryIntent(intent, resolvedType,
6987                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6988        }
6989
6990        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6991                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6992            if (!sUserManager.exists(userId)) return null;
6993            if (packageActivities == null) {
6994                return null;
6995            }
6996            mFlags = flags;
6997            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6998            final int N = packageActivities.size();
6999            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7000                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7001
7002            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7003            for (int i = 0; i < N; ++i) {
7004                intentFilters = packageActivities.get(i).intents;
7005                if (intentFilters != null && intentFilters.size() > 0) {
7006                    PackageParser.ActivityIntentInfo[] array =
7007                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7008                    intentFilters.toArray(array);
7009                    listCut.add(array);
7010                }
7011            }
7012            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7013        }
7014
7015        public final void addActivity(PackageParser.Activity a, String type) {
7016            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7017            mActivities.put(a.getComponentName(), a);
7018            if (DEBUG_SHOW_INFO)
7019                Log.v(
7020                TAG, "  " + type + " " +
7021                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7022            if (DEBUG_SHOW_INFO)
7023                Log.v(TAG, "    Class=" + a.info.name);
7024            final int NI = a.intents.size();
7025            for (int j=0; j<NI; j++) {
7026                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7027                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7028                    intent.setPriority(0);
7029                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7030                            + a.className + " with priority > 0, forcing to 0");
7031                }
7032                if (DEBUG_SHOW_INFO) {
7033                    Log.v(TAG, "    IntentFilter:");
7034                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7035                }
7036                if (!intent.debugCheck()) {
7037                    Log.w(TAG, "==> For Activity " + a.info.name);
7038                }
7039                addFilter(intent);
7040            }
7041        }
7042
7043        public final void removeActivity(PackageParser.Activity a, String type) {
7044            mActivities.remove(a.getComponentName());
7045            if (DEBUG_SHOW_INFO) {
7046                Log.v(TAG, "  " + type + " "
7047                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7048                                : a.info.name) + ":");
7049                Log.v(TAG, "    Class=" + a.info.name);
7050            }
7051            final int NI = a.intents.size();
7052            for (int j=0; j<NI; j++) {
7053                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7054                if (DEBUG_SHOW_INFO) {
7055                    Log.v(TAG, "    IntentFilter:");
7056                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7057                }
7058                removeFilter(intent);
7059            }
7060        }
7061
7062        @Override
7063        protected boolean allowFilterResult(
7064                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7065            ActivityInfo filterAi = filter.activity.info;
7066            for (int i=dest.size()-1; i>=0; i--) {
7067                ActivityInfo destAi = dest.get(i).activityInfo;
7068                if (destAi.name == filterAi.name
7069                        && destAi.packageName == filterAi.packageName) {
7070                    return false;
7071                }
7072            }
7073            return true;
7074        }
7075
7076        @Override
7077        protected ActivityIntentInfo[] newArray(int size) {
7078            return new ActivityIntentInfo[size];
7079        }
7080
7081        @Override
7082        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7083            if (!sUserManager.exists(userId)) return true;
7084            PackageParser.Package p = filter.activity.owner;
7085            if (p != null) {
7086                PackageSetting ps = (PackageSetting)p.mExtras;
7087                if (ps != null) {
7088                    // System apps are never considered stopped for purposes of
7089                    // filtering, because there may be no way for the user to
7090                    // actually re-launch them.
7091                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7092                            && ps.getStopped(userId);
7093                }
7094            }
7095            return false;
7096        }
7097
7098        @Override
7099        protected boolean isPackageForFilter(String packageName,
7100                PackageParser.ActivityIntentInfo info) {
7101            return packageName.equals(info.activity.owner.packageName);
7102        }
7103
7104        @Override
7105        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7106                int match, int userId) {
7107            if (!sUserManager.exists(userId)) return null;
7108            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7109                return null;
7110            }
7111            final PackageParser.Activity activity = info.activity;
7112            if (mSafeMode && (activity.info.applicationInfo.flags
7113                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7114                return null;
7115            }
7116            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7117            if (ps == null) {
7118                return null;
7119            }
7120            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7121                    ps.readUserState(userId), userId);
7122            if (ai == null) {
7123                return null;
7124            }
7125            final ResolveInfo res = new ResolveInfo();
7126            res.activityInfo = ai;
7127            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7128                res.filter = info;
7129            }
7130            res.priority = info.getPriority();
7131            res.preferredOrder = activity.owner.mPreferredOrder;
7132            //System.out.println("Result: " + res.activityInfo.className +
7133            //                   " = " + res.priority);
7134            res.match = match;
7135            res.isDefault = info.hasDefault;
7136            res.labelRes = info.labelRes;
7137            res.nonLocalizedLabel = info.nonLocalizedLabel;
7138            if (userNeedsBadging(userId)) {
7139                res.noResourceId = true;
7140            } else {
7141                res.icon = info.icon;
7142            }
7143            res.system = isSystemApp(res.activityInfo.applicationInfo);
7144            return res;
7145        }
7146
7147        @Override
7148        protected void sortResults(List<ResolveInfo> results) {
7149            Collections.sort(results, mResolvePrioritySorter);
7150        }
7151
7152        @Override
7153        protected void dumpFilter(PrintWriter out, String prefix,
7154                PackageParser.ActivityIntentInfo filter) {
7155            out.print(prefix); out.print(
7156                    Integer.toHexString(System.identityHashCode(filter.activity)));
7157                    out.print(' ');
7158                    filter.activity.printComponentShortName(out);
7159                    out.print(" filter ");
7160                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7161        }
7162
7163//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7164//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7165//            final List<ResolveInfo> retList = Lists.newArrayList();
7166//            while (i.hasNext()) {
7167//                final ResolveInfo resolveInfo = i.next();
7168//                if (isEnabledLP(resolveInfo.activityInfo)) {
7169//                    retList.add(resolveInfo);
7170//                }
7171//            }
7172//            return retList;
7173//        }
7174
7175        // Keys are String (activity class name), values are Activity.
7176        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7177                = new HashMap<ComponentName, PackageParser.Activity>();
7178        private int mFlags;
7179    }
7180
7181    private final class ServiceIntentResolver
7182            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7183        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7184                boolean defaultOnly, int userId) {
7185            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7186            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7187        }
7188
7189        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7190                int userId) {
7191            if (!sUserManager.exists(userId)) return null;
7192            mFlags = flags;
7193            return super.queryIntent(intent, resolvedType,
7194                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7195        }
7196
7197        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7198                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7199            if (!sUserManager.exists(userId)) return null;
7200            if (packageServices == null) {
7201                return null;
7202            }
7203            mFlags = flags;
7204            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7205            final int N = packageServices.size();
7206            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7207                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7208
7209            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7210            for (int i = 0; i < N; ++i) {
7211                intentFilters = packageServices.get(i).intents;
7212                if (intentFilters != null && intentFilters.size() > 0) {
7213                    PackageParser.ServiceIntentInfo[] array =
7214                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7215                    intentFilters.toArray(array);
7216                    listCut.add(array);
7217                }
7218            }
7219            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7220        }
7221
7222        public final void addService(PackageParser.Service s) {
7223            mServices.put(s.getComponentName(), s);
7224            if (DEBUG_SHOW_INFO) {
7225                Log.v(TAG, "  "
7226                        + (s.info.nonLocalizedLabel != null
7227                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7228                Log.v(TAG, "    Class=" + s.info.name);
7229            }
7230            final int NI = s.intents.size();
7231            int j;
7232            for (j=0; j<NI; j++) {
7233                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7234                if (DEBUG_SHOW_INFO) {
7235                    Log.v(TAG, "    IntentFilter:");
7236                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7237                }
7238                if (!intent.debugCheck()) {
7239                    Log.w(TAG, "==> For Service " + s.info.name);
7240                }
7241                addFilter(intent);
7242            }
7243        }
7244
7245        public final void removeService(PackageParser.Service s) {
7246            mServices.remove(s.getComponentName());
7247            if (DEBUG_SHOW_INFO) {
7248                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7249                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7250                Log.v(TAG, "    Class=" + s.info.name);
7251            }
7252            final int NI = s.intents.size();
7253            int j;
7254            for (j=0; j<NI; j++) {
7255                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7256                if (DEBUG_SHOW_INFO) {
7257                    Log.v(TAG, "    IntentFilter:");
7258                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7259                }
7260                removeFilter(intent);
7261            }
7262        }
7263
7264        @Override
7265        protected boolean allowFilterResult(
7266                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7267            ServiceInfo filterSi = filter.service.info;
7268            for (int i=dest.size()-1; i>=0; i--) {
7269                ServiceInfo destAi = dest.get(i).serviceInfo;
7270                if (destAi.name == filterSi.name
7271                        && destAi.packageName == filterSi.packageName) {
7272                    return false;
7273                }
7274            }
7275            return true;
7276        }
7277
7278        @Override
7279        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7280            return new PackageParser.ServiceIntentInfo[size];
7281        }
7282
7283        @Override
7284        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7285            if (!sUserManager.exists(userId)) return true;
7286            PackageParser.Package p = filter.service.owner;
7287            if (p != null) {
7288                PackageSetting ps = (PackageSetting)p.mExtras;
7289                if (ps != null) {
7290                    // System apps are never considered stopped for purposes of
7291                    // filtering, because there may be no way for the user to
7292                    // actually re-launch them.
7293                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7294                            && ps.getStopped(userId);
7295                }
7296            }
7297            return false;
7298        }
7299
7300        @Override
7301        protected boolean isPackageForFilter(String packageName,
7302                PackageParser.ServiceIntentInfo info) {
7303            return packageName.equals(info.service.owner.packageName);
7304        }
7305
7306        @Override
7307        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7308                int match, int userId) {
7309            if (!sUserManager.exists(userId)) return null;
7310            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7311            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7312                return null;
7313            }
7314            final PackageParser.Service service = info.service;
7315            if (mSafeMode && (service.info.applicationInfo.flags
7316                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7317                return null;
7318            }
7319            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7320            if (ps == null) {
7321                return null;
7322            }
7323            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7324                    ps.readUserState(userId), userId);
7325            if (si == null) {
7326                return null;
7327            }
7328            final ResolveInfo res = new ResolveInfo();
7329            res.serviceInfo = si;
7330            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7331                res.filter = filter;
7332            }
7333            res.priority = info.getPriority();
7334            res.preferredOrder = service.owner.mPreferredOrder;
7335            //System.out.println("Result: " + res.activityInfo.className +
7336            //                   " = " + res.priority);
7337            res.match = match;
7338            res.isDefault = info.hasDefault;
7339            res.labelRes = info.labelRes;
7340            res.nonLocalizedLabel = info.nonLocalizedLabel;
7341            res.icon = info.icon;
7342            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7343            return res;
7344        }
7345
7346        @Override
7347        protected void sortResults(List<ResolveInfo> results) {
7348            Collections.sort(results, mResolvePrioritySorter);
7349        }
7350
7351        @Override
7352        protected void dumpFilter(PrintWriter out, String prefix,
7353                PackageParser.ServiceIntentInfo filter) {
7354            out.print(prefix); out.print(
7355                    Integer.toHexString(System.identityHashCode(filter.service)));
7356                    out.print(' ');
7357                    filter.service.printComponentShortName(out);
7358                    out.print(" filter ");
7359                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7360        }
7361
7362//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7363//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7364//            final List<ResolveInfo> retList = Lists.newArrayList();
7365//            while (i.hasNext()) {
7366//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7367//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7368//                    retList.add(resolveInfo);
7369//                }
7370//            }
7371//            return retList;
7372//        }
7373
7374        // Keys are String (activity class name), values are Activity.
7375        private final HashMap<ComponentName, PackageParser.Service> mServices
7376                = new HashMap<ComponentName, PackageParser.Service>();
7377        private int mFlags;
7378    };
7379
7380    private final class ProviderIntentResolver
7381            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7382        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7383                boolean defaultOnly, int userId) {
7384            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7385            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7386        }
7387
7388        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7389                int userId) {
7390            if (!sUserManager.exists(userId))
7391                return null;
7392            mFlags = flags;
7393            return super.queryIntent(intent, resolvedType,
7394                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7395        }
7396
7397        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7398                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7399            if (!sUserManager.exists(userId))
7400                return null;
7401            if (packageProviders == null) {
7402                return null;
7403            }
7404            mFlags = flags;
7405            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7406            final int N = packageProviders.size();
7407            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7408                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7409
7410            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7411            for (int i = 0; i < N; ++i) {
7412                intentFilters = packageProviders.get(i).intents;
7413                if (intentFilters != null && intentFilters.size() > 0) {
7414                    PackageParser.ProviderIntentInfo[] array =
7415                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7416                    intentFilters.toArray(array);
7417                    listCut.add(array);
7418                }
7419            }
7420            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7421        }
7422
7423        public final void addProvider(PackageParser.Provider p) {
7424            if (mProviders.containsKey(p.getComponentName())) {
7425                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7426                return;
7427            }
7428
7429            mProviders.put(p.getComponentName(), p);
7430            if (DEBUG_SHOW_INFO) {
7431                Log.v(TAG, "  "
7432                        + (p.info.nonLocalizedLabel != null
7433                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7434                Log.v(TAG, "    Class=" + p.info.name);
7435            }
7436            final int NI = p.intents.size();
7437            int j;
7438            for (j = 0; j < NI; j++) {
7439                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7440                if (DEBUG_SHOW_INFO) {
7441                    Log.v(TAG, "    IntentFilter:");
7442                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7443                }
7444                if (!intent.debugCheck()) {
7445                    Log.w(TAG, "==> For Provider " + p.info.name);
7446                }
7447                addFilter(intent);
7448            }
7449        }
7450
7451        public final void removeProvider(PackageParser.Provider p) {
7452            mProviders.remove(p.getComponentName());
7453            if (DEBUG_SHOW_INFO) {
7454                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7455                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7456                Log.v(TAG, "    Class=" + p.info.name);
7457            }
7458            final int NI = p.intents.size();
7459            int j;
7460            for (j = 0; j < NI; j++) {
7461                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7462                if (DEBUG_SHOW_INFO) {
7463                    Log.v(TAG, "    IntentFilter:");
7464                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7465                }
7466                removeFilter(intent);
7467            }
7468        }
7469
7470        @Override
7471        protected boolean allowFilterResult(
7472                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7473            ProviderInfo filterPi = filter.provider.info;
7474            for (int i = dest.size() - 1; i >= 0; i--) {
7475                ProviderInfo destPi = dest.get(i).providerInfo;
7476                if (destPi.name == filterPi.name
7477                        && destPi.packageName == filterPi.packageName) {
7478                    return false;
7479                }
7480            }
7481            return true;
7482        }
7483
7484        @Override
7485        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7486            return new PackageParser.ProviderIntentInfo[size];
7487        }
7488
7489        @Override
7490        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7491            if (!sUserManager.exists(userId))
7492                return true;
7493            PackageParser.Package p = filter.provider.owner;
7494            if (p != null) {
7495                PackageSetting ps = (PackageSetting) p.mExtras;
7496                if (ps != null) {
7497                    // System apps are never considered stopped for purposes of
7498                    // filtering, because there may be no way for the user to
7499                    // actually re-launch them.
7500                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7501                            && ps.getStopped(userId);
7502                }
7503            }
7504            return false;
7505        }
7506
7507        @Override
7508        protected boolean isPackageForFilter(String packageName,
7509                PackageParser.ProviderIntentInfo info) {
7510            return packageName.equals(info.provider.owner.packageName);
7511        }
7512
7513        @Override
7514        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7515                int match, int userId) {
7516            if (!sUserManager.exists(userId))
7517                return null;
7518            final PackageParser.ProviderIntentInfo info = filter;
7519            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7520                return null;
7521            }
7522            final PackageParser.Provider provider = info.provider;
7523            if (mSafeMode && (provider.info.applicationInfo.flags
7524                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7525                return null;
7526            }
7527            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7528            if (ps == null) {
7529                return null;
7530            }
7531            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7532                    ps.readUserState(userId), userId);
7533            if (pi == null) {
7534                return null;
7535            }
7536            final ResolveInfo res = new ResolveInfo();
7537            res.providerInfo = pi;
7538            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7539                res.filter = filter;
7540            }
7541            res.priority = info.getPriority();
7542            res.preferredOrder = provider.owner.mPreferredOrder;
7543            res.match = match;
7544            res.isDefault = info.hasDefault;
7545            res.labelRes = info.labelRes;
7546            res.nonLocalizedLabel = info.nonLocalizedLabel;
7547            res.icon = info.icon;
7548            res.system = isSystemApp(res.providerInfo.applicationInfo);
7549            return res;
7550        }
7551
7552        @Override
7553        protected void sortResults(List<ResolveInfo> results) {
7554            Collections.sort(results, mResolvePrioritySorter);
7555        }
7556
7557        @Override
7558        protected void dumpFilter(PrintWriter out, String prefix,
7559                PackageParser.ProviderIntentInfo filter) {
7560            out.print(prefix);
7561            out.print(
7562                    Integer.toHexString(System.identityHashCode(filter.provider)));
7563            out.print(' ');
7564            filter.provider.printComponentShortName(out);
7565            out.print(" filter ");
7566            out.println(Integer.toHexString(System.identityHashCode(filter)));
7567        }
7568
7569        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7570                = new HashMap<ComponentName, PackageParser.Provider>();
7571        private int mFlags;
7572    };
7573
7574    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7575            new Comparator<ResolveInfo>() {
7576        public int compare(ResolveInfo r1, ResolveInfo r2) {
7577            int v1 = r1.priority;
7578            int v2 = r2.priority;
7579            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7580            if (v1 != v2) {
7581                return (v1 > v2) ? -1 : 1;
7582            }
7583            v1 = r1.preferredOrder;
7584            v2 = r2.preferredOrder;
7585            if (v1 != v2) {
7586                return (v1 > v2) ? -1 : 1;
7587            }
7588            if (r1.isDefault != r2.isDefault) {
7589                return r1.isDefault ? -1 : 1;
7590            }
7591            v1 = r1.match;
7592            v2 = r2.match;
7593            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7594            if (v1 != v2) {
7595                return (v1 > v2) ? -1 : 1;
7596            }
7597            if (r1.system != r2.system) {
7598                return r1.system ? -1 : 1;
7599            }
7600            return 0;
7601        }
7602    };
7603
7604    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7605            new Comparator<ProviderInfo>() {
7606        public int compare(ProviderInfo p1, ProviderInfo p2) {
7607            final int v1 = p1.initOrder;
7608            final int v2 = p2.initOrder;
7609            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7610        }
7611    };
7612
7613    static final void sendPackageBroadcast(String action, String pkg,
7614            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7615            int[] userIds) {
7616        IActivityManager am = ActivityManagerNative.getDefault();
7617        if (am != null) {
7618            try {
7619                if (userIds == null) {
7620                    userIds = am.getRunningUserIds();
7621                }
7622                for (int id : userIds) {
7623                    final Intent intent = new Intent(action,
7624                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7625                    if (extras != null) {
7626                        intent.putExtras(extras);
7627                    }
7628                    if (targetPkg != null) {
7629                        intent.setPackage(targetPkg);
7630                    }
7631                    // Modify the UID when posting to other users
7632                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7633                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7634                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7635                        intent.putExtra(Intent.EXTRA_UID, uid);
7636                    }
7637                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7638                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7639                    if (DEBUG_BROADCASTS) {
7640                        RuntimeException here = new RuntimeException("here");
7641                        here.fillInStackTrace();
7642                        Slog.d(TAG, "Sending to user " + id + ": "
7643                                + intent.toShortString(false, true, false, false)
7644                                + " " + intent.getExtras(), here);
7645                    }
7646                    am.broadcastIntent(null, intent, null, finishedReceiver,
7647                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7648                            finishedReceiver != null, false, id);
7649                }
7650            } catch (RemoteException ex) {
7651            }
7652        }
7653    }
7654
7655    /**
7656     * Check if the external storage media is available. This is true if there
7657     * is a mounted external storage medium or if the external storage is
7658     * emulated.
7659     */
7660    private boolean isExternalMediaAvailable() {
7661        return mMediaMounted || Environment.isExternalStorageEmulated();
7662    }
7663
7664    @Override
7665    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7666        // writer
7667        synchronized (mPackages) {
7668            if (!isExternalMediaAvailable()) {
7669                // If the external storage is no longer mounted at this point,
7670                // the caller may not have been able to delete all of this
7671                // packages files and can not delete any more.  Bail.
7672                return null;
7673            }
7674            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7675            if (lastPackage != null) {
7676                pkgs.remove(lastPackage);
7677            }
7678            if (pkgs.size() > 0) {
7679                return pkgs.get(0);
7680            }
7681        }
7682        return null;
7683    }
7684
7685    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7686        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7687                userId, andCode ? 1 : 0, packageName);
7688        if (mSystemReady) {
7689            msg.sendToTarget();
7690        } else {
7691            if (mPostSystemReadyMessages == null) {
7692                mPostSystemReadyMessages = new ArrayList<>();
7693            }
7694            mPostSystemReadyMessages.add(msg);
7695        }
7696    }
7697
7698    void startCleaningPackages() {
7699        // reader
7700        synchronized (mPackages) {
7701            if (!isExternalMediaAvailable()) {
7702                return;
7703            }
7704            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7705                return;
7706            }
7707        }
7708        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7709        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7710        IActivityManager am = ActivityManagerNative.getDefault();
7711        if (am != null) {
7712            try {
7713                am.startService(null, intent, null, UserHandle.USER_OWNER);
7714            } catch (RemoteException e) {
7715            }
7716        }
7717    }
7718
7719    @Override
7720    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7721            int installFlags, String installerPackageName, VerificationParams verificationParams,
7722            String packageAbiOverride) {
7723        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7724                packageAbiOverride, UserHandle.getCallingUserId());
7725    }
7726
7727    @Override
7728    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7729            int installFlags, String installerPackageName, VerificationParams verificationParams,
7730            String packageAbiOverride, int userId) {
7731        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
7732
7733        final int callingUid = Binder.getCallingUid();
7734        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
7735
7736        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7737            try {
7738                if (observer != null) {
7739                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7740                }
7741            } catch (RemoteException re) {
7742            }
7743            return;
7744        }
7745
7746        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
7747            installFlags |= PackageManager.INSTALL_FROM_ADB;
7748
7749        } else {
7750            // Caller holds INSTALL_PACKAGES permission, so we're less strict
7751            // about installerPackageName.
7752
7753            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
7754            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
7755        }
7756
7757        UserHandle user;
7758        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7759            user = UserHandle.ALL;
7760        } else {
7761            user = new UserHandle(userId);
7762        }
7763
7764        verificationParams.setInstallerUid(callingUid);
7765
7766        final File originFile = new File(originPath);
7767        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7768
7769        final Message msg = mHandler.obtainMessage(INIT_COPY);
7770        msg.obj = new InstallParams(origin, observer, installFlags,
7771                installerPackageName, verificationParams, user, packageAbiOverride);
7772        mHandler.sendMessage(msg);
7773    }
7774
7775    void installStage(String packageName, File stagedDir, String stagedCid,
7776            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7777            String installerPackageName, int installerUid, UserHandle user) {
7778        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7779                params.referrerUri, installerUid, null);
7780
7781        final OriginInfo origin;
7782        if (stagedDir != null) {
7783            origin = OriginInfo.fromStagedFile(stagedDir);
7784        } else {
7785            origin = OriginInfo.fromStagedContainer(stagedCid);
7786        }
7787
7788        final Message msg = mHandler.obtainMessage(INIT_COPY);
7789        msg.obj = new InstallParams(origin, observer, params.installFlags,
7790                installerPackageName, verifParams, user, params.abiOverride);
7791        mHandler.sendMessage(msg);
7792    }
7793
7794    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7795        Bundle extras = new Bundle(1);
7796        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7797
7798        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7799                packageName, extras, null, null, new int[] {userId});
7800        try {
7801            IActivityManager am = ActivityManagerNative.getDefault();
7802            final boolean isSystem =
7803                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7804            if (isSystem && am.isUserRunning(userId, false)) {
7805                // The just-installed/enabled app is bundled on the system, so presumed
7806                // to be able to run automatically without needing an explicit launch.
7807                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7808                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7809                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7810                        .setPackage(packageName);
7811                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7812                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7813            }
7814        } catch (RemoteException e) {
7815            // shouldn't happen
7816            Slog.w(TAG, "Unable to bootstrap installed package", e);
7817        }
7818    }
7819
7820    @Override
7821    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7822            int userId) {
7823        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7824        PackageSetting pkgSetting;
7825        final int uid = Binder.getCallingUid();
7826        enforceCrossUserPermission(uid, userId, true, true,
7827                "setApplicationHiddenSetting for user " + userId);
7828
7829        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7830            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7831            return false;
7832        }
7833
7834        long callingId = Binder.clearCallingIdentity();
7835        try {
7836            boolean sendAdded = false;
7837            boolean sendRemoved = false;
7838            // writer
7839            synchronized (mPackages) {
7840                pkgSetting = mSettings.mPackages.get(packageName);
7841                if (pkgSetting == null) {
7842                    return false;
7843                }
7844                if (pkgSetting.getHidden(userId) != hidden) {
7845                    pkgSetting.setHidden(hidden, userId);
7846                    mSettings.writePackageRestrictionsLPr(userId);
7847                    if (hidden) {
7848                        sendRemoved = true;
7849                    } else {
7850                        sendAdded = true;
7851                    }
7852                }
7853            }
7854            if (sendAdded) {
7855                sendPackageAddedForUser(packageName, pkgSetting, userId);
7856                return true;
7857            }
7858            if (sendRemoved) {
7859                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7860                        "hiding pkg");
7861                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7862            }
7863        } finally {
7864            Binder.restoreCallingIdentity(callingId);
7865        }
7866        return false;
7867    }
7868
7869    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7870            int userId) {
7871        final PackageRemovedInfo info = new PackageRemovedInfo();
7872        info.removedPackage = packageName;
7873        info.removedUsers = new int[] {userId};
7874        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7875        info.sendBroadcast(false, false, false);
7876    }
7877
7878    /**
7879     * Returns true if application is not found or there was an error. Otherwise it returns
7880     * the hidden state of the package for the given user.
7881     */
7882    @Override
7883    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7884        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7885        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7886                false, "getApplicationHidden for user " + userId);
7887        PackageSetting pkgSetting;
7888        long callingId = Binder.clearCallingIdentity();
7889        try {
7890            // writer
7891            synchronized (mPackages) {
7892                pkgSetting = mSettings.mPackages.get(packageName);
7893                if (pkgSetting == null) {
7894                    return true;
7895                }
7896                return pkgSetting.getHidden(userId);
7897            }
7898        } finally {
7899            Binder.restoreCallingIdentity(callingId);
7900        }
7901    }
7902
7903    /**
7904     * @hide
7905     */
7906    @Override
7907    public int installExistingPackageAsUser(String packageName, int userId) {
7908        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7909                null);
7910        PackageSetting pkgSetting;
7911        final int uid = Binder.getCallingUid();
7912        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
7913                + userId);
7914        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7915            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7916        }
7917
7918        long callingId = Binder.clearCallingIdentity();
7919        try {
7920            boolean sendAdded = false;
7921            Bundle extras = new Bundle(1);
7922
7923            // writer
7924            synchronized (mPackages) {
7925                pkgSetting = mSettings.mPackages.get(packageName);
7926                if (pkgSetting == null) {
7927                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7928                }
7929                if (!pkgSetting.getInstalled(userId)) {
7930                    pkgSetting.setInstalled(true, userId);
7931                    pkgSetting.setHidden(false, userId);
7932                    mSettings.writePackageRestrictionsLPr(userId);
7933                    sendAdded = true;
7934                }
7935            }
7936
7937            if (sendAdded) {
7938                sendPackageAddedForUser(packageName, pkgSetting, userId);
7939            }
7940        } finally {
7941            Binder.restoreCallingIdentity(callingId);
7942        }
7943
7944        return PackageManager.INSTALL_SUCCEEDED;
7945    }
7946
7947    boolean isUserRestricted(int userId, String restrictionKey) {
7948        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7949        if (restrictions.getBoolean(restrictionKey, false)) {
7950            Log.w(TAG, "User is restricted: " + restrictionKey);
7951            return true;
7952        }
7953        return false;
7954    }
7955
7956    @Override
7957    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7958        mContext.enforceCallingOrSelfPermission(
7959                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7960                "Only package verification agents can verify applications");
7961
7962        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7963        final PackageVerificationResponse response = new PackageVerificationResponse(
7964                verificationCode, Binder.getCallingUid());
7965        msg.arg1 = id;
7966        msg.obj = response;
7967        mHandler.sendMessage(msg);
7968    }
7969
7970    @Override
7971    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7972            long millisecondsToDelay) {
7973        mContext.enforceCallingOrSelfPermission(
7974                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7975                "Only package verification agents can extend verification timeouts");
7976
7977        final PackageVerificationState state = mPendingVerification.get(id);
7978        final PackageVerificationResponse response = new PackageVerificationResponse(
7979                verificationCodeAtTimeout, Binder.getCallingUid());
7980
7981        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7982            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7983        }
7984        if (millisecondsToDelay < 0) {
7985            millisecondsToDelay = 0;
7986        }
7987        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7988                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7989            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7990        }
7991
7992        if ((state != null) && !state.timeoutExtended()) {
7993            state.extendTimeout();
7994
7995            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7996            msg.arg1 = id;
7997            msg.obj = response;
7998            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7999        }
8000    }
8001
8002    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8003            int verificationCode, UserHandle user) {
8004        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8005        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8006        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8007        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8008        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8009
8010        mContext.sendBroadcastAsUser(intent, user,
8011                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8012    }
8013
8014    private ComponentName matchComponentForVerifier(String packageName,
8015            List<ResolveInfo> receivers) {
8016        ActivityInfo targetReceiver = null;
8017
8018        final int NR = receivers.size();
8019        for (int i = 0; i < NR; i++) {
8020            final ResolveInfo info = receivers.get(i);
8021            if (info.activityInfo == null) {
8022                continue;
8023            }
8024
8025            if (packageName.equals(info.activityInfo.packageName)) {
8026                targetReceiver = info.activityInfo;
8027                break;
8028            }
8029        }
8030
8031        if (targetReceiver == null) {
8032            return null;
8033        }
8034
8035        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8036    }
8037
8038    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8039            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8040        if (pkgInfo.verifiers.length == 0) {
8041            return null;
8042        }
8043
8044        final int N = pkgInfo.verifiers.length;
8045        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8046        for (int i = 0; i < N; i++) {
8047            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8048
8049            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8050                    receivers);
8051            if (comp == null) {
8052                continue;
8053            }
8054
8055            final int verifierUid = getUidForVerifier(verifierInfo);
8056            if (verifierUid == -1) {
8057                continue;
8058            }
8059
8060            if (DEBUG_VERIFY) {
8061                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8062                        + " with the correct signature");
8063            }
8064            sufficientVerifiers.add(comp);
8065            verificationState.addSufficientVerifier(verifierUid);
8066        }
8067
8068        return sufficientVerifiers;
8069    }
8070
8071    private int getUidForVerifier(VerifierInfo verifierInfo) {
8072        synchronized (mPackages) {
8073            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8074            if (pkg == null) {
8075                return -1;
8076            } else if (pkg.mSignatures.length != 1) {
8077                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8078                        + " has more than one signature; ignoring");
8079                return -1;
8080            }
8081
8082            /*
8083             * If the public key of the package's signature does not match
8084             * our expected public key, then this is a different package and
8085             * we should skip.
8086             */
8087
8088            final byte[] expectedPublicKey;
8089            try {
8090                final Signature verifierSig = pkg.mSignatures[0];
8091                final PublicKey publicKey = verifierSig.getPublicKey();
8092                expectedPublicKey = publicKey.getEncoded();
8093            } catch (CertificateException e) {
8094                return -1;
8095            }
8096
8097            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8098
8099            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8100                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8101                        + " does not have the expected public key; ignoring");
8102                return -1;
8103            }
8104
8105            return pkg.applicationInfo.uid;
8106        }
8107    }
8108
8109    @Override
8110    public void finishPackageInstall(int token) {
8111        enforceSystemOrRoot("Only the system is allowed to finish installs");
8112
8113        if (DEBUG_INSTALL) {
8114            Slog.v(TAG, "BM finishing package install for " + token);
8115        }
8116
8117        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8118        mHandler.sendMessage(msg);
8119    }
8120
8121    /**
8122     * Get the verification agent timeout.
8123     *
8124     * @return verification timeout in milliseconds
8125     */
8126    private long getVerificationTimeout() {
8127        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8128                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8129                DEFAULT_VERIFICATION_TIMEOUT);
8130    }
8131
8132    /**
8133     * Get the default verification agent response code.
8134     *
8135     * @return default verification response code
8136     */
8137    private int getDefaultVerificationResponse() {
8138        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8139                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8140                DEFAULT_VERIFICATION_RESPONSE);
8141    }
8142
8143    /**
8144     * Check whether or not package verification has been enabled.
8145     *
8146     * @return true if verification should be performed
8147     */
8148    private boolean isVerificationEnabled(int userId, int installFlags) {
8149        if (!DEFAULT_VERIFY_ENABLE) {
8150            return false;
8151        }
8152
8153        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8154
8155        // Check if installing from ADB
8156        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8157            // Do not run verification in a test harness environment
8158            if (ActivityManager.isRunningInTestHarness()) {
8159                return false;
8160            }
8161            if (ensureVerifyAppsEnabled) {
8162                return true;
8163            }
8164            // Check if the developer does not want package verification for ADB installs
8165            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8166                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8167                return false;
8168            }
8169        }
8170
8171        if (ensureVerifyAppsEnabled) {
8172            return true;
8173        }
8174
8175        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8176                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8177    }
8178
8179    /**
8180     * Get the "allow unknown sources" setting.
8181     *
8182     * @return the current "allow unknown sources" setting
8183     */
8184    private int getUnknownSourcesSettings() {
8185        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8186                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8187                -1);
8188    }
8189
8190    @Override
8191    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8192        final int uid = Binder.getCallingUid();
8193        // writer
8194        synchronized (mPackages) {
8195            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8196            if (targetPackageSetting == null) {
8197                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8198            }
8199
8200            PackageSetting installerPackageSetting;
8201            if (installerPackageName != null) {
8202                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8203                if (installerPackageSetting == null) {
8204                    throw new IllegalArgumentException("Unknown installer package: "
8205                            + installerPackageName);
8206                }
8207            } else {
8208                installerPackageSetting = null;
8209            }
8210
8211            Signature[] callerSignature;
8212            Object obj = mSettings.getUserIdLPr(uid);
8213            if (obj != null) {
8214                if (obj instanceof SharedUserSetting) {
8215                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8216                } else if (obj instanceof PackageSetting) {
8217                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8218                } else {
8219                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8220                }
8221            } else {
8222                throw new SecurityException("Unknown calling uid " + uid);
8223            }
8224
8225            // Verify: can't set installerPackageName to a package that is
8226            // not signed with the same cert as the caller.
8227            if (installerPackageSetting != null) {
8228                if (compareSignatures(callerSignature,
8229                        installerPackageSetting.signatures.mSignatures)
8230                        != PackageManager.SIGNATURE_MATCH) {
8231                    throw new SecurityException(
8232                            "Caller does not have same cert as new installer package "
8233                            + installerPackageName);
8234                }
8235            }
8236
8237            // Verify: if target already has an installer package, it must
8238            // be signed with the same cert as the caller.
8239            if (targetPackageSetting.installerPackageName != null) {
8240                PackageSetting setting = mSettings.mPackages.get(
8241                        targetPackageSetting.installerPackageName);
8242                // If the currently set package isn't valid, then it's always
8243                // okay to change it.
8244                if (setting != null) {
8245                    if (compareSignatures(callerSignature,
8246                            setting.signatures.mSignatures)
8247                            != PackageManager.SIGNATURE_MATCH) {
8248                        throw new SecurityException(
8249                                "Caller does not have same cert as old installer package "
8250                                + targetPackageSetting.installerPackageName);
8251                    }
8252                }
8253            }
8254
8255            // Okay!
8256            targetPackageSetting.installerPackageName = installerPackageName;
8257            scheduleWriteSettingsLocked();
8258        }
8259    }
8260
8261    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8262        // Queue up an async operation since the package installation may take a little while.
8263        mHandler.post(new Runnable() {
8264            public void run() {
8265                mHandler.removeCallbacks(this);
8266                 // Result object to be returned
8267                PackageInstalledInfo res = new PackageInstalledInfo();
8268                res.returnCode = currentStatus;
8269                res.uid = -1;
8270                res.pkg = null;
8271                res.removedInfo = new PackageRemovedInfo();
8272                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8273                    args.doPreInstall(res.returnCode);
8274                    synchronized (mInstallLock) {
8275                        installPackageLI(args, res);
8276                    }
8277                    args.doPostInstall(res.returnCode, res.uid);
8278                }
8279
8280                // A restore should be performed at this point if (a) the install
8281                // succeeded, (b) the operation is not an update, and (c) the new
8282                // package has not opted out of backup participation.
8283                final boolean update = res.removedInfo.removedPackage != null;
8284                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8285                boolean doRestore = !update
8286                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8287
8288                // Set up the post-install work request bookkeeping.  This will be used
8289                // and cleaned up by the post-install event handling regardless of whether
8290                // there's a restore pass performed.  Token values are >= 1.
8291                int token;
8292                if (mNextInstallToken < 0) mNextInstallToken = 1;
8293                token = mNextInstallToken++;
8294
8295                PostInstallData data = new PostInstallData(args, res);
8296                mRunningInstalls.put(token, data);
8297                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8298
8299                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8300                    // Pass responsibility to the Backup Manager.  It will perform a
8301                    // restore if appropriate, then pass responsibility back to the
8302                    // Package Manager to run the post-install observer callbacks
8303                    // and broadcasts.
8304                    IBackupManager bm = IBackupManager.Stub.asInterface(
8305                            ServiceManager.getService(Context.BACKUP_SERVICE));
8306                    if (bm != null) {
8307                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8308                                + " to BM for possible restore");
8309                        try {
8310                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8311                        } catch (RemoteException e) {
8312                            // can't happen; the backup manager is local
8313                        } catch (Exception e) {
8314                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8315                            doRestore = false;
8316                        }
8317                    } else {
8318                        Slog.e(TAG, "Backup Manager not found!");
8319                        doRestore = false;
8320                    }
8321                }
8322
8323                if (!doRestore) {
8324                    // No restore possible, or the Backup Manager was mysteriously not
8325                    // available -- just fire the post-install work request directly.
8326                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8327                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8328                    mHandler.sendMessage(msg);
8329                }
8330            }
8331        });
8332    }
8333
8334    private abstract class HandlerParams {
8335        private static final int MAX_RETRIES = 4;
8336
8337        /**
8338         * Number of times startCopy() has been attempted and had a non-fatal
8339         * error.
8340         */
8341        private int mRetries = 0;
8342
8343        /** User handle for the user requesting the information or installation. */
8344        private final UserHandle mUser;
8345
8346        HandlerParams(UserHandle user) {
8347            mUser = user;
8348        }
8349
8350        UserHandle getUser() {
8351            return mUser;
8352        }
8353
8354        final boolean startCopy() {
8355            boolean res;
8356            try {
8357                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8358
8359                if (++mRetries > MAX_RETRIES) {
8360                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8361                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8362                    handleServiceError();
8363                    return false;
8364                } else {
8365                    handleStartCopy();
8366                    res = true;
8367                }
8368            } catch (RemoteException e) {
8369                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8370                mHandler.sendEmptyMessage(MCS_RECONNECT);
8371                res = false;
8372            }
8373            handleReturnCode();
8374            return res;
8375        }
8376
8377        final void serviceError() {
8378            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8379            handleServiceError();
8380            handleReturnCode();
8381        }
8382
8383        abstract void handleStartCopy() throws RemoteException;
8384        abstract void handleServiceError();
8385        abstract void handleReturnCode();
8386    }
8387
8388    class MeasureParams extends HandlerParams {
8389        private final PackageStats mStats;
8390        private boolean mSuccess;
8391
8392        private final IPackageStatsObserver mObserver;
8393
8394        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8395            super(new UserHandle(stats.userHandle));
8396            mObserver = observer;
8397            mStats = stats;
8398        }
8399
8400        @Override
8401        public String toString() {
8402            return "MeasureParams{"
8403                + Integer.toHexString(System.identityHashCode(this))
8404                + " " + mStats.packageName + "}";
8405        }
8406
8407        @Override
8408        void handleStartCopy() throws RemoteException {
8409            synchronized (mInstallLock) {
8410                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8411            }
8412
8413            if (mSuccess) {
8414                final boolean mounted;
8415                if (Environment.isExternalStorageEmulated()) {
8416                    mounted = true;
8417                } else {
8418                    final String status = Environment.getExternalStorageState();
8419                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8420                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8421                }
8422
8423                if (mounted) {
8424                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8425
8426                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8427                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8428
8429                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8430                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8431
8432                    // Always subtract cache size, since it's a subdirectory
8433                    mStats.externalDataSize -= mStats.externalCacheSize;
8434
8435                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8436                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8437
8438                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8439                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8440                }
8441            }
8442        }
8443
8444        @Override
8445        void handleReturnCode() {
8446            if (mObserver != null) {
8447                try {
8448                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8449                } catch (RemoteException e) {
8450                    Slog.i(TAG, "Observer no longer exists.");
8451                }
8452            }
8453        }
8454
8455        @Override
8456        void handleServiceError() {
8457            Slog.e(TAG, "Could not measure application " + mStats.packageName
8458                            + " external storage");
8459        }
8460    }
8461
8462    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8463            throws RemoteException {
8464        long result = 0;
8465        for (File path : paths) {
8466            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8467        }
8468        return result;
8469    }
8470
8471    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8472        for (File path : paths) {
8473            try {
8474                mcs.clearDirectory(path.getAbsolutePath());
8475            } catch (RemoteException e) {
8476            }
8477        }
8478    }
8479
8480    static class OriginInfo {
8481        /**
8482         * Location where install is coming from, before it has been
8483         * copied/renamed into place. This could be a single monolithic APK
8484         * file, or a cluster directory. This location may be untrusted.
8485         */
8486        final File file;
8487        final String cid;
8488
8489        /**
8490         * Flag indicating that {@link #file} or {@link #cid} has already been
8491         * staged, meaning downstream users don't need to defensively copy the
8492         * contents.
8493         */
8494        final boolean staged;
8495
8496        /**
8497         * Flag indicating that {@link #file} or {@link #cid} is an already
8498         * installed app that is being moved.
8499         */
8500        final boolean existing;
8501
8502        final String resolvedPath;
8503        final File resolvedFile;
8504
8505        static OriginInfo fromNothing() {
8506            return new OriginInfo(null, null, false, false);
8507        }
8508
8509        static OriginInfo fromUntrustedFile(File file) {
8510            return new OriginInfo(file, null, false, false);
8511        }
8512
8513        static OriginInfo fromExistingFile(File file) {
8514            return new OriginInfo(file, null, false, true);
8515        }
8516
8517        static OriginInfo fromStagedFile(File file) {
8518            return new OriginInfo(file, null, true, false);
8519        }
8520
8521        static OriginInfo fromStagedContainer(String cid) {
8522            return new OriginInfo(null, cid, true, false);
8523        }
8524
8525        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8526            this.file = file;
8527            this.cid = cid;
8528            this.staged = staged;
8529            this.existing = existing;
8530
8531            if (cid != null) {
8532                resolvedPath = PackageHelper.getSdDir(cid);
8533                resolvedFile = new File(resolvedPath);
8534            } else if (file != null) {
8535                resolvedPath = file.getAbsolutePath();
8536                resolvedFile = file;
8537            } else {
8538                resolvedPath = null;
8539                resolvedFile = null;
8540            }
8541        }
8542    }
8543
8544    class InstallParams extends HandlerParams {
8545        final OriginInfo origin;
8546        final IPackageInstallObserver2 observer;
8547        int installFlags;
8548        final String installerPackageName;
8549        final VerificationParams verificationParams;
8550        private InstallArgs mArgs;
8551        private int mRet;
8552        final String packageAbiOverride;
8553
8554        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8555                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8556                String packageAbiOverride) {
8557            super(user);
8558            this.origin = origin;
8559            this.observer = observer;
8560            this.installFlags = installFlags;
8561            this.installerPackageName = installerPackageName;
8562            this.verificationParams = verificationParams;
8563            this.packageAbiOverride = packageAbiOverride;
8564        }
8565
8566        @Override
8567        public String toString() {
8568            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8569                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8570        }
8571
8572        public ManifestDigest getManifestDigest() {
8573            if (verificationParams == null) {
8574                return null;
8575            }
8576            return verificationParams.getManifestDigest();
8577        }
8578
8579        private int installLocationPolicy(PackageInfoLite pkgLite) {
8580            String packageName = pkgLite.packageName;
8581            int installLocation = pkgLite.installLocation;
8582            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8583            // reader
8584            synchronized (mPackages) {
8585                PackageParser.Package pkg = mPackages.get(packageName);
8586                if (pkg != null) {
8587                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8588                        // Check for downgrading.
8589                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8590                            if (pkgLite.versionCode < pkg.mVersionCode) {
8591                                Slog.w(TAG, "Can't install update of " + packageName
8592                                        + " update version " + pkgLite.versionCode
8593                                        + " is older than installed version "
8594                                        + pkg.mVersionCode);
8595                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8596                            }
8597                        }
8598                        // Check for updated system application.
8599                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8600                            if (onSd) {
8601                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8602                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8603                            }
8604                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8605                        } else {
8606                            if (onSd) {
8607                                // Install flag overrides everything.
8608                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8609                            }
8610                            // If current upgrade specifies particular preference
8611                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8612                                // Application explicitly specified internal.
8613                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8614                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8615                                // App explictly prefers external. Let policy decide
8616                            } else {
8617                                // Prefer previous location
8618                                if (isExternal(pkg)) {
8619                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8620                                }
8621                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8622                            }
8623                        }
8624                    } else {
8625                        // Invalid install. Return error code
8626                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8627                    }
8628                }
8629            }
8630            // All the special cases have been taken care of.
8631            // Return result based on recommended install location.
8632            if (onSd) {
8633                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8634            }
8635            return pkgLite.recommendedInstallLocation;
8636        }
8637
8638        /*
8639         * Invoke remote method to get package information and install
8640         * location values. Override install location based on default
8641         * policy if needed and then create install arguments based
8642         * on the install location.
8643         */
8644        public void handleStartCopy() throws RemoteException {
8645            int ret = PackageManager.INSTALL_SUCCEEDED;
8646
8647            // If we're already staged, we've firmly committed to an install location
8648            if (origin.staged) {
8649                if (origin.file != null) {
8650                    installFlags |= PackageManager.INSTALL_INTERNAL;
8651                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8652                } else if (origin.cid != null) {
8653                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8654                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8655                } else {
8656                    throw new IllegalStateException("Invalid stage location");
8657                }
8658            }
8659
8660            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8661            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8662
8663            PackageInfoLite pkgLite = null;
8664
8665            if (onInt && onSd) {
8666                // Check if both bits are set.
8667                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8668                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8669            } else {
8670                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8671                        packageAbiOverride);
8672
8673                /*
8674                 * If we have too little free space, try to free cache
8675                 * before giving up.
8676                 */
8677                if (!origin.staged && pkgLite.recommendedInstallLocation
8678                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8679                    // TODO: focus freeing disk space on the target device
8680                    final StorageManager storage = StorageManager.from(mContext);
8681                    final long lowThreshold = storage.getStorageLowBytes(
8682                            Environment.getDataDirectory());
8683
8684                    final long sizeBytes = mContainerService.calculateInstalledSize(
8685                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8686
8687                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8688                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8689                                installFlags, packageAbiOverride);
8690                    }
8691
8692                    /*
8693                     * The cache free must have deleted the file we
8694                     * downloaded to install.
8695                     *
8696                     * TODO: fix the "freeCache" call to not delete
8697                     *       the file we care about.
8698                     */
8699                    if (pkgLite.recommendedInstallLocation
8700                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8701                        pkgLite.recommendedInstallLocation
8702                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8703                    }
8704                }
8705            }
8706
8707            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8708                int loc = pkgLite.recommendedInstallLocation;
8709                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8710                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8711                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8712                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8713                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8714                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8715                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8716                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8717                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8718                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8719                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8720                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8721                } else {
8722                    // Override with defaults if needed.
8723                    loc = installLocationPolicy(pkgLite);
8724                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8725                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8726                    } else if (!onSd && !onInt) {
8727                        // Override install location with flags
8728                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8729                            // Set the flag to install on external media.
8730                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8731                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8732                        } else {
8733                            // Make sure the flag for installing on external
8734                            // media is unset
8735                            installFlags |= PackageManager.INSTALL_INTERNAL;
8736                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8737                        }
8738                    }
8739                }
8740            }
8741
8742            final InstallArgs args = createInstallArgs(this);
8743            mArgs = args;
8744
8745            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8746                 /*
8747                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8748                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8749                 */
8750                int userIdentifier = getUser().getIdentifier();
8751                if (userIdentifier == UserHandle.USER_ALL
8752                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8753                    userIdentifier = UserHandle.USER_OWNER;
8754                }
8755
8756                /*
8757                 * Determine if we have any installed package verifiers. If we
8758                 * do, then we'll defer to them to verify the packages.
8759                 */
8760                final int requiredUid = mRequiredVerifierPackage == null ? -1
8761                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8762                if (!origin.existing && requiredUid != -1
8763                        && isVerificationEnabled(userIdentifier, installFlags)) {
8764                    final Intent verification = new Intent(
8765                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8766                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8767                            PACKAGE_MIME_TYPE);
8768                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8769
8770                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8771                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8772                            0 /* TODO: Which userId? */);
8773
8774                    if (DEBUG_VERIFY) {
8775                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8776                                + verification.toString() + " with " + pkgLite.verifiers.length
8777                                + " optional verifiers");
8778                    }
8779
8780                    final int verificationId = mPendingVerificationToken++;
8781
8782                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8783
8784                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8785                            installerPackageName);
8786
8787                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8788                            installFlags);
8789
8790                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8791                            pkgLite.packageName);
8792
8793                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8794                            pkgLite.versionCode);
8795
8796                    if (verificationParams != null) {
8797                        if (verificationParams.getVerificationURI() != null) {
8798                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8799                                 verificationParams.getVerificationURI());
8800                        }
8801                        if (verificationParams.getOriginatingURI() != null) {
8802                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8803                                  verificationParams.getOriginatingURI());
8804                        }
8805                        if (verificationParams.getReferrer() != null) {
8806                            verification.putExtra(Intent.EXTRA_REFERRER,
8807                                  verificationParams.getReferrer());
8808                        }
8809                        if (verificationParams.getOriginatingUid() >= 0) {
8810                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8811                                  verificationParams.getOriginatingUid());
8812                        }
8813                        if (verificationParams.getInstallerUid() >= 0) {
8814                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8815                                  verificationParams.getInstallerUid());
8816                        }
8817                    }
8818
8819                    final PackageVerificationState verificationState = new PackageVerificationState(
8820                            requiredUid, args);
8821
8822                    mPendingVerification.append(verificationId, verificationState);
8823
8824                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8825                            receivers, verificationState);
8826
8827                    /*
8828                     * If any sufficient verifiers were listed in the package
8829                     * manifest, attempt to ask them.
8830                     */
8831                    if (sufficientVerifiers != null) {
8832                        final int N = sufficientVerifiers.size();
8833                        if (N == 0) {
8834                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8835                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8836                        } else {
8837                            for (int i = 0; i < N; i++) {
8838                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8839
8840                                final Intent sufficientIntent = new Intent(verification);
8841                                sufficientIntent.setComponent(verifierComponent);
8842
8843                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8844                            }
8845                        }
8846                    }
8847
8848                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8849                            mRequiredVerifierPackage, receivers);
8850                    if (ret == PackageManager.INSTALL_SUCCEEDED
8851                            && mRequiredVerifierPackage != null) {
8852                        /*
8853                         * Send the intent to the required verification agent,
8854                         * but only start the verification timeout after the
8855                         * target BroadcastReceivers have run.
8856                         */
8857                        verification.setComponent(requiredVerifierComponent);
8858                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8859                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8860                                new BroadcastReceiver() {
8861                                    @Override
8862                                    public void onReceive(Context context, Intent intent) {
8863                                        final Message msg = mHandler
8864                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8865                                        msg.arg1 = verificationId;
8866                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8867                                    }
8868                                }, null, 0, null, null);
8869
8870                        /*
8871                         * We don't want the copy to proceed until verification
8872                         * succeeds, so null out this field.
8873                         */
8874                        mArgs = null;
8875                    }
8876                } else {
8877                    /*
8878                     * No package verification is enabled, so immediately start
8879                     * the remote call to initiate copy using temporary file.
8880                     */
8881                    ret = args.copyApk(mContainerService, true);
8882                }
8883            }
8884
8885            mRet = ret;
8886        }
8887
8888        @Override
8889        void handleReturnCode() {
8890            // If mArgs is null, then MCS couldn't be reached. When it
8891            // reconnects, it will try again to install. At that point, this
8892            // will succeed.
8893            if (mArgs != null) {
8894                processPendingInstall(mArgs, mRet);
8895            }
8896        }
8897
8898        @Override
8899        void handleServiceError() {
8900            mArgs = createInstallArgs(this);
8901            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8902        }
8903
8904        public boolean isForwardLocked() {
8905            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8906        }
8907    }
8908
8909    /**
8910     * Used during creation of InstallArgs
8911     *
8912     * @param installFlags package installation flags
8913     * @return true if should be installed on external storage
8914     */
8915    private static boolean installOnSd(int installFlags) {
8916        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
8917            return false;
8918        }
8919        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
8920            return true;
8921        }
8922        return false;
8923    }
8924
8925    /**
8926     * Used during creation of InstallArgs
8927     *
8928     * @param installFlags package installation flags
8929     * @return true if should be installed as forward locked
8930     */
8931    private static boolean installForwardLocked(int installFlags) {
8932        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8933    }
8934
8935    private InstallArgs createInstallArgs(InstallParams params) {
8936        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
8937            return new AsecInstallArgs(params);
8938        } else {
8939            return new FileInstallArgs(params);
8940        }
8941    }
8942
8943    /**
8944     * Create args that describe an existing installed package. Typically used
8945     * when cleaning up old installs, or used as a move source.
8946     */
8947    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
8948            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
8949        final boolean isInAsec;
8950        if (installOnSd(installFlags)) {
8951            /* Apps on SD card are always in ASEC containers. */
8952            isInAsec = true;
8953        } else if (installForwardLocked(installFlags)
8954                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8955            /*
8956             * Forward-locked apps are only in ASEC containers if they're the
8957             * new style
8958             */
8959            isInAsec = true;
8960        } else {
8961            isInAsec = false;
8962        }
8963
8964        if (isInAsec) {
8965            return new AsecInstallArgs(codePath, instructionSets,
8966                    installOnSd(installFlags), installForwardLocked(installFlags));
8967        } else {
8968            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
8969                    instructionSets);
8970        }
8971    }
8972
8973    static abstract class InstallArgs {
8974        /** @see InstallParams#origin */
8975        final OriginInfo origin;
8976
8977        final IPackageInstallObserver2 observer;
8978        // Always refers to PackageManager flags only
8979        final int installFlags;
8980        final String installerPackageName;
8981        final ManifestDigest manifestDigest;
8982        final UserHandle user;
8983        final String abiOverride;
8984
8985        // The list of instruction sets supported by this app. This is currently
8986        // only used during the rmdex() phase to clean up resources. We can get rid of this
8987        // if we move dex files under the common app path.
8988        /* nullable */ String[] instructionSets;
8989
8990        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8991                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
8992                String[] instructionSets, String abiOverride) {
8993            this.origin = origin;
8994            this.installFlags = installFlags;
8995            this.observer = observer;
8996            this.installerPackageName = installerPackageName;
8997            this.manifestDigest = manifestDigest;
8998            this.user = user;
8999            this.instructionSets = instructionSets;
9000            this.abiOverride = abiOverride;
9001        }
9002
9003        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9004        abstract int doPreInstall(int status);
9005
9006        /**
9007         * Rename package into final resting place. All paths on the given
9008         * scanned package should be updated to reflect the rename.
9009         */
9010        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9011        abstract int doPostInstall(int status, int uid);
9012
9013        /** @see PackageSettingBase#codePathString */
9014        abstract String getCodePath();
9015        /** @see PackageSettingBase#resourcePathString */
9016        abstract String getResourcePath();
9017        abstract String getLegacyNativeLibraryPath();
9018
9019        // Need installer lock especially for dex file removal.
9020        abstract void cleanUpResourcesLI();
9021        abstract boolean doPostDeleteLI(boolean delete);
9022        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9023
9024        /**
9025         * Called before the source arguments are copied. This is used mostly
9026         * for MoveParams when it needs to read the source file to put it in the
9027         * destination.
9028         */
9029        int doPreCopy() {
9030            return PackageManager.INSTALL_SUCCEEDED;
9031        }
9032
9033        /**
9034         * Called after the source arguments are copied. This is used mostly for
9035         * MoveParams when it needs to read the source file to put it in the
9036         * destination.
9037         *
9038         * @return
9039         */
9040        int doPostCopy(int uid) {
9041            return PackageManager.INSTALL_SUCCEEDED;
9042        }
9043
9044        protected boolean isFwdLocked() {
9045            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9046        }
9047
9048        protected boolean isExternal() {
9049            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9050        }
9051
9052        UserHandle getUser() {
9053            return user;
9054        }
9055    }
9056
9057    /**
9058     * Logic to handle installation of non-ASEC applications, including copying
9059     * and renaming logic.
9060     */
9061    class FileInstallArgs extends InstallArgs {
9062        private File codeFile;
9063        private File resourceFile;
9064        private File legacyNativeLibraryPath;
9065
9066        // Example topology:
9067        // /data/app/com.example/base.apk
9068        // /data/app/com.example/split_foo.apk
9069        // /data/app/com.example/lib/arm/libfoo.so
9070        // /data/app/com.example/lib/arm64/libfoo.so
9071        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9072
9073        /** New install */
9074        FileInstallArgs(InstallParams params) {
9075            super(params.origin, params.observer, params.installFlags,
9076                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9077                    null /* instruction sets */, params.packageAbiOverride);
9078            if (isFwdLocked()) {
9079                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9080            }
9081        }
9082
9083        /** Existing install */
9084        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9085                String[] instructionSets) {
9086            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9087            this.codeFile = (codePath != null) ? new File(codePath) : null;
9088            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9089            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9090                    new File(legacyNativeLibraryPath) : null;
9091        }
9092
9093        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9094            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9095                    isFwdLocked(), abiOverride);
9096
9097            final StorageManager storage = StorageManager.from(mContext);
9098            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9099        }
9100
9101        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9102            if (origin.staged) {
9103                Slog.d(TAG, origin.file + " already staged; skipping copy");
9104                codeFile = origin.file;
9105                resourceFile = origin.file;
9106                return PackageManager.INSTALL_SUCCEEDED;
9107            }
9108
9109            try {
9110                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9111                codeFile = tempDir;
9112                resourceFile = tempDir;
9113            } catch (IOException e) {
9114                Slog.w(TAG, "Failed to create copy file: " + e);
9115                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9116            }
9117
9118            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9119                @Override
9120                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9121                    if (!FileUtils.isValidExtFilename(name)) {
9122                        throw new IllegalArgumentException("Invalid filename: " + name);
9123                    }
9124                    try {
9125                        final File file = new File(codeFile, name);
9126                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9127                                O_RDWR | O_CREAT, 0644);
9128                        Os.chmod(file.getAbsolutePath(), 0644);
9129                        return new ParcelFileDescriptor(fd);
9130                    } catch (ErrnoException e) {
9131                        throw new RemoteException("Failed to open: " + e.getMessage());
9132                    }
9133                }
9134            };
9135
9136            int ret = PackageManager.INSTALL_SUCCEEDED;
9137            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9138            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9139                Slog.e(TAG, "Failed to copy package");
9140                return ret;
9141            }
9142
9143            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9144            NativeLibraryHelper.Handle handle = null;
9145            try {
9146                handle = NativeLibraryHelper.Handle.create(codeFile);
9147                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9148                        abiOverride);
9149            } catch (IOException e) {
9150                Slog.e(TAG, "Copying native libraries failed", e);
9151                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9152            } finally {
9153                IoUtils.closeQuietly(handle);
9154            }
9155
9156            return ret;
9157        }
9158
9159        int doPreInstall(int status) {
9160            if (status != PackageManager.INSTALL_SUCCEEDED) {
9161                cleanUp();
9162            }
9163            return status;
9164        }
9165
9166        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9167            if (status != PackageManager.INSTALL_SUCCEEDED) {
9168                cleanUp();
9169                return false;
9170            } else {
9171                final File beforeCodeFile = codeFile;
9172                final File afterCodeFile = getNextCodePath(pkg.packageName);
9173
9174                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9175                try {
9176                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9177                } catch (ErrnoException e) {
9178                    Slog.d(TAG, "Failed to rename", e);
9179                    return false;
9180                }
9181
9182                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9183                    Slog.d(TAG, "Failed to restorecon");
9184                    return false;
9185                }
9186
9187                // Reflect the rename internally
9188                codeFile = afterCodeFile;
9189                resourceFile = afterCodeFile;
9190
9191                // Reflect the rename in scanned details
9192                pkg.codePath = afterCodeFile.getAbsolutePath();
9193                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9194                        pkg.baseCodePath);
9195                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9196                        pkg.splitCodePaths);
9197
9198                // Reflect the rename in app info
9199                pkg.applicationInfo.setCodePath(pkg.codePath);
9200                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9201                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9202                pkg.applicationInfo.setResourcePath(pkg.codePath);
9203                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9204                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9205
9206                return true;
9207            }
9208        }
9209
9210        int doPostInstall(int status, int uid) {
9211            if (status != PackageManager.INSTALL_SUCCEEDED) {
9212                cleanUp();
9213            }
9214            return status;
9215        }
9216
9217        @Override
9218        String getCodePath() {
9219            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9220        }
9221
9222        @Override
9223        String getResourcePath() {
9224            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9225        }
9226
9227        @Override
9228        String getLegacyNativeLibraryPath() {
9229            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9230        }
9231
9232        private boolean cleanUp() {
9233            if (codeFile == null || !codeFile.exists()) {
9234                return false;
9235            }
9236
9237            if (codeFile.isDirectory()) {
9238                FileUtils.deleteContents(codeFile);
9239            }
9240            codeFile.delete();
9241
9242            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9243                resourceFile.delete();
9244            }
9245
9246            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9247                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9248                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9249                }
9250                legacyNativeLibraryPath.delete();
9251            }
9252
9253            return true;
9254        }
9255
9256        void cleanUpResourcesLI() {
9257            // Try enumerating all code paths before deleting
9258            List<String> allCodePaths = Collections.EMPTY_LIST;
9259            if (codeFile != null && codeFile.exists()) {
9260                try {
9261                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9262                    allCodePaths = pkg.getAllCodePaths();
9263                } catch (PackageParserException e) {
9264                    // Ignored; we tried our best
9265                }
9266            }
9267
9268            cleanUp();
9269
9270            if (!allCodePaths.isEmpty()) {
9271                if (instructionSets == null) {
9272                    throw new IllegalStateException("instructionSet == null");
9273                }
9274                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9275                for (String codePath : allCodePaths) {
9276                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9277                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9278                        if (retCode < 0) {
9279                            Slog.w(TAG, "Couldn't remove dex file for package: "
9280                                    + " at location " + codePath + ", retcode=" + retCode);
9281                            // we don't consider this to be a failure of the core package deletion
9282                        }
9283                    }
9284                }
9285            }
9286        }
9287
9288        boolean doPostDeleteLI(boolean delete) {
9289            // XXX err, shouldn't we respect the delete flag?
9290            cleanUpResourcesLI();
9291            return true;
9292        }
9293    }
9294
9295    private boolean isAsecExternal(String cid) {
9296        final String asecPath = PackageHelper.getSdFilesystem(cid);
9297        return !asecPath.startsWith(mAsecInternalPath);
9298    }
9299
9300    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9301            PackageManagerException {
9302        if (copyRet < 0) {
9303            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9304                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9305                throw new PackageManagerException(copyRet, message);
9306            }
9307        }
9308    }
9309
9310    /**
9311     * Extract the MountService "container ID" from the full code path of an
9312     * .apk.
9313     */
9314    static String cidFromCodePath(String fullCodePath) {
9315        int eidx = fullCodePath.lastIndexOf("/");
9316        String subStr1 = fullCodePath.substring(0, eidx);
9317        int sidx = subStr1.lastIndexOf("/");
9318        return subStr1.substring(sidx+1, eidx);
9319    }
9320
9321    /**
9322     * Logic to handle installation of ASEC applications, including copying and
9323     * renaming logic.
9324     */
9325    class AsecInstallArgs extends InstallArgs {
9326        static final String RES_FILE_NAME = "pkg.apk";
9327        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9328
9329        String cid;
9330        String packagePath;
9331        String resourcePath;
9332        String legacyNativeLibraryDir;
9333
9334        /** New install */
9335        AsecInstallArgs(InstallParams params) {
9336            super(params.origin, params.observer, params.installFlags,
9337                    params.installerPackageName, params.getManifestDigest(),
9338                    params.getUser(), null /* instruction sets */,
9339                    params.packageAbiOverride);
9340        }
9341
9342        /** Existing install */
9343        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9344                        boolean isExternal, boolean isForwardLocked) {
9345            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9346                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9347                    instructionSets, null);
9348            // Hackily pretend we're still looking at a full code path
9349            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9350                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9351            }
9352
9353            // Extract cid from fullCodePath
9354            int eidx = fullCodePath.lastIndexOf("/");
9355            String subStr1 = fullCodePath.substring(0, eidx);
9356            int sidx = subStr1.lastIndexOf("/");
9357            cid = subStr1.substring(sidx+1, eidx);
9358            setMountPath(subStr1);
9359        }
9360
9361        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9362            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9363                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9364                    instructionSets, null);
9365            this.cid = cid;
9366            setMountPath(PackageHelper.getSdDir(cid));
9367        }
9368
9369        void createCopyFile() {
9370            cid = mInstallerService.allocateExternalStageCidLegacy();
9371        }
9372
9373        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9374            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9375                    abiOverride);
9376
9377            final File target;
9378            if (isExternal()) {
9379                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9380            } else {
9381                target = Environment.getDataDirectory();
9382            }
9383
9384            final StorageManager storage = StorageManager.from(mContext);
9385            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9386        }
9387
9388        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9389            if (origin.staged) {
9390                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9391                cid = origin.cid;
9392                setMountPath(PackageHelper.getSdDir(cid));
9393                return PackageManager.INSTALL_SUCCEEDED;
9394            }
9395
9396            if (temp) {
9397                createCopyFile();
9398            } else {
9399                /*
9400                 * Pre-emptively destroy the container since it's destroyed if
9401                 * copying fails due to it existing anyway.
9402                 */
9403                PackageHelper.destroySdDir(cid);
9404            }
9405
9406            final String newMountPath = imcs.copyPackageToContainer(
9407                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9408                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9409
9410            if (newMountPath != null) {
9411                setMountPath(newMountPath);
9412                return PackageManager.INSTALL_SUCCEEDED;
9413            } else {
9414                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9415            }
9416        }
9417
9418        @Override
9419        String getCodePath() {
9420            return packagePath;
9421        }
9422
9423        @Override
9424        String getResourcePath() {
9425            return resourcePath;
9426        }
9427
9428        @Override
9429        String getLegacyNativeLibraryPath() {
9430            return legacyNativeLibraryDir;
9431        }
9432
9433        int doPreInstall(int status) {
9434            if (status != PackageManager.INSTALL_SUCCEEDED) {
9435                // Destroy container
9436                PackageHelper.destroySdDir(cid);
9437            } else {
9438                boolean mounted = PackageHelper.isContainerMounted(cid);
9439                if (!mounted) {
9440                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9441                            Process.SYSTEM_UID);
9442                    if (newMountPath != null) {
9443                        setMountPath(newMountPath);
9444                    } else {
9445                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9446                    }
9447                }
9448            }
9449            return status;
9450        }
9451
9452        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9453            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9454            String newMountPath = null;
9455            if (PackageHelper.isContainerMounted(cid)) {
9456                // Unmount the container
9457                if (!PackageHelper.unMountSdDir(cid)) {
9458                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9459                    return false;
9460                }
9461            }
9462            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9463                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9464                        " which might be stale. Will try to clean up.");
9465                // Clean up the stale container and proceed to recreate.
9466                if (!PackageHelper.destroySdDir(newCacheId)) {
9467                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9468                    return false;
9469                }
9470                // Successfully cleaned up stale container. Try to rename again.
9471                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9472                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9473                            + " inspite of cleaning it up.");
9474                    return false;
9475                }
9476            }
9477            if (!PackageHelper.isContainerMounted(newCacheId)) {
9478                Slog.w(TAG, "Mounting container " + newCacheId);
9479                newMountPath = PackageHelper.mountSdDir(newCacheId,
9480                        getEncryptKey(), Process.SYSTEM_UID);
9481            } else {
9482                newMountPath = PackageHelper.getSdDir(newCacheId);
9483            }
9484            if (newMountPath == null) {
9485                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9486                return false;
9487            }
9488            Log.i(TAG, "Succesfully renamed " + cid +
9489                    " to " + newCacheId +
9490                    " at new path: " + newMountPath);
9491            cid = newCacheId;
9492
9493            final File beforeCodeFile = new File(packagePath);
9494            setMountPath(newMountPath);
9495            final File afterCodeFile = new File(packagePath);
9496
9497            // Reflect the rename in scanned details
9498            pkg.codePath = afterCodeFile.getAbsolutePath();
9499            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9500                    pkg.baseCodePath);
9501            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9502                    pkg.splitCodePaths);
9503
9504            // Reflect the rename in app info
9505            pkg.applicationInfo.setCodePath(pkg.codePath);
9506            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9507            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9508            pkg.applicationInfo.setResourcePath(pkg.codePath);
9509            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9510            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9511
9512            return true;
9513        }
9514
9515        private void setMountPath(String mountPath) {
9516            final File mountFile = new File(mountPath);
9517
9518            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9519            if (monolithicFile.exists()) {
9520                packagePath = monolithicFile.getAbsolutePath();
9521                if (isFwdLocked()) {
9522                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9523                } else {
9524                    resourcePath = packagePath;
9525                }
9526            } else {
9527                packagePath = mountFile.getAbsolutePath();
9528                resourcePath = packagePath;
9529            }
9530
9531            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9532        }
9533
9534        int doPostInstall(int status, int uid) {
9535            if (status != PackageManager.INSTALL_SUCCEEDED) {
9536                cleanUp();
9537            } else {
9538                final int groupOwner;
9539                final String protectedFile;
9540                if (isFwdLocked()) {
9541                    groupOwner = UserHandle.getSharedAppGid(uid);
9542                    protectedFile = RES_FILE_NAME;
9543                } else {
9544                    groupOwner = -1;
9545                    protectedFile = null;
9546                }
9547
9548                if (uid < Process.FIRST_APPLICATION_UID
9549                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9550                    Slog.e(TAG, "Failed to finalize " + cid);
9551                    PackageHelper.destroySdDir(cid);
9552                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9553                }
9554
9555                boolean mounted = PackageHelper.isContainerMounted(cid);
9556                if (!mounted) {
9557                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9558                }
9559            }
9560            return status;
9561        }
9562
9563        private void cleanUp() {
9564            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9565
9566            // Destroy secure container
9567            PackageHelper.destroySdDir(cid);
9568        }
9569
9570        private List<String> getAllCodePaths() {
9571            final File codeFile = new File(getCodePath());
9572            if (codeFile != null && codeFile.exists()) {
9573                try {
9574                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9575                    return pkg.getAllCodePaths();
9576                } catch (PackageParserException e) {
9577                    // Ignored; we tried our best
9578                }
9579            }
9580            return Collections.EMPTY_LIST;
9581        }
9582
9583        void cleanUpResourcesLI() {
9584            // Enumerate all code paths before deleting
9585            cleanUpResourcesLI(getAllCodePaths());
9586        }
9587
9588        private void cleanUpResourcesLI(List<String> allCodePaths) {
9589            cleanUp();
9590
9591            if (!allCodePaths.isEmpty()) {
9592                if (instructionSets == null) {
9593                    throw new IllegalStateException("instructionSet == null");
9594                }
9595                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9596                for (String codePath : allCodePaths) {
9597                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9598                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9599                        if (retCode < 0) {
9600                            Slog.w(TAG, "Couldn't remove dex file for package: "
9601                                    + " at location " + codePath + ", retcode=" + retCode);
9602                            // we don't consider this to be a failure of the core package deletion
9603                        }
9604                    }
9605                }
9606            }
9607        }
9608
9609        boolean matchContainer(String app) {
9610            if (cid.startsWith(app)) {
9611                return true;
9612            }
9613            return false;
9614        }
9615
9616        String getPackageName() {
9617            return getAsecPackageName(cid);
9618        }
9619
9620        boolean doPostDeleteLI(boolean delete) {
9621            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9622            final List<String> allCodePaths = getAllCodePaths();
9623            boolean mounted = PackageHelper.isContainerMounted(cid);
9624            if (mounted) {
9625                // Unmount first
9626                if (PackageHelper.unMountSdDir(cid)) {
9627                    mounted = false;
9628                }
9629            }
9630            if (!mounted && delete) {
9631                cleanUpResourcesLI(allCodePaths);
9632            }
9633            return !mounted;
9634        }
9635
9636        @Override
9637        int doPreCopy() {
9638            if (isFwdLocked()) {
9639                if (!PackageHelper.fixSdPermissions(cid,
9640                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9641                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9642                }
9643            }
9644
9645            return PackageManager.INSTALL_SUCCEEDED;
9646        }
9647
9648        @Override
9649        int doPostCopy(int uid) {
9650            if (isFwdLocked()) {
9651                if (uid < Process.FIRST_APPLICATION_UID
9652                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9653                                RES_FILE_NAME)) {
9654                    Slog.e(TAG, "Failed to finalize " + cid);
9655                    PackageHelper.destroySdDir(cid);
9656                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9657                }
9658            }
9659
9660            return PackageManager.INSTALL_SUCCEEDED;
9661        }
9662    }
9663
9664    static String getAsecPackageName(String packageCid) {
9665        int idx = packageCid.lastIndexOf("-");
9666        if (idx == -1) {
9667            return packageCid;
9668        }
9669        return packageCid.substring(0, idx);
9670    }
9671
9672    // Utility method used to create code paths based on package name and available index.
9673    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9674        String idxStr = "";
9675        int idx = 1;
9676        // Fall back to default value of idx=1 if prefix is not
9677        // part of oldCodePath
9678        if (oldCodePath != null) {
9679            String subStr = oldCodePath;
9680            // Drop the suffix right away
9681            if (suffix != null && subStr.endsWith(suffix)) {
9682                subStr = subStr.substring(0, subStr.length() - suffix.length());
9683            }
9684            // If oldCodePath already contains prefix find out the
9685            // ending index to either increment or decrement.
9686            int sidx = subStr.lastIndexOf(prefix);
9687            if (sidx != -1) {
9688                subStr = subStr.substring(sidx + prefix.length());
9689                if (subStr != null) {
9690                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9691                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9692                    }
9693                    try {
9694                        idx = Integer.parseInt(subStr);
9695                        if (idx <= 1) {
9696                            idx++;
9697                        } else {
9698                            idx--;
9699                        }
9700                    } catch(NumberFormatException e) {
9701                    }
9702                }
9703            }
9704        }
9705        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9706        return prefix + idxStr;
9707    }
9708
9709    private File getNextCodePath(String packageName) {
9710        int suffix = 1;
9711        File result;
9712        do {
9713            result = new File(mAppInstallDir, packageName + "-" + suffix);
9714            suffix++;
9715        } while (result.exists());
9716        return result;
9717    }
9718
9719    // Utility method used to ignore ADD/REMOVE events
9720    // by directory observer.
9721    private static boolean ignoreCodePath(String fullPathStr) {
9722        String apkName = deriveCodePathName(fullPathStr);
9723        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9724        if (idx != -1 && ((idx+1) < apkName.length())) {
9725            // Make sure the package ends with a numeral
9726            String version = apkName.substring(idx+1);
9727            try {
9728                Integer.parseInt(version);
9729                return true;
9730            } catch (NumberFormatException e) {}
9731        }
9732        return false;
9733    }
9734
9735    // Utility method that returns the relative package path with respect
9736    // to the installation directory. Like say for /data/data/com.test-1.apk
9737    // string com.test-1 is returned.
9738    static String deriveCodePathName(String codePath) {
9739        if (codePath == null) {
9740            return null;
9741        }
9742        final File codeFile = new File(codePath);
9743        final String name = codeFile.getName();
9744        if (codeFile.isDirectory()) {
9745            return name;
9746        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9747            final int lastDot = name.lastIndexOf('.');
9748            return name.substring(0, lastDot);
9749        } else {
9750            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9751            return null;
9752        }
9753    }
9754
9755    class PackageInstalledInfo {
9756        String name;
9757        int uid;
9758        // The set of users that originally had this package installed.
9759        int[] origUsers;
9760        // The set of users that now have this package installed.
9761        int[] newUsers;
9762        PackageParser.Package pkg;
9763        int returnCode;
9764        String returnMsg;
9765        PackageRemovedInfo removedInfo;
9766
9767        public void setError(int code, String msg) {
9768            returnCode = code;
9769            returnMsg = msg;
9770            Slog.w(TAG, msg);
9771        }
9772
9773        public void setError(String msg, PackageParserException e) {
9774            returnCode = e.error;
9775            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9776            Slog.w(TAG, msg, e);
9777        }
9778
9779        public void setError(String msg, PackageManagerException e) {
9780            returnCode = e.error;
9781            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9782            Slog.w(TAG, msg, e);
9783        }
9784
9785        // In some error cases we want to convey more info back to the observer
9786        String origPackage;
9787        String origPermission;
9788    }
9789
9790    /*
9791     * Install a non-existing package.
9792     */
9793    private void installNewPackageLI(PackageParser.Package pkg,
9794            int parseFlags, int scanFlags, UserHandle user,
9795            String installerPackageName, PackageInstalledInfo res) {
9796        // Remember this for later, in case we need to rollback this install
9797        String pkgName = pkg.packageName;
9798
9799        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9800        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9801        synchronized(mPackages) {
9802            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9803                // A package with the same name is already installed, though
9804                // it has been renamed to an older name.  The package we
9805                // are trying to install should be installed as an update to
9806                // the existing one, but that has not been requested, so bail.
9807                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9808                        + " without first uninstalling package running as "
9809                        + mSettings.mRenamedPackages.get(pkgName));
9810                return;
9811            }
9812            if (mPackages.containsKey(pkgName)) {
9813                // Don't allow installation over an existing package with the same name.
9814                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9815                        + " without first uninstalling.");
9816                return;
9817            }
9818        }
9819
9820        try {
9821            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9822                    System.currentTimeMillis(), user);
9823
9824            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9825            // delete the partially installed application. the data directory will have to be
9826            // restored if it was already existing
9827            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9828                // remove package from internal structures.  Note that we want deletePackageX to
9829                // delete the package data and cache directories that it created in
9830                // scanPackageLocked, unless those directories existed before we even tried to
9831                // install.
9832                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9833                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9834                                res.removedInfo, true);
9835            }
9836
9837        } catch (PackageManagerException e) {
9838            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9839        }
9840    }
9841
9842    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9843        // Upgrade keysets are being used.  Determine if new package has a superset of the
9844        // required keys.
9845        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9846        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9847        for (int i = 0; i < upgradeKeySets.length; i++) {
9848            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9849            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9850                return true;
9851            }
9852        }
9853        return false;
9854    }
9855
9856    private void replacePackageLI(PackageParser.Package pkg,
9857            int parseFlags, int scanFlags, UserHandle user,
9858            String installerPackageName, PackageInstalledInfo res) {
9859        PackageParser.Package oldPackage;
9860        String pkgName = pkg.packageName;
9861        int[] allUsers;
9862        boolean[] perUserInstalled;
9863
9864        // First find the old package info and check signatures
9865        synchronized(mPackages) {
9866            oldPackage = mPackages.get(pkgName);
9867            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9868            PackageSetting ps = mSettings.mPackages.get(pkgName);
9869            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9870                // default to original signature matching
9871                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9872                    != PackageManager.SIGNATURE_MATCH) {
9873                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9874                            "New package has a different signature: " + pkgName);
9875                    return;
9876                }
9877            } else {
9878                if(!checkUpgradeKeySetLP(ps, pkg)) {
9879                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9880                            "New package not signed by keys specified by upgrade-keysets: "
9881                            + pkgName);
9882                    return;
9883                }
9884            }
9885
9886            // In case of rollback, remember per-user/profile install state
9887            allUsers = sUserManager.getUserIds();
9888            perUserInstalled = new boolean[allUsers.length];
9889            for (int i = 0; i < allUsers.length; i++) {
9890                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9891            }
9892        }
9893
9894        boolean sysPkg = (isSystemApp(oldPackage));
9895        if (sysPkg) {
9896            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9897                    user, allUsers, perUserInstalled, installerPackageName, res);
9898        } else {
9899            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9900                    user, allUsers, perUserInstalled, installerPackageName, res);
9901        }
9902    }
9903
9904    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9905            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9906            int[] allUsers, boolean[] perUserInstalled,
9907            String installerPackageName, PackageInstalledInfo res) {
9908        String pkgName = deletedPackage.packageName;
9909        boolean deletedPkg = true;
9910        boolean updatedSettings = false;
9911
9912        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9913                + deletedPackage);
9914        long origUpdateTime;
9915        if (pkg.mExtras != null) {
9916            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9917        } else {
9918            origUpdateTime = 0;
9919        }
9920
9921        // First delete the existing package while retaining the data directory
9922        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9923                res.removedInfo, true)) {
9924            // If the existing package wasn't successfully deleted
9925            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
9926            deletedPkg = false;
9927        } else {
9928            // Successfully deleted the old package; proceed with replace.
9929
9930            // If deleted package lived in a container, give users a chance to
9931            // relinquish resources before killing.
9932            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
9933                if (DEBUG_INSTALL) {
9934                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
9935                }
9936                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
9937                final ArrayList<String> pkgList = new ArrayList<String>(1);
9938                pkgList.add(deletedPackage.applicationInfo.packageName);
9939                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
9940            }
9941
9942            deleteCodeCacheDirsLI(pkgName);
9943            try {
9944                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
9945                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
9946                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9947                updatedSettings = true;
9948            } catch (PackageManagerException e) {
9949                res.setError("Package couldn't be installed in " + pkg.codePath, e);
9950            }
9951        }
9952
9953        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9954            // remove package from internal structures.  Note that we want deletePackageX to
9955            // delete the package data and cache directories that it created in
9956            // scanPackageLocked, unless those directories existed before we even tried to
9957            // install.
9958            if(updatedSettings) {
9959                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9960                deletePackageLI(
9961                        pkgName, null, true, allUsers, perUserInstalled,
9962                        PackageManager.DELETE_KEEP_DATA,
9963                                res.removedInfo, true);
9964            }
9965            // Since we failed to install the new package we need to restore the old
9966            // package that we deleted.
9967            if (deletedPkg) {
9968                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9969                File restoreFile = new File(deletedPackage.codePath);
9970                // Parse old package
9971                boolean oldOnSd = isExternal(deletedPackage);
9972                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9973                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9974                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9975                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
9976                try {
9977                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
9978                } catch (PackageManagerException e) {
9979                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
9980                            + e.getMessage());
9981                    return;
9982                }
9983                // Restore of old package succeeded. Update permissions.
9984                // writer
9985                synchronized (mPackages) {
9986                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9987                            UPDATE_PERMISSIONS_ALL);
9988                    // can downgrade to reader
9989                    mSettings.writeLPr();
9990                }
9991                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9992            }
9993        }
9994    }
9995
9996    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9997            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9998            int[] allUsers, boolean[] perUserInstalled,
9999            String installerPackageName, PackageInstalledInfo res) {
10000        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10001                + ", old=" + deletedPackage);
10002        boolean updatedSettings = false;
10003        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10004        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10005            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10006        }
10007        String packageName = deletedPackage.packageName;
10008        if (packageName == null) {
10009            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10010                    "Attempt to delete null packageName.");
10011            return;
10012        }
10013        PackageParser.Package oldPkg;
10014        PackageSetting oldPkgSetting;
10015        // reader
10016        synchronized (mPackages) {
10017            oldPkg = mPackages.get(packageName);
10018            oldPkgSetting = mSettings.mPackages.get(packageName);
10019            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10020                    (oldPkgSetting == null)) {
10021                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10022                        "Couldn't find package:" + packageName + " information");
10023                return;
10024            }
10025        }
10026
10027        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10028
10029        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10030        res.removedInfo.removedPackage = packageName;
10031        // Remove existing system package
10032        removePackageLI(oldPkgSetting, true);
10033        // writer
10034        synchronized (mPackages) {
10035            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10036                // We didn't need to disable the .apk as a current system package,
10037                // which means we are replacing another update that is already
10038                // installed.  We need to make sure to delete the older one's .apk.
10039                res.removedInfo.args = createInstallArgsForExisting(0,
10040                        deletedPackage.applicationInfo.getCodePath(),
10041                        deletedPackage.applicationInfo.getResourcePath(),
10042                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10043                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10044            } else {
10045                res.removedInfo.args = null;
10046            }
10047        }
10048
10049        // Successfully disabled the old package. Now proceed with re-installation
10050        deleteCodeCacheDirsLI(packageName);
10051
10052        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10053        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10054
10055        PackageParser.Package newPackage = null;
10056        try {
10057            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10058            if (newPackage.mExtras != null) {
10059                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10060                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10061                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10062
10063                // is the update attempting to change shared user? that isn't going to work...
10064                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10065                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10066                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10067                            + " to " + newPkgSetting.sharedUser);
10068                    updatedSettings = true;
10069                }
10070            }
10071
10072            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10073                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10074                updatedSettings = true;
10075            }
10076
10077        } catch (PackageManagerException e) {
10078            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10079        }
10080
10081        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10082            // Re installation failed. Restore old information
10083            // Remove new pkg information
10084            if (newPackage != null) {
10085                removeInstalledPackageLI(newPackage, true);
10086            }
10087            // Add back the old system package
10088            try {
10089                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10090            } catch (PackageManagerException e) {
10091                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10092            }
10093            // Restore the old system information in Settings
10094            synchronized(mPackages) {
10095                if (updatedSettings) {
10096                    mSettings.enableSystemPackageLPw(packageName);
10097                    mSettings.setInstallerPackageName(packageName,
10098                            oldPkgSetting.installerPackageName);
10099                }
10100                mSettings.writeLPr();
10101            }
10102        }
10103    }
10104
10105    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10106            int[] allUsers, boolean[] perUserInstalled,
10107            PackageInstalledInfo res) {
10108        String pkgName = newPackage.packageName;
10109        synchronized (mPackages) {
10110            //write settings. the installStatus will be incomplete at this stage.
10111            //note that the new package setting would have already been
10112            //added to mPackages. It hasn't been persisted yet.
10113            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10114            mSettings.writeLPr();
10115        }
10116
10117        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10118
10119        synchronized (mPackages) {
10120            updatePermissionsLPw(newPackage.packageName, newPackage,
10121                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10122                            ? UPDATE_PERMISSIONS_ALL : 0));
10123            // For system-bundled packages, we assume that installing an upgraded version
10124            // of the package implies that the user actually wants to run that new code,
10125            // so we enable the package.
10126            if (isSystemApp(newPackage)) {
10127                // NB: implicit assumption that system package upgrades apply to all users
10128                if (DEBUG_INSTALL) {
10129                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10130                }
10131                PackageSetting ps = mSettings.mPackages.get(pkgName);
10132                if (ps != null) {
10133                    if (res.origUsers != null) {
10134                        for (int userHandle : res.origUsers) {
10135                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10136                                    userHandle, installerPackageName);
10137                        }
10138                    }
10139                    // Also convey the prior install/uninstall state
10140                    if (allUsers != null && perUserInstalled != null) {
10141                        for (int i = 0; i < allUsers.length; i++) {
10142                            if (DEBUG_INSTALL) {
10143                                Slog.d(TAG, "    user " + allUsers[i]
10144                                        + " => " + perUserInstalled[i]);
10145                            }
10146                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10147                        }
10148                        // these install state changes will be persisted in the
10149                        // upcoming call to mSettings.writeLPr().
10150                    }
10151                }
10152            }
10153            res.name = pkgName;
10154            res.uid = newPackage.applicationInfo.uid;
10155            res.pkg = newPackage;
10156            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10157            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10158            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10159            //to update install status
10160            mSettings.writeLPr();
10161        }
10162    }
10163
10164    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10165        final int installFlags = args.installFlags;
10166        String installerPackageName = args.installerPackageName;
10167        File tmpPackageFile = new File(args.getCodePath());
10168        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10169        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10170        boolean replace = false;
10171        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10172        // Result object to be returned
10173        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10174
10175        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10176        // Retrieve PackageSettings and parse package
10177        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10178                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10179                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10180        PackageParser pp = new PackageParser();
10181        pp.setSeparateProcesses(mSeparateProcesses);
10182        pp.setDisplayMetrics(mMetrics);
10183
10184        final PackageParser.Package pkg;
10185        try {
10186            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10187        } catch (PackageParserException e) {
10188            res.setError("Failed parse during installPackageLI", e);
10189            return;
10190        }
10191
10192        // Mark that we have an install time CPU ABI override.
10193        pkg.cpuAbiOverride = args.abiOverride;
10194
10195        String pkgName = res.name = pkg.packageName;
10196        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10197            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10198                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10199                return;
10200            }
10201        }
10202
10203        try {
10204            pp.collectCertificates(pkg, parseFlags);
10205            pp.collectManifestDigest(pkg);
10206        } catch (PackageParserException e) {
10207            res.setError("Failed collect during installPackageLI", e);
10208            return;
10209        }
10210
10211        /* If the installer passed in a manifest digest, compare it now. */
10212        if (args.manifestDigest != null) {
10213            if (DEBUG_INSTALL) {
10214                final String parsedManifest = pkg.manifestDigest == null ? "null"
10215                        : pkg.manifestDigest.toString();
10216                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10217                        + parsedManifest);
10218            }
10219
10220            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10221                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10222                return;
10223            }
10224        } else if (DEBUG_INSTALL) {
10225            final String parsedManifest = pkg.manifestDigest == null
10226                    ? "null" : pkg.manifestDigest.toString();
10227            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10228        }
10229
10230        // Get rid of all references to package scan path via parser.
10231        pp = null;
10232        String oldCodePath = null;
10233        boolean systemApp = false;
10234        synchronized (mPackages) {
10235            // Check whether the newly-scanned package wants to define an already-defined perm
10236            int N = pkg.permissions.size();
10237            for (int i = N-1; i >= 0; i--) {
10238                PackageParser.Permission perm = pkg.permissions.get(i);
10239                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10240                if (bp != null) {
10241                    // If the defining package is signed with our cert, it's okay.  This
10242                    // also includes the "updating the same package" case, of course.
10243                    // "updating same package" could also involve key-rotation.
10244                    final boolean sigsOk;
10245                    if (!bp.sourcePackage.equals(pkg.packageName)
10246                            || !(bp.packageSetting instanceof PackageSetting)
10247                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10248                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10249                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10250                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10251                    } else {
10252                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10253                    }
10254                    if (!sigsOk) {
10255                        // If the owning package is the system itself, we log but allow
10256                        // install to proceed; we fail the install on all other permission
10257                        // redefinitions.
10258                        if (!bp.sourcePackage.equals("android")) {
10259                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10260                                    + pkg.packageName + " attempting to redeclare permission "
10261                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10262                            res.origPermission = perm.info.name;
10263                            res.origPackage = bp.sourcePackage;
10264                            return;
10265                        } else {
10266                            Slog.w(TAG, "Package " + pkg.packageName
10267                                    + " attempting to redeclare system permission "
10268                                    + perm.info.name + "; ignoring new declaration");
10269                            pkg.permissions.remove(i);
10270                        }
10271                    }
10272                }
10273            }
10274
10275            // Check if installing already existing package
10276            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10277                String oldName = mSettings.mRenamedPackages.get(pkgName);
10278                if (pkg.mOriginalPackages != null
10279                        && pkg.mOriginalPackages.contains(oldName)
10280                        && mPackages.containsKey(oldName)) {
10281                    // This package is derived from an original package,
10282                    // and this device has been updating from that original
10283                    // name.  We must continue using the original name, so
10284                    // rename the new package here.
10285                    pkg.setPackageName(oldName);
10286                    pkgName = pkg.packageName;
10287                    replace = true;
10288                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10289                            + oldName + " pkgName=" + pkgName);
10290                } else if (mPackages.containsKey(pkgName)) {
10291                    // This package, under its official name, already exists
10292                    // on the device; we should replace it.
10293                    replace = true;
10294                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10295                }
10296            }
10297            PackageSetting ps = mSettings.mPackages.get(pkgName);
10298            if (ps != null) {
10299                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10300                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10301                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10302                    systemApp = (ps.pkg.applicationInfo.flags &
10303                            ApplicationInfo.FLAG_SYSTEM) != 0;
10304                }
10305                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10306            }
10307        }
10308
10309        if (systemApp && onSd) {
10310            // Disable updates to system apps on sdcard
10311            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10312                    "Cannot install updates to system apps on sdcard");
10313            return;
10314        }
10315
10316        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10317            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10318            return;
10319        }
10320
10321        if (replace) {
10322            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10323                    installerPackageName, res);
10324        } else {
10325            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10326                    args.user, installerPackageName, res);
10327        }
10328        synchronized (mPackages) {
10329            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10330            if (ps != null) {
10331                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10332            }
10333        }
10334    }
10335
10336    private static boolean isForwardLocked(PackageParser.Package pkg) {
10337        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10338    }
10339
10340    private static boolean isForwardLocked(ApplicationInfo info) {
10341        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10342    }
10343
10344    private boolean isForwardLocked(PackageSetting ps) {
10345        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10346    }
10347
10348    private static boolean isMultiArch(PackageSetting ps) {
10349        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10350    }
10351
10352    private static boolean isMultiArch(ApplicationInfo info) {
10353        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10354    }
10355
10356    private static boolean isExternal(PackageParser.Package pkg) {
10357        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10358    }
10359
10360    private static boolean isExternal(PackageSetting ps) {
10361        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10362    }
10363
10364    private static boolean isExternal(ApplicationInfo info) {
10365        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10366    }
10367
10368    private static boolean isSystemApp(PackageParser.Package pkg) {
10369        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10370    }
10371
10372    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10373        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10374    }
10375
10376    private static boolean isSystemApp(ApplicationInfo info) {
10377        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10378    }
10379
10380    private static boolean isSystemApp(PackageSetting ps) {
10381        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10382    }
10383
10384    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10385        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10386    }
10387
10388    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10389        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10390    }
10391
10392    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10393        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10394    }
10395
10396    private int packageFlagsToInstallFlags(PackageSetting ps) {
10397        int installFlags = 0;
10398        if (isExternal(ps)) {
10399            installFlags |= PackageManager.INSTALL_EXTERNAL;
10400        }
10401        if (isForwardLocked(ps)) {
10402            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10403        }
10404        return installFlags;
10405    }
10406
10407    private void deleteTempPackageFiles() {
10408        final FilenameFilter filter = new FilenameFilter() {
10409            public boolean accept(File dir, String name) {
10410                return name.startsWith("vmdl") && name.endsWith(".tmp");
10411            }
10412        };
10413        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10414            file.delete();
10415        }
10416    }
10417
10418    @Override
10419    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10420            int flags) {
10421        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10422                flags);
10423    }
10424
10425    @Override
10426    public void deletePackage(final String packageName,
10427            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10428        mContext.enforceCallingOrSelfPermission(
10429                android.Manifest.permission.DELETE_PACKAGES, null);
10430        final int uid = Binder.getCallingUid();
10431        if (UserHandle.getUserId(uid) != userId) {
10432            mContext.enforceCallingPermission(
10433                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10434                    "deletePackage for user " + userId);
10435        }
10436        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10437            try {
10438                observer.onPackageDeleted(packageName,
10439                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10440            } catch (RemoteException re) {
10441            }
10442            return;
10443        }
10444
10445        boolean uninstallBlocked = false;
10446        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10447            int[] users = sUserManager.getUserIds();
10448            for (int i = 0; i < users.length; ++i) {
10449                if (getBlockUninstallForUser(packageName, users[i])) {
10450                    uninstallBlocked = true;
10451                    break;
10452                }
10453            }
10454        } else {
10455            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10456        }
10457        if (uninstallBlocked) {
10458            try {
10459                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10460                        null);
10461            } catch (RemoteException re) {
10462            }
10463            return;
10464        }
10465
10466        if (DEBUG_REMOVE) {
10467            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10468        }
10469        // Queue up an async operation since the package deletion may take a little while.
10470        mHandler.post(new Runnable() {
10471            public void run() {
10472                mHandler.removeCallbacks(this);
10473                final int returnCode = deletePackageX(packageName, userId, flags);
10474                if (observer != null) {
10475                    try {
10476                        observer.onPackageDeleted(packageName, returnCode, null);
10477                    } catch (RemoteException e) {
10478                        Log.i(TAG, "Observer no longer exists.");
10479                    } //end catch
10480                } //end if
10481            } //end run
10482        });
10483    }
10484
10485    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10486        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10487                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10488        try {
10489            if (dpm != null) {
10490                if (dpm.isDeviceOwner(packageName)) {
10491                    return true;
10492                }
10493                int[] users;
10494                if (userId == UserHandle.USER_ALL) {
10495                    users = sUserManager.getUserIds();
10496                } else {
10497                    users = new int[]{userId};
10498                }
10499                for (int i = 0; i < users.length; ++i) {
10500                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10501                        return true;
10502                    }
10503                }
10504            }
10505        } catch (RemoteException e) {
10506        }
10507        return false;
10508    }
10509
10510    /**
10511     *  This method is an internal method that could be get invoked either
10512     *  to delete an installed package or to clean up a failed installation.
10513     *  After deleting an installed package, a broadcast is sent to notify any
10514     *  listeners that the package has been installed. For cleaning up a failed
10515     *  installation, the broadcast is not necessary since the package's
10516     *  installation wouldn't have sent the initial broadcast either
10517     *  The key steps in deleting a package are
10518     *  deleting the package information in internal structures like mPackages,
10519     *  deleting the packages base directories through installd
10520     *  updating mSettings to reflect current status
10521     *  persisting settings for later use
10522     *  sending a broadcast if necessary
10523     */
10524    private int deletePackageX(String packageName, int userId, int flags) {
10525        final PackageRemovedInfo info = new PackageRemovedInfo();
10526        final boolean res;
10527
10528        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10529                ? UserHandle.ALL : new UserHandle(userId);
10530
10531        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10532            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10533            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10534        }
10535
10536        boolean removedForAllUsers = false;
10537        boolean systemUpdate = false;
10538
10539        // for the uninstall-updates case and restricted profiles, remember the per-
10540        // userhandle installed state
10541        int[] allUsers;
10542        boolean[] perUserInstalled;
10543        synchronized (mPackages) {
10544            PackageSetting ps = mSettings.mPackages.get(packageName);
10545            allUsers = sUserManager.getUserIds();
10546            perUserInstalled = new boolean[allUsers.length];
10547            for (int i = 0; i < allUsers.length; i++) {
10548                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10549            }
10550        }
10551
10552        synchronized (mInstallLock) {
10553            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10554            res = deletePackageLI(packageName, removeForUser,
10555                    true, allUsers, perUserInstalled,
10556                    flags | REMOVE_CHATTY, info, true);
10557            systemUpdate = info.isRemovedPackageSystemUpdate;
10558            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10559                removedForAllUsers = true;
10560            }
10561            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10562                    + " removedForAllUsers=" + removedForAllUsers);
10563        }
10564
10565        if (res) {
10566            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10567
10568            // If the removed package was a system update, the old system package
10569            // was re-enabled; we need to broadcast this information
10570            if (systemUpdate) {
10571                Bundle extras = new Bundle(1);
10572                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10573                        ? info.removedAppId : info.uid);
10574                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10575
10576                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10577                        extras, null, null, null);
10578                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10579                        extras, null, null, null);
10580                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10581                        null, packageName, null, null);
10582            }
10583        }
10584        // Force a gc here.
10585        Runtime.getRuntime().gc();
10586        // Delete the resources here after sending the broadcast to let
10587        // other processes clean up before deleting resources.
10588        if (info.args != null) {
10589            synchronized (mInstallLock) {
10590                info.args.doPostDeleteLI(true);
10591            }
10592        }
10593
10594        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10595    }
10596
10597    static class PackageRemovedInfo {
10598        String removedPackage;
10599        int uid = -1;
10600        int removedAppId = -1;
10601        int[] removedUsers = null;
10602        boolean isRemovedPackageSystemUpdate = false;
10603        // Clean up resources deleted packages.
10604        InstallArgs args = null;
10605
10606        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10607            Bundle extras = new Bundle(1);
10608            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10609            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10610            if (replacing) {
10611                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10612            }
10613            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10614            if (removedPackage != null) {
10615                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10616                        extras, null, null, removedUsers);
10617                if (fullRemove && !replacing) {
10618                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10619                            extras, null, null, removedUsers);
10620                }
10621            }
10622            if (removedAppId >= 0) {
10623                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10624                        removedUsers);
10625            }
10626        }
10627    }
10628
10629    /*
10630     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10631     * flag is not set, the data directory is removed as well.
10632     * make sure this flag is set for partially installed apps. If not its meaningless to
10633     * delete a partially installed application.
10634     */
10635    private void removePackageDataLI(PackageSetting ps,
10636            int[] allUserHandles, boolean[] perUserInstalled,
10637            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10638        String packageName = ps.name;
10639        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10640        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10641        // Retrieve object to delete permissions for shared user later on
10642        final PackageSetting deletedPs;
10643        // reader
10644        synchronized (mPackages) {
10645            deletedPs = mSettings.mPackages.get(packageName);
10646            if (outInfo != null) {
10647                outInfo.removedPackage = packageName;
10648                outInfo.removedUsers = deletedPs != null
10649                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10650                        : null;
10651            }
10652        }
10653        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10654            removeDataDirsLI(packageName);
10655            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10656        }
10657        // writer
10658        synchronized (mPackages) {
10659            if (deletedPs != null) {
10660                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10661                    if (outInfo != null) {
10662                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10663                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10664                    }
10665                    if (deletedPs != null) {
10666                        updatePermissionsLPw(deletedPs.name, null, 0);
10667                        if (deletedPs.sharedUser != null) {
10668                            // remove permissions associated with package
10669                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10670                        }
10671                    }
10672                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10673                }
10674                // make sure to preserve per-user disabled state if this removal was just
10675                // a downgrade of a system app to the factory package
10676                if (allUserHandles != null && perUserInstalled != null) {
10677                    if (DEBUG_REMOVE) {
10678                        Slog.d(TAG, "Propagating install state across downgrade");
10679                    }
10680                    for (int i = 0; i < allUserHandles.length; i++) {
10681                        if (DEBUG_REMOVE) {
10682                            Slog.d(TAG, "    user " + allUserHandles[i]
10683                                    + " => " + perUserInstalled[i]);
10684                        }
10685                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10686                    }
10687                }
10688            }
10689            // can downgrade to reader
10690            if (writeSettings) {
10691                // Save settings now
10692                mSettings.writeLPr();
10693            }
10694        }
10695        if (outInfo != null) {
10696            // A user ID was deleted here. Go through all users and remove it
10697            // from KeyStore.
10698            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10699        }
10700    }
10701
10702    static boolean locationIsPrivileged(File path) {
10703        try {
10704            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10705                    .getCanonicalPath();
10706            return path.getCanonicalPath().startsWith(privilegedAppDir);
10707        } catch (IOException e) {
10708            Slog.e(TAG, "Unable to access code path " + path);
10709        }
10710        return false;
10711    }
10712
10713    /*
10714     * Tries to delete system package.
10715     */
10716    private boolean deleteSystemPackageLI(PackageSetting newPs,
10717            int[] allUserHandles, boolean[] perUserInstalled,
10718            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10719        final boolean applyUserRestrictions
10720                = (allUserHandles != null) && (perUserInstalled != null);
10721        PackageSetting disabledPs = null;
10722        // Confirm if the system package has been updated
10723        // An updated system app can be deleted. This will also have to restore
10724        // the system pkg from system partition
10725        // reader
10726        synchronized (mPackages) {
10727            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10728        }
10729        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10730                + " disabledPs=" + disabledPs);
10731        if (disabledPs == null) {
10732            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10733            return false;
10734        } else if (DEBUG_REMOVE) {
10735            Slog.d(TAG, "Deleting system pkg from data partition");
10736        }
10737        if (DEBUG_REMOVE) {
10738            if (applyUserRestrictions) {
10739                Slog.d(TAG, "Remembering install states:");
10740                for (int i = 0; i < allUserHandles.length; i++) {
10741                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10742                }
10743            }
10744        }
10745        // Delete the updated package
10746        outInfo.isRemovedPackageSystemUpdate = true;
10747        if (disabledPs.versionCode < newPs.versionCode) {
10748            // Delete data for downgrades
10749            flags &= ~PackageManager.DELETE_KEEP_DATA;
10750        } else {
10751            // Preserve data by setting flag
10752            flags |= PackageManager.DELETE_KEEP_DATA;
10753        }
10754        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10755                allUserHandles, perUserInstalled, outInfo, writeSettings);
10756        if (!ret) {
10757            return false;
10758        }
10759        // writer
10760        synchronized (mPackages) {
10761            // Reinstate the old system package
10762            mSettings.enableSystemPackageLPw(newPs.name);
10763            // Remove any native libraries from the upgraded package.
10764            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10765        }
10766        // Install the system package
10767        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10768        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10769        if (locationIsPrivileged(disabledPs.codePath)) {
10770            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10771        }
10772
10773        final PackageParser.Package newPkg;
10774        try {
10775            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10776        } catch (PackageManagerException e) {
10777            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10778            return false;
10779        }
10780
10781        // writer
10782        synchronized (mPackages) {
10783            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10784            updatePermissionsLPw(newPkg.packageName, newPkg,
10785                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10786            if (applyUserRestrictions) {
10787                if (DEBUG_REMOVE) {
10788                    Slog.d(TAG, "Propagating install state across reinstall");
10789                }
10790                for (int i = 0; i < allUserHandles.length; i++) {
10791                    if (DEBUG_REMOVE) {
10792                        Slog.d(TAG, "    user " + allUserHandles[i]
10793                                + " => " + perUserInstalled[i]);
10794                    }
10795                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10796                }
10797                // Regardless of writeSettings we need to ensure that this restriction
10798                // state propagation is persisted
10799                mSettings.writeAllUsersPackageRestrictionsLPr();
10800            }
10801            // can downgrade to reader here
10802            if (writeSettings) {
10803                mSettings.writeLPr();
10804            }
10805        }
10806        return true;
10807    }
10808
10809    private boolean deleteInstalledPackageLI(PackageSetting ps,
10810            boolean deleteCodeAndResources, int flags,
10811            int[] allUserHandles, boolean[] perUserInstalled,
10812            PackageRemovedInfo outInfo, boolean writeSettings) {
10813        if (outInfo != null) {
10814            outInfo.uid = ps.appId;
10815        }
10816
10817        // Delete package data from internal structures and also remove data if flag is set
10818        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10819
10820        // Delete application code and resources
10821        if (deleteCodeAndResources && (outInfo != null)) {
10822            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10823                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10824                    getAppDexInstructionSets(ps));
10825            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10826        }
10827        return true;
10828    }
10829
10830    @Override
10831    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10832            int userId) {
10833        mContext.enforceCallingOrSelfPermission(
10834                android.Manifest.permission.DELETE_PACKAGES, null);
10835        synchronized (mPackages) {
10836            PackageSetting ps = mSettings.mPackages.get(packageName);
10837            if (ps == null) {
10838                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10839                return false;
10840            }
10841            if (!ps.getInstalled(userId)) {
10842                // Can't block uninstall for an app that is not installed or enabled.
10843                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10844                return false;
10845            }
10846            ps.setBlockUninstall(blockUninstall, userId);
10847            mSettings.writePackageRestrictionsLPr(userId);
10848        }
10849        return true;
10850    }
10851
10852    @Override
10853    public boolean getBlockUninstallForUser(String packageName, int userId) {
10854        synchronized (mPackages) {
10855            PackageSetting ps = mSettings.mPackages.get(packageName);
10856            if (ps == null) {
10857                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10858                return false;
10859            }
10860            return ps.getBlockUninstall(userId);
10861        }
10862    }
10863
10864    /*
10865     * This method handles package deletion in general
10866     */
10867    private boolean deletePackageLI(String packageName, UserHandle user,
10868            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10869            int flags, PackageRemovedInfo outInfo,
10870            boolean writeSettings) {
10871        if (packageName == null) {
10872            Slog.w(TAG, "Attempt to delete null packageName.");
10873            return false;
10874        }
10875        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10876        PackageSetting ps;
10877        boolean dataOnly = false;
10878        int removeUser = -1;
10879        int appId = -1;
10880        synchronized (mPackages) {
10881            ps = mSettings.mPackages.get(packageName);
10882            if (ps == null) {
10883                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10884                return false;
10885            }
10886            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10887                    && user.getIdentifier() != UserHandle.USER_ALL) {
10888                // The caller is asking that the package only be deleted for a single
10889                // user.  To do this, we just mark its uninstalled state and delete
10890                // its data.  If this is a system app, we only allow this to happen if
10891                // they have set the special DELETE_SYSTEM_APP which requests different
10892                // semantics than normal for uninstalling system apps.
10893                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10894                ps.setUserState(user.getIdentifier(),
10895                        COMPONENT_ENABLED_STATE_DEFAULT,
10896                        false, //installed
10897                        true,  //stopped
10898                        true,  //notLaunched
10899                        false, //hidden
10900                        null, null, null,
10901                        false // blockUninstall
10902                        );
10903                if (!isSystemApp(ps)) {
10904                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10905                        // Other user still have this package installed, so all
10906                        // we need to do is clear this user's data and save that
10907                        // it is uninstalled.
10908                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10909                        removeUser = user.getIdentifier();
10910                        appId = ps.appId;
10911                        mSettings.writePackageRestrictionsLPr(removeUser);
10912                    } else {
10913                        // We need to set it back to 'installed' so the uninstall
10914                        // broadcasts will be sent correctly.
10915                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10916                        ps.setInstalled(true, user.getIdentifier());
10917                    }
10918                } else {
10919                    // This is a system app, so we assume that the
10920                    // other users still have this package installed, so all
10921                    // we need to do is clear this user's data and save that
10922                    // it is uninstalled.
10923                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10924                    removeUser = user.getIdentifier();
10925                    appId = ps.appId;
10926                    mSettings.writePackageRestrictionsLPr(removeUser);
10927                }
10928            }
10929        }
10930
10931        if (removeUser >= 0) {
10932            // From above, we determined that we are deleting this only
10933            // for a single user.  Continue the work here.
10934            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10935            if (outInfo != null) {
10936                outInfo.removedPackage = packageName;
10937                outInfo.removedAppId = appId;
10938                outInfo.removedUsers = new int[] {removeUser};
10939            }
10940            mInstaller.clearUserData(packageName, removeUser);
10941            removeKeystoreDataIfNeeded(removeUser, appId);
10942            schedulePackageCleaning(packageName, removeUser, false);
10943            return true;
10944        }
10945
10946        if (dataOnly) {
10947            // Delete application data first
10948            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10949            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10950            return true;
10951        }
10952
10953        boolean ret = false;
10954        if (isSystemApp(ps)) {
10955            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10956            // When an updated system application is deleted we delete the existing resources as well and
10957            // fall back to existing code in system partition
10958            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10959                    flags, outInfo, writeSettings);
10960        } else {
10961            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10962            // Kill application pre-emptively especially for apps on sd.
10963            killApplication(packageName, ps.appId, "uninstall pkg");
10964            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10965                    allUserHandles, perUserInstalled,
10966                    outInfo, writeSettings);
10967        }
10968
10969        return ret;
10970    }
10971
10972    private final class ClearStorageConnection implements ServiceConnection {
10973        IMediaContainerService mContainerService;
10974
10975        @Override
10976        public void onServiceConnected(ComponentName name, IBinder service) {
10977            synchronized (this) {
10978                mContainerService = IMediaContainerService.Stub.asInterface(service);
10979                notifyAll();
10980            }
10981        }
10982
10983        @Override
10984        public void onServiceDisconnected(ComponentName name) {
10985        }
10986    }
10987
10988    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10989        final boolean mounted;
10990        if (Environment.isExternalStorageEmulated()) {
10991            mounted = true;
10992        } else {
10993            final String status = Environment.getExternalStorageState();
10994
10995            mounted = status.equals(Environment.MEDIA_MOUNTED)
10996                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10997        }
10998
10999        if (!mounted) {
11000            return;
11001        }
11002
11003        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11004        int[] users;
11005        if (userId == UserHandle.USER_ALL) {
11006            users = sUserManager.getUserIds();
11007        } else {
11008            users = new int[] { userId };
11009        }
11010        final ClearStorageConnection conn = new ClearStorageConnection();
11011        if (mContext.bindServiceAsUser(
11012                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11013            try {
11014                for (int curUser : users) {
11015                    long timeout = SystemClock.uptimeMillis() + 5000;
11016                    synchronized (conn) {
11017                        long now = SystemClock.uptimeMillis();
11018                        while (conn.mContainerService == null && now < timeout) {
11019                            try {
11020                                conn.wait(timeout - now);
11021                            } catch (InterruptedException e) {
11022                            }
11023                        }
11024                    }
11025                    if (conn.mContainerService == null) {
11026                        return;
11027                    }
11028
11029                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11030                    clearDirectory(conn.mContainerService,
11031                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11032                    if (allData) {
11033                        clearDirectory(conn.mContainerService,
11034                                userEnv.buildExternalStorageAppDataDirs(packageName));
11035                        clearDirectory(conn.mContainerService,
11036                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11037                    }
11038                }
11039            } finally {
11040                mContext.unbindService(conn);
11041            }
11042        }
11043    }
11044
11045    @Override
11046    public void clearApplicationUserData(final String packageName,
11047            final IPackageDataObserver observer, final int userId) {
11048        mContext.enforceCallingOrSelfPermission(
11049                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11050        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11051        // Queue up an async operation since the package deletion may take a little while.
11052        mHandler.post(new Runnable() {
11053            public void run() {
11054                mHandler.removeCallbacks(this);
11055                final boolean succeeded;
11056                synchronized (mInstallLock) {
11057                    succeeded = clearApplicationUserDataLI(packageName, userId);
11058                }
11059                clearExternalStorageDataSync(packageName, userId, true);
11060                if (succeeded) {
11061                    // invoke DeviceStorageMonitor's update method to clear any notifications
11062                    DeviceStorageMonitorInternal
11063                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11064                    if (dsm != null) {
11065                        dsm.checkMemory();
11066                    }
11067                }
11068                if(observer != null) {
11069                    try {
11070                        observer.onRemoveCompleted(packageName, succeeded);
11071                    } catch (RemoteException e) {
11072                        Log.i(TAG, "Observer no longer exists.");
11073                    }
11074                } //end if observer
11075            } //end run
11076        });
11077    }
11078
11079    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11080        if (packageName == null) {
11081            Slog.w(TAG, "Attempt to delete null packageName.");
11082            return false;
11083        }
11084
11085        // Try finding details about the requested package
11086        PackageParser.Package pkg;
11087        synchronized (mPackages) {
11088            pkg = mPackages.get(packageName);
11089            if (pkg == null) {
11090                final PackageSetting ps = mSettings.mPackages.get(packageName);
11091                if (ps != null) {
11092                    pkg = ps.pkg;
11093                }
11094            }
11095        }
11096
11097        if (pkg == null) {
11098            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11099        }
11100
11101        // Always delete data directories for package, even if we found no other
11102        // record of app. This helps users recover from UID mismatches without
11103        // resorting to a full data wipe.
11104        int retCode = mInstaller.clearUserData(packageName, userId);
11105        if (retCode < 0) {
11106            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11107            return false;
11108        }
11109
11110        if (pkg == null) {
11111            return false;
11112        }
11113
11114        if (pkg != null && pkg.applicationInfo != null) {
11115            final int appId = pkg.applicationInfo.uid;
11116            removeKeystoreDataIfNeeded(userId, appId);
11117        }
11118
11119        // Create a native library symlink only if we have native libraries
11120        // and if the native libraries are 32 bit libraries. We do not provide
11121        // this symlink for 64 bit libraries.
11122        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11123                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11124            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11125            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11126                Slog.w(TAG, "Failed linking native library dir");
11127                return false;
11128            }
11129        }
11130
11131        return true;
11132    }
11133
11134    /**
11135     * Remove entries from the keystore daemon. Will only remove it if the
11136     * {@code appId} is valid.
11137     */
11138    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11139        if (appId < 0) {
11140            return;
11141        }
11142
11143        final KeyStore keyStore = KeyStore.getInstance();
11144        if (keyStore != null) {
11145            if (userId == UserHandle.USER_ALL) {
11146                for (final int individual : sUserManager.getUserIds()) {
11147                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11148                }
11149            } else {
11150                keyStore.clearUid(UserHandle.getUid(userId, appId));
11151            }
11152        } else {
11153            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11154        }
11155    }
11156
11157    @Override
11158    public void deleteApplicationCacheFiles(final String packageName,
11159            final IPackageDataObserver observer) {
11160        mContext.enforceCallingOrSelfPermission(
11161                android.Manifest.permission.DELETE_CACHE_FILES, null);
11162        // Queue up an async operation since the package deletion may take a little while.
11163        final int userId = UserHandle.getCallingUserId();
11164        mHandler.post(new Runnable() {
11165            public void run() {
11166                mHandler.removeCallbacks(this);
11167                final boolean succeded;
11168                synchronized (mInstallLock) {
11169                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11170                }
11171                clearExternalStorageDataSync(packageName, userId, false);
11172                if(observer != null) {
11173                    try {
11174                        observer.onRemoveCompleted(packageName, succeded);
11175                    } catch (RemoteException e) {
11176                        Log.i(TAG, "Observer no longer exists.");
11177                    }
11178                } //end if observer
11179            } //end run
11180        });
11181    }
11182
11183    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11184        if (packageName == null) {
11185            Slog.w(TAG, "Attempt to delete null packageName.");
11186            return false;
11187        }
11188        PackageParser.Package p;
11189        synchronized (mPackages) {
11190            p = mPackages.get(packageName);
11191        }
11192        if (p == null) {
11193            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11194            return false;
11195        }
11196        final ApplicationInfo applicationInfo = p.applicationInfo;
11197        if (applicationInfo == null) {
11198            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11199            return false;
11200        }
11201        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11202        if (retCode < 0) {
11203            Slog.w(TAG, "Couldn't remove cache files for package: "
11204                       + packageName + " u" + userId);
11205            return false;
11206        }
11207        return true;
11208    }
11209
11210    @Override
11211    public void getPackageSizeInfo(final String packageName, int userHandle,
11212            final IPackageStatsObserver observer) {
11213        mContext.enforceCallingOrSelfPermission(
11214                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11215        if (packageName == null) {
11216            throw new IllegalArgumentException("Attempt to get size of null packageName");
11217        }
11218
11219        PackageStats stats = new PackageStats(packageName, userHandle);
11220
11221        /*
11222         * Queue up an async operation since the package measurement may take a
11223         * little while.
11224         */
11225        Message msg = mHandler.obtainMessage(INIT_COPY);
11226        msg.obj = new MeasureParams(stats, observer);
11227        mHandler.sendMessage(msg);
11228    }
11229
11230    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11231            PackageStats pStats) {
11232        if (packageName == null) {
11233            Slog.w(TAG, "Attempt to get size of null packageName.");
11234            return false;
11235        }
11236        PackageParser.Package p;
11237        boolean dataOnly = false;
11238        String libDirRoot = null;
11239        String asecPath = null;
11240        PackageSetting ps = null;
11241        synchronized (mPackages) {
11242            p = mPackages.get(packageName);
11243            ps = mSettings.mPackages.get(packageName);
11244            if(p == null) {
11245                dataOnly = true;
11246                if((ps == null) || (ps.pkg == null)) {
11247                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11248                    return false;
11249                }
11250                p = ps.pkg;
11251            }
11252            if (ps != null) {
11253                libDirRoot = ps.legacyNativeLibraryPathString;
11254            }
11255            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11256                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11257                if (secureContainerId != null) {
11258                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11259                }
11260            }
11261        }
11262        String publicSrcDir = null;
11263        if(!dataOnly) {
11264            final ApplicationInfo applicationInfo = p.applicationInfo;
11265            if (applicationInfo == null) {
11266                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11267                return false;
11268            }
11269            if (isForwardLocked(p)) {
11270                publicSrcDir = applicationInfo.getBaseResourcePath();
11271            }
11272        }
11273        // TODO: extend to measure size of split APKs
11274        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11275        // not just the first level.
11276        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11277        // just the primary.
11278        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11279        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11280                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11281        if (res < 0) {
11282            return false;
11283        }
11284
11285        // Fix-up for forward-locked applications in ASEC containers.
11286        if (!isExternal(p)) {
11287            pStats.codeSize += pStats.externalCodeSize;
11288            pStats.externalCodeSize = 0L;
11289        }
11290
11291        return true;
11292    }
11293
11294
11295    @Override
11296    public void addPackageToPreferred(String packageName) {
11297        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11298    }
11299
11300    @Override
11301    public void removePackageFromPreferred(String packageName) {
11302        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11303    }
11304
11305    @Override
11306    public List<PackageInfo> getPreferredPackages(int flags) {
11307        return new ArrayList<PackageInfo>();
11308    }
11309
11310    private int getUidTargetSdkVersionLockedLPr(int uid) {
11311        Object obj = mSettings.getUserIdLPr(uid);
11312        if (obj instanceof SharedUserSetting) {
11313            final SharedUserSetting sus = (SharedUserSetting) obj;
11314            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11315            final Iterator<PackageSetting> it = sus.packages.iterator();
11316            while (it.hasNext()) {
11317                final PackageSetting ps = it.next();
11318                if (ps.pkg != null) {
11319                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11320                    if (v < vers) vers = v;
11321                }
11322            }
11323            return vers;
11324        } else if (obj instanceof PackageSetting) {
11325            final PackageSetting ps = (PackageSetting) obj;
11326            if (ps.pkg != null) {
11327                return ps.pkg.applicationInfo.targetSdkVersion;
11328            }
11329        }
11330        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11331    }
11332
11333    @Override
11334    public void addPreferredActivity(IntentFilter filter, int match,
11335            ComponentName[] set, ComponentName activity, int userId) {
11336        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11337                "Adding preferred");
11338    }
11339
11340    private void addPreferredActivityInternal(IntentFilter filter, int match,
11341            ComponentName[] set, ComponentName activity, boolean always, int userId,
11342            String opname) {
11343        // writer
11344        int callingUid = Binder.getCallingUid();
11345        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11346        if (filter.countActions() == 0) {
11347            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11348            return;
11349        }
11350        synchronized (mPackages) {
11351            if (mContext.checkCallingOrSelfPermission(
11352                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11353                    != PackageManager.PERMISSION_GRANTED) {
11354                if (getUidTargetSdkVersionLockedLPr(callingUid)
11355                        < Build.VERSION_CODES.FROYO) {
11356                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11357                            + callingUid);
11358                    return;
11359                }
11360                mContext.enforceCallingOrSelfPermission(
11361                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11362            }
11363
11364            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11365            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11366                    + userId + ":");
11367            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11368            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11369            mSettings.writePackageRestrictionsLPr(userId);
11370        }
11371    }
11372
11373    @Override
11374    public void replacePreferredActivity(IntentFilter filter, int match,
11375            ComponentName[] set, ComponentName activity, int userId) {
11376        if (filter.countActions() != 1) {
11377            throw new IllegalArgumentException(
11378                    "replacePreferredActivity expects filter to have only 1 action.");
11379        }
11380        if (filter.countDataAuthorities() != 0
11381                || filter.countDataPaths() != 0
11382                || filter.countDataSchemes() > 1
11383                || filter.countDataTypes() != 0) {
11384            throw new IllegalArgumentException(
11385                    "replacePreferredActivity expects filter to have no data authorities, " +
11386                    "paths, or types; and at most one scheme.");
11387        }
11388
11389        final int callingUid = Binder.getCallingUid();
11390        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11391        synchronized (mPackages) {
11392            if (mContext.checkCallingOrSelfPermission(
11393                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11394                    != PackageManager.PERMISSION_GRANTED) {
11395                if (getUidTargetSdkVersionLockedLPr(callingUid)
11396                        < Build.VERSION_CODES.FROYO) {
11397                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11398                            + Binder.getCallingUid());
11399                    return;
11400                }
11401                mContext.enforceCallingOrSelfPermission(
11402                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11403            }
11404
11405            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11406            if (pir != null) {
11407                // Get all of the existing entries that exactly match this filter.
11408                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11409                if (existing != null && existing.size() == 1) {
11410                    PreferredActivity cur = existing.get(0);
11411                    if (DEBUG_PREFERRED) {
11412                        Slog.i(TAG, "Checking replace of preferred:");
11413                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11414                        if (!cur.mPref.mAlways) {
11415                            Slog.i(TAG, "  -- CUR; not mAlways!");
11416                        } else {
11417                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11418                            Slog.i(TAG, "  -- CUR: mSet="
11419                                    + Arrays.toString(cur.mPref.mSetComponents));
11420                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11421                            Slog.i(TAG, "  -- NEW: mMatch="
11422                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11423                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11424                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11425                        }
11426                    }
11427                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11428                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11429                            && cur.mPref.sameSet(set)) {
11430                        // Setting the preferred activity to what it happens to be already
11431                        if (DEBUG_PREFERRED) {
11432                            Slog.i(TAG, "Replacing with same preferred activity "
11433                                    + cur.mPref.mShortComponent + " for user "
11434                                    + userId + ":");
11435                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11436                        }
11437                        return;
11438                    }
11439                }
11440
11441                if (existing != null) {
11442                    if (DEBUG_PREFERRED) {
11443                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11444                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11445                    }
11446                    for (int i = 0; i < existing.size(); i++) {
11447                        PreferredActivity pa = existing.get(i);
11448                        if (DEBUG_PREFERRED) {
11449                            Slog.i(TAG, "Removing existing preferred activity "
11450                                    + pa.mPref.mComponent + ":");
11451                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11452                        }
11453                        pir.removeFilter(pa);
11454                    }
11455                }
11456            }
11457            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11458                    "Replacing preferred");
11459        }
11460    }
11461
11462    @Override
11463    public void clearPackagePreferredActivities(String packageName) {
11464        final int uid = Binder.getCallingUid();
11465        // writer
11466        synchronized (mPackages) {
11467            PackageParser.Package pkg = mPackages.get(packageName);
11468            if (pkg == null || pkg.applicationInfo.uid != uid) {
11469                if (mContext.checkCallingOrSelfPermission(
11470                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11471                        != PackageManager.PERMISSION_GRANTED) {
11472                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11473                            < Build.VERSION_CODES.FROYO) {
11474                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11475                                + Binder.getCallingUid());
11476                        return;
11477                    }
11478                    mContext.enforceCallingOrSelfPermission(
11479                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11480                }
11481            }
11482
11483            int user = UserHandle.getCallingUserId();
11484            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11485                mSettings.writePackageRestrictionsLPr(user);
11486                scheduleWriteSettingsLocked();
11487            }
11488        }
11489    }
11490
11491    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11492    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11493        ArrayList<PreferredActivity> removed = null;
11494        boolean changed = false;
11495        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11496            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11497            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11498            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11499                continue;
11500            }
11501            Iterator<PreferredActivity> it = pir.filterIterator();
11502            while (it.hasNext()) {
11503                PreferredActivity pa = it.next();
11504                // Mark entry for removal only if it matches the package name
11505                // and the entry is of type "always".
11506                if (packageName == null ||
11507                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11508                                && pa.mPref.mAlways)) {
11509                    if (removed == null) {
11510                        removed = new ArrayList<PreferredActivity>();
11511                    }
11512                    removed.add(pa);
11513                }
11514            }
11515            if (removed != null) {
11516                for (int j=0; j<removed.size(); j++) {
11517                    PreferredActivity pa = removed.get(j);
11518                    pir.removeFilter(pa);
11519                }
11520                changed = true;
11521            }
11522        }
11523        return changed;
11524    }
11525
11526    @Override
11527    public void resetPreferredActivities(int userId) {
11528        /* TODO: Actually use userId. Why is it being passed in? */
11529        mContext.enforceCallingOrSelfPermission(
11530                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11531        // writer
11532        synchronized (mPackages) {
11533            int user = UserHandle.getCallingUserId();
11534            clearPackagePreferredActivitiesLPw(null, user);
11535            mSettings.readDefaultPreferredAppsLPw(this, user);
11536            mSettings.writePackageRestrictionsLPr(user);
11537            scheduleWriteSettingsLocked();
11538        }
11539    }
11540
11541    @Override
11542    public int getPreferredActivities(List<IntentFilter> outFilters,
11543            List<ComponentName> outActivities, String packageName) {
11544
11545        int num = 0;
11546        final int userId = UserHandle.getCallingUserId();
11547        // reader
11548        synchronized (mPackages) {
11549            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11550            if (pir != null) {
11551                final Iterator<PreferredActivity> it = pir.filterIterator();
11552                while (it.hasNext()) {
11553                    final PreferredActivity pa = it.next();
11554                    if (packageName == null
11555                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11556                                    && pa.mPref.mAlways)) {
11557                        if (outFilters != null) {
11558                            outFilters.add(new IntentFilter(pa));
11559                        }
11560                        if (outActivities != null) {
11561                            outActivities.add(pa.mPref.mComponent);
11562                        }
11563                    }
11564                }
11565            }
11566        }
11567
11568        return num;
11569    }
11570
11571    @Override
11572    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11573            int userId) {
11574        int callingUid = Binder.getCallingUid();
11575        if (callingUid != Process.SYSTEM_UID) {
11576            throw new SecurityException(
11577                    "addPersistentPreferredActivity can only be run by the system");
11578        }
11579        if (filter.countActions() == 0) {
11580            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11581            return;
11582        }
11583        synchronized (mPackages) {
11584            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11585                    " :");
11586            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11587            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11588                    new PersistentPreferredActivity(filter, activity));
11589            mSettings.writePackageRestrictionsLPr(userId);
11590        }
11591    }
11592
11593    @Override
11594    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11595        int callingUid = Binder.getCallingUid();
11596        if (callingUid != Process.SYSTEM_UID) {
11597            throw new SecurityException(
11598                    "clearPackagePersistentPreferredActivities can only be run by the system");
11599        }
11600        ArrayList<PersistentPreferredActivity> removed = null;
11601        boolean changed = false;
11602        synchronized (mPackages) {
11603            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11604                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11605                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11606                        .valueAt(i);
11607                if (userId != thisUserId) {
11608                    continue;
11609                }
11610                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11611                while (it.hasNext()) {
11612                    PersistentPreferredActivity ppa = it.next();
11613                    // Mark entry for removal only if it matches the package name.
11614                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11615                        if (removed == null) {
11616                            removed = new ArrayList<PersistentPreferredActivity>();
11617                        }
11618                        removed.add(ppa);
11619                    }
11620                }
11621                if (removed != null) {
11622                    for (int j=0; j<removed.size(); j++) {
11623                        PersistentPreferredActivity ppa = removed.get(j);
11624                        ppir.removeFilter(ppa);
11625                    }
11626                    changed = true;
11627                }
11628            }
11629
11630            if (changed) {
11631                mSettings.writePackageRestrictionsLPr(userId);
11632            }
11633        }
11634    }
11635
11636    @Override
11637    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11638            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11639        mContext.enforceCallingOrSelfPermission(
11640                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11641        int callingUid = Binder.getCallingUid();
11642        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11643        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11644        if (intentFilter.countActions() == 0) {
11645            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11646            return;
11647        }
11648        synchronized (mPackages) {
11649            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11650                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11651            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11652            mSettings.writePackageRestrictionsLPr(sourceUserId);
11653        }
11654    }
11655
11656    @Override
11657    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11658            int ownerUserId) {
11659        mContext.enforceCallingOrSelfPermission(
11660                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11661        int callingUid = Binder.getCallingUid();
11662        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11663        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11664        int callingUserId = UserHandle.getUserId(callingUid);
11665        synchronized (mPackages) {
11666            CrossProfileIntentResolver resolver =
11667                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11668            HashSet<CrossProfileIntentFilter> set =
11669                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11670            for (CrossProfileIntentFilter filter : set) {
11671                if (filter.getOwnerPackage().equals(ownerPackage)
11672                        && filter.getOwnerUserId() == callingUserId) {
11673                    resolver.removeFilter(filter);
11674                }
11675            }
11676            mSettings.writePackageRestrictionsLPr(sourceUserId);
11677        }
11678    }
11679
11680    // Enforcing that callingUid is owning pkg on userId
11681    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11682        // The system owns everything.
11683        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11684            return;
11685        }
11686        int callingUserId = UserHandle.getUserId(callingUid);
11687        if (callingUserId != userId) {
11688            throw new SecurityException("calling uid " + callingUid
11689                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11690                    + callingUserId);
11691        }
11692        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11693        if (pi == null) {
11694            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11695                    + callingUserId);
11696        }
11697        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11698            throw new SecurityException("Calling uid " + callingUid
11699                    + " does not own package " + pkg);
11700        }
11701    }
11702
11703    @Override
11704    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11705        Intent intent = new Intent(Intent.ACTION_MAIN);
11706        intent.addCategory(Intent.CATEGORY_HOME);
11707
11708        final int callingUserId = UserHandle.getCallingUserId();
11709        List<ResolveInfo> list = queryIntentActivities(intent, null,
11710                PackageManager.GET_META_DATA, callingUserId);
11711        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11712                true, false, false, callingUserId);
11713
11714        allHomeCandidates.clear();
11715        if (list != null) {
11716            for (ResolveInfo ri : list) {
11717                allHomeCandidates.add(ri);
11718            }
11719        }
11720        return (preferred == null || preferred.activityInfo == null)
11721                ? null
11722                : new ComponentName(preferred.activityInfo.packageName,
11723                        preferred.activityInfo.name);
11724    }
11725
11726    @Override
11727    public void setApplicationEnabledSetting(String appPackageName,
11728            int newState, int flags, int userId, String callingPackage) {
11729        if (!sUserManager.exists(userId)) return;
11730        if (callingPackage == null) {
11731            callingPackage = Integer.toString(Binder.getCallingUid());
11732        }
11733        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11734    }
11735
11736    @Override
11737    public void setComponentEnabledSetting(ComponentName componentName,
11738            int newState, int flags, int userId) {
11739        if (!sUserManager.exists(userId)) return;
11740        setEnabledSetting(componentName.getPackageName(),
11741                componentName.getClassName(), newState, flags, userId, null);
11742    }
11743
11744    private void setEnabledSetting(final String packageName, String className, int newState,
11745            final int flags, int userId, String callingPackage) {
11746        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11747              || newState == COMPONENT_ENABLED_STATE_ENABLED
11748              || newState == COMPONENT_ENABLED_STATE_DISABLED
11749              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11750              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11751            throw new IllegalArgumentException("Invalid new component state: "
11752                    + newState);
11753        }
11754        PackageSetting pkgSetting;
11755        final int uid = Binder.getCallingUid();
11756        final int permission = mContext.checkCallingOrSelfPermission(
11757                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11758        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11759        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11760        boolean sendNow = false;
11761        boolean isApp = (className == null);
11762        String componentName = isApp ? packageName : className;
11763        int packageUid = -1;
11764        ArrayList<String> components;
11765
11766        // writer
11767        synchronized (mPackages) {
11768            pkgSetting = mSettings.mPackages.get(packageName);
11769            if (pkgSetting == null) {
11770                if (className == null) {
11771                    throw new IllegalArgumentException(
11772                            "Unknown package: " + packageName);
11773                }
11774                throw new IllegalArgumentException(
11775                        "Unknown component: " + packageName
11776                        + "/" + className);
11777            }
11778            // Allow root and verify that userId is not being specified by a different user
11779            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11780                throw new SecurityException(
11781                        "Permission Denial: attempt to change component state from pid="
11782                        + Binder.getCallingPid()
11783                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11784            }
11785            if (className == null) {
11786                // We're dealing with an application/package level state change
11787                if (pkgSetting.getEnabled(userId) == newState) {
11788                    // Nothing to do
11789                    return;
11790                }
11791                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11792                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11793                    // Don't care about who enables an app.
11794                    callingPackage = null;
11795                }
11796                pkgSetting.setEnabled(newState, userId, callingPackage);
11797                // pkgSetting.pkg.mSetEnabled = newState;
11798            } else {
11799                // We're dealing with a component level state change
11800                // First, verify that this is a valid class name.
11801                PackageParser.Package pkg = pkgSetting.pkg;
11802                if (pkg == null || !pkg.hasComponentClassName(className)) {
11803                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11804                        throw new IllegalArgumentException("Component class " + className
11805                                + " does not exist in " + packageName);
11806                    } else {
11807                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11808                                + className + " does not exist in " + packageName);
11809                    }
11810                }
11811                switch (newState) {
11812                case COMPONENT_ENABLED_STATE_ENABLED:
11813                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11814                        return;
11815                    }
11816                    break;
11817                case COMPONENT_ENABLED_STATE_DISABLED:
11818                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11819                        return;
11820                    }
11821                    break;
11822                case COMPONENT_ENABLED_STATE_DEFAULT:
11823                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11824                        return;
11825                    }
11826                    break;
11827                default:
11828                    Slog.e(TAG, "Invalid new component state: " + newState);
11829                    return;
11830                }
11831            }
11832            mSettings.writePackageRestrictionsLPr(userId);
11833            components = mPendingBroadcasts.get(userId, packageName);
11834            final boolean newPackage = components == null;
11835            if (newPackage) {
11836                components = new ArrayList<String>();
11837            }
11838            if (!components.contains(componentName)) {
11839                components.add(componentName);
11840            }
11841            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11842                sendNow = true;
11843                // Purge entry from pending broadcast list if another one exists already
11844                // since we are sending one right away.
11845                mPendingBroadcasts.remove(userId, packageName);
11846            } else {
11847                if (newPackage) {
11848                    mPendingBroadcasts.put(userId, packageName, components);
11849                }
11850                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11851                    // Schedule a message
11852                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11853                }
11854            }
11855        }
11856
11857        long callingId = Binder.clearCallingIdentity();
11858        try {
11859            if (sendNow) {
11860                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11861                sendPackageChangedBroadcast(packageName,
11862                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11863            }
11864        } finally {
11865            Binder.restoreCallingIdentity(callingId);
11866        }
11867    }
11868
11869    private void sendPackageChangedBroadcast(String packageName,
11870            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11871        if (DEBUG_INSTALL)
11872            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11873                    + componentNames);
11874        Bundle extras = new Bundle(4);
11875        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11876        String nameList[] = new String[componentNames.size()];
11877        componentNames.toArray(nameList);
11878        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11879        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11880        extras.putInt(Intent.EXTRA_UID, packageUid);
11881        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11882                new int[] {UserHandle.getUserId(packageUid)});
11883    }
11884
11885    @Override
11886    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11887        if (!sUserManager.exists(userId)) return;
11888        final int uid = Binder.getCallingUid();
11889        final int permission = mContext.checkCallingOrSelfPermission(
11890                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11891        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11892        enforceCrossUserPermission(uid, userId, true, true, "stop package");
11893        // writer
11894        synchronized (mPackages) {
11895            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11896                    uid, userId)) {
11897                scheduleWritePackageRestrictionsLocked(userId);
11898            }
11899        }
11900    }
11901
11902    @Override
11903    public String getInstallerPackageName(String packageName) {
11904        // reader
11905        synchronized (mPackages) {
11906            return mSettings.getInstallerPackageNameLPr(packageName);
11907        }
11908    }
11909
11910    @Override
11911    public int getApplicationEnabledSetting(String packageName, int userId) {
11912        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11913        int uid = Binder.getCallingUid();
11914        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
11915        // reader
11916        synchronized (mPackages) {
11917            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11918        }
11919    }
11920
11921    @Override
11922    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11923        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11924        int uid = Binder.getCallingUid();
11925        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
11926        // reader
11927        synchronized (mPackages) {
11928            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11929        }
11930    }
11931
11932    @Override
11933    public void enterSafeMode() {
11934        enforceSystemOrRoot("Only the system can request entering safe mode");
11935
11936        if (!mSystemReady) {
11937            mSafeMode = true;
11938        }
11939    }
11940
11941    @Override
11942    public void systemReady() {
11943        mSystemReady = true;
11944
11945        // Read the compatibilty setting when the system is ready.
11946        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11947                mContext.getContentResolver(),
11948                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11949        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11950        if (DEBUG_SETTINGS) {
11951            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11952        }
11953
11954        synchronized (mPackages) {
11955            // Verify that all of the preferred activity components actually
11956            // exist.  It is possible for applications to be updated and at
11957            // that point remove a previously declared activity component that
11958            // had been set as a preferred activity.  We try to clean this up
11959            // the next time we encounter that preferred activity, but it is
11960            // possible for the user flow to never be able to return to that
11961            // situation so here we do a sanity check to make sure we haven't
11962            // left any junk around.
11963            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11964            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11965                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11966                removed.clear();
11967                for (PreferredActivity pa : pir.filterSet()) {
11968                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11969                        removed.add(pa);
11970                    }
11971                }
11972                if (removed.size() > 0) {
11973                    for (int r=0; r<removed.size(); r++) {
11974                        PreferredActivity pa = removed.get(r);
11975                        Slog.w(TAG, "Removing dangling preferred activity: "
11976                                + pa.mPref.mComponent);
11977                        pir.removeFilter(pa);
11978                    }
11979                    mSettings.writePackageRestrictionsLPr(
11980                            mSettings.mPreferredActivities.keyAt(i));
11981                }
11982            }
11983        }
11984        sUserManager.systemReady();
11985
11986        // Kick off any messages waiting for system ready
11987        if (mPostSystemReadyMessages != null) {
11988            for (Message msg : mPostSystemReadyMessages) {
11989                msg.sendToTarget();
11990            }
11991            mPostSystemReadyMessages = null;
11992        }
11993    }
11994
11995    @Override
11996    public boolean isSafeMode() {
11997        return mSafeMode;
11998    }
11999
12000    @Override
12001    public boolean hasSystemUidErrors() {
12002        return mHasSystemUidErrors;
12003    }
12004
12005    static String arrayToString(int[] array) {
12006        StringBuffer buf = new StringBuffer(128);
12007        buf.append('[');
12008        if (array != null) {
12009            for (int i=0; i<array.length; i++) {
12010                if (i > 0) buf.append(", ");
12011                buf.append(array[i]);
12012            }
12013        }
12014        buf.append(']');
12015        return buf.toString();
12016    }
12017
12018    static class DumpState {
12019        public static final int DUMP_LIBS = 1 << 0;
12020        public static final int DUMP_FEATURES = 1 << 1;
12021        public static final int DUMP_RESOLVERS = 1 << 2;
12022        public static final int DUMP_PERMISSIONS = 1 << 3;
12023        public static final int DUMP_PACKAGES = 1 << 4;
12024        public static final int DUMP_SHARED_USERS = 1 << 5;
12025        public static final int DUMP_MESSAGES = 1 << 6;
12026        public static final int DUMP_PROVIDERS = 1 << 7;
12027        public static final int DUMP_VERIFIERS = 1 << 8;
12028        public static final int DUMP_PREFERRED = 1 << 9;
12029        public static final int DUMP_PREFERRED_XML = 1 << 10;
12030        public static final int DUMP_KEYSETS = 1 << 11;
12031        public static final int DUMP_VERSION = 1 << 12;
12032        public static final int DUMP_INSTALLS = 1 << 13;
12033
12034        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12035
12036        private int mTypes;
12037
12038        private int mOptions;
12039
12040        private boolean mTitlePrinted;
12041
12042        private SharedUserSetting mSharedUser;
12043
12044        public boolean isDumping(int type) {
12045            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12046                return true;
12047            }
12048
12049            return (mTypes & type) != 0;
12050        }
12051
12052        public void setDump(int type) {
12053            mTypes |= type;
12054        }
12055
12056        public boolean isOptionEnabled(int option) {
12057            return (mOptions & option) != 0;
12058        }
12059
12060        public void setOptionEnabled(int option) {
12061            mOptions |= option;
12062        }
12063
12064        public boolean onTitlePrinted() {
12065            final boolean printed = mTitlePrinted;
12066            mTitlePrinted = true;
12067            return printed;
12068        }
12069
12070        public boolean getTitlePrinted() {
12071            return mTitlePrinted;
12072        }
12073
12074        public void setTitlePrinted(boolean enabled) {
12075            mTitlePrinted = enabled;
12076        }
12077
12078        public SharedUserSetting getSharedUser() {
12079            return mSharedUser;
12080        }
12081
12082        public void setSharedUser(SharedUserSetting user) {
12083            mSharedUser = user;
12084        }
12085    }
12086
12087    @Override
12088    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12089        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12090                != PackageManager.PERMISSION_GRANTED) {
12091            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12092                    + Binder.getCallingPid()
12093                    + ", uid=" + Binder.getCallingUid()
12094                    + " without permission "
12095                    + android.Manifest.permission.DUMP);
12096            return;
12097        }
12098
12099        DumpState dumpState = new DumpState();
12100        boolean fullPreferred = false;
12101        boolean checkin = false;
12102
12103        String packageName = null;
12104
12105        int opti = 0;
12106        while (opti < args.length) {
12107            String opt = args[opti];
12108            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12109                break;
12110            }
12111            opti++;
12112            if ("-a".equals(opt)) {
12113                // Right now we only know how to print all.
12114            } else if ("-h".equals(opt)) {
12115                pw.println("Package manager dump options:");
12116                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12117                pw.println("    --checkin: dump for a checkin");
12118                pw.println("    -f: print details of intent filters");
12119                pw.println("    -h: print this help");
12120                pw.println("  cmd may be one of:");
12121                pw.println("    l[ibraries]: list known shared libraries");
12122                pw.println("    f[ibraries]: list device features");
12123                pw.println("    k[eysets]: print known keysets");
12124                pw.println("    r[esolvers]: dump intent resolvers");
12125                pw.println("    perm[issions]: dump permissions");
12126                pw.println("    pref[erred]: print preferred package settings");
12127                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12128                pw.println("    prov[iders]: dump content providers");
12129                pw.println("    p[ackages]: dump installed packages");
12130                pw.println("    s[hared-users]: dump shared user IDs");
12131                pw.println("    m[essages]: print collected runtime messages");
12132                pw.println("    v[erifiers]: print package verifier info");
12133                pw.println("    version: print database version info");
12134                pw.println("    write: write current settings now");
12135                pw.println("    <package.name>: info about given package");
12136                pw.println("    installs: details about install sessions");
12137                return;
12138            } else if ("--checkin".equals(opt)) {
12139                checkin = true;
12140            } else if ("-f".equals(opt)) {
12141                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12142            } else {
12143                pw.println("Unknown argument: " + opt + "; use -h for help");
12144            }
12145        }
12146
12147        // Is the caller requesting to dump a particular piece of data?
12148        if (opti < args.length) {
12149            String cmd = args[opti];
12150            opti++;
12151            // Is this a package name?
12152            if ("android".equals(cmd) || cmd.contains(".")) {
12153                packageName = cmd;
12154                // When dumping a single package, we always dump all of its
12155                // filter information since the amount of data will be reasonable.
12156                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12157            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12158                dumpState.setDump(DumpState.DUMP_LIBS);
12159            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12160                dumpState.setDump(DumpState.DUMP_FEATURES);
12161            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12162                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12163            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12164                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12165            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12166                dumpState.setDump(DumpState.DUMP_PREFERRED);
12167            } else if ("preferred-xml".equals(cmd)) {
12168                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12169                if (opti < args.length && "--full".equals(args[opti])) {
12170                    fullPreferred = true;
12171                    opti++;
12172                }
12173            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12174                dumpState.setDump(DumpState.DUMP_PACKAGES);
12175            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12176                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12177            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12178                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12179            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12180                dumpState.setDump(DumpState.DUMP_MESSAGES);
12181            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12182                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12183            } else if ("version".equals(cmd)) {
12184                dumpState.setDump(DumpState.DUMP_VERSION);
12185            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12186                dumpState.setDump(DumpState.DUMP_KEYSETS);
12187            } else if ("installs".equals(cmd)) {
12188                dumpState.setDump(DumpState.DUMP_INSTALLS);
12189            } else if ("write".equals(cmd)) {
12190                synchronized (mPackages) {
12191                    mSettings.writeLPr();
12192                    pw.println("Settings written.");
12193                    return;
12194                }
12195            }
12196        }
12197
12198        if (checkin) {
12199            pw.println("vers,1");
12200        }
12201
12202        // reader
12203        synchronized (mPackages) {
12204            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12205                if (!checkin) {
12206                    if (dumpState.onTitlePrinted())
12207                        pw.println();
12208                    pw.println("Database versions:");
12209                    pw.print("  SDK Version:");
12210                    pw.print(" internal=");
12211                    pw.print(mSettings.mInternalSdkPlatform);
12212                    pw.print(" external=");
12213                    pw.println(mSettings.mExternalSdkPlatform);
12214                    pw.print("  DB Version:");
12215                    pw.print(" internal=");
12216                    pw.print(mSettings.mInternalDatabaseVersion);
12217                    pw.print(" external=");
12218                    pw.println(mSettings.mExternalDatabaseVersion);
12219                }
12220            }
12221
12222            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12223                if (!checkin) {
12224                    if (dumpState.onTitlePrinted())
12225                        pw.println();
12226                    pw.println("Verifiers:");
12227                    pw.print("  Required: ");
12228                    pw.print(mRequiredVerifierPackage);
12229                    pw.print(" (uid=");
12230                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12231                    pw.println(")");
12232                } else if (mRequiredVerifierPackage != null) {
12233                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12234                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12235                }
12236            }
12237
12238            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12239                boolean printedHeader = false;
12240                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12241                while (it.hasNext()) {
12242                    String name = it.next();
12243                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12244                    if (!checkin) {
12245                        if (!printedHeader) {
12246                            if (dumpState.onTitlePrinted())
12247                                pw.println();
12248                            pw.println("Libraries:");
12249                            printedHeader = true;
12250                        }
12251                        pw.print("  ");
12252                    } else {
12253                        pw.print("lib,");
12254                    }
12255                    pw.print(name);
12256                    if (!checkin) {
12257                        pw.print(" -> ");
12258                    }
12259                    if (ent.path != null) {
12260                        if (!checkin) {
12261                            pw.print("(jar) ");
12262                            pw.print(ent.path);
12263                        } else {
12264                            pw.print(",jar,");
12265                            pw.print(ent.path);
12266                        }
12267                    } else {
12268                        if (!checkin) {
12269                            pw.print("(apk) ");
12270                            pw.print(ent.apk);
12271                        } else {
12272                            pw.print(",apk,");
12273                            pw.print(ent.apk);
12274                        }
12275                    }
12276                    pw.println();
12277                }
12278            }
12279
12280            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12281                if (dumpState.onTitlePrinted())
12282                    pw.println();
12283                if (!checkin) {
12284                    pw.println("Features:");
12285                }
12286                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12287                while (it.hasNext()) {
12288                    String name = it.next();
12289                    if (!checkin) {
12290                        pw.print("  ");
12291                    } else {
12292                        pw.print("feat,");
12293                    }
12294                    pw.println(name);
12295                }
12296            }
12297
12298            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12299                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12300                        : "Activity Resolver Table:", "  ", packageName,
12301                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12302                    dumpState.setTitlePrinted(true);
12303                }
12304                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12305                        : "Receiver Resolver Table:", "  ", packageName,
12306                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12307                    dumpState.setTitlePrinted(true);
12308                }
12309                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12310                        : "Service Resolver Table:", "  ", packageName,
12311                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12312                    dumpState.setTitlePrinted(true);
12313                }
12314                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12315                        : "Provider Resolver Table:", "  ", packageName,
12316                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12317                    dumpState.setTitlePrinted(true);
12318                }
12319            }
12320
12321            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12322                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12323                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12324                    int user = mSettings.mPreferredActivities.keyAt(i);
12325                    if (pir.dump(pw,
12326                            dumpState.getTitlePrinted()
12327                                ? "\nPreferred Activities User " + user + ":"
12328                                : "Preferred Activities User " + user + ":", "  ",
12329                            packageName, true)) {
12330                        dumpState.setTitlePrinted(true);
12331                    }
12332                }
12333            }
12334
12335            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12336                pw.flush();
12337                FileOutputStream fout = new FileOutputStream(fd);
12338                BufferedOutputStream str = new BufferedOutputStream(fout);
12339                XmlSerializer serializer = new FastXmlSerializer();
12340                try {
12341                    serializer.setOutput(str, "utf-8");
12342                    serializer.startDocument(null, true);
12343                    serializer.setFeature(
12344                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12345                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12346                    serializer.endDocument();
12347                    serializer.flush();
12348                } catch (IllegalArgumentException e) {
12349                    pw.println("Failed writing: " + e);
12350                } catch (IllegalStateException e) {
12351                    pw.println("Failed writing: " + e);
12352                } catch (IOException e) {
12353                    pw.println("Failed writing: " + e);
12354                }
12355            }
12356
12357            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12358                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12359                if (packageName == null) {
12360                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12361                        if (iperm == 0) {
12362                            if (dumpState.onTitlePrinted())
12363                                pw.println();
12364                            pw.println("AppOp Permissions:");
12365                        }
12366                        pw.print("  AppOp Permission ");
12367                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12368                        pw.println(":");
12369                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12370                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12371                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12372                        }
12373                    }
12374                }
12375            }
12376
12377            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12378                boolean printedSomething = false;
12379                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12380                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12381                        continue;
12382                    }
12383                    if (!printedSomething) {
12384                        if (dumpState.onTitlePrinted())
12385                            pw.println();
12386                        pw.println("Registered ContentProviders:");
12387                        printedSomething = true;
12388                    }
12389                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12390                    pw.print("    "); pw.println(p.toString());
12391                }
12392                printedSomething = false;
12393                for (Map.Entry<String, PackageParser.Provider> entry :
12394                        mProvidersByAuthority.entrySet()) {
12395                    PackageParser.Provider p = entry.getValue();
12396                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12397                        continue;
12398                    }
12399                    if (!printedSomething) {
12400                        if (dumpState.onTitlePrinted())
12401                            pw.println();
12402                        pw.println("ContentProvider Authorities:");
12403                        printedSomething = true;
12404                    }
12405                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12406                    pw.print("    "); pw.println(p.toString());
12407                    if (p.info != null && p.info.applicationInfo != null) {
12408                        final String appInfo = p.info.applicationInfo.toString();
12409                        pw.print("      applicationInfo="); pw.println(appInfo);
12410                    }
12411                }
12412            }
12413
12414            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12415                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12416            }
12417
12418            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12419                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12420            }
12421
12422            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12423                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12424            }
12425
12426            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12427                // XXX should handle packageName != null by dumping only install data that
12428                // the given package is involved with.
12429                if (dumpState.onTitlePrinted()) pw.println();
12430                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12431            }
12432
12433            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12434                if (dumpState.onTitlePrinted()) pw.println();
12435                mSettings.dumpReadMessagesLPr(pw, dumpState);
12436
12437                pw.println();
12438                pw.println("Package warning messages:");
12439                final File fname = getSettingsProblemFile();
12440                FileInputStream in = null;
12441                try {
12442                    in = new FileInputStream(fname);
12443                    final int avail = in.available();
12444                    final byte[] data = new byte[avail];
12445                    in.read(data);
12446                    pw.print(new String(data));
12447                } catch (FileNotFoundException e) {
12448                } catch (IOException e) {
12449                } finally {
12450                    if (in != null) {
12451                        try {
12452                            in.close();
12453                        } catch (IOException e) {
12454                        }
12455                    }
12456                }
12457            }
12458        }
12459    }
12460
12461    // ------- apps on sdcard specific code -------
12462    static final boolean DEBUG_SD_INSTALL = false;
12463
12464    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12465
12466    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12467
12468    private boolean mMediaMounted = false;
12469
12470    static String getEncryptKey() {
12471        try {
12472            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12473                    SD_ENCRYPTION_KEYSTORE_NAME);
12474            if (sdEncKey == null) {
12475                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12476                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12477                if (sdEncKey == null) {
12478                    Slog.e(TAG, "Failed to create encryption keys");
12479                    return null;
12480                }
12481            }
12482            return sdEncKey;
12483        } catch (NoSuchAlgorithmException nsae) {
12484            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12485            return null;
12486        } catch (IOException ioe) {
12487            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12488            return null;
12489        }
12490    }
12491
12492    /*
12493     * Update media status on PackageManager.
12494     */
12495    @Override
12496    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12497        int callingUid = Binder.getCallingUid();
12498        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12499            throw new SecurityException("Media status can only be updated by the system");
12500        }
12501        // reader; this apparently protects mMediaMounted, but should probably
12502        // be a different lock in that case.
12503        synchronized (mPackages) {
12504            Log.i(TAG, "Updating external media status from "
12505                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12506                    + (mediaStatus ? "mounted" : "unmounted"));
12507            if (DEBUG_SD_INSTALL)
12508                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12509                        + ", mMediaMounted=" + mMediaMounted);
12510            if (mediaStatus == mMediaMounted) {
12511                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12512                        : 0, -1);
12513                mHandler.sendMessage(msg);
12514                return;
12515            }
12516            mMediaMounted = mediaStatus;
12517        }
12518        // Queue up an async operation since the package installation may take a
12519        // little while.
12520        mHandler.post(new Runnable() {
12521            public void run() {
12522                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12523            }
12524        });
12525    }
12526
12527    /**
12528     * Called by MountService when the initial ASECs to scan are available.
12529     * Should block until all the ASEC containers are finished being scanned.
12530     */
12531    public void scanAvailableAsecs() {
12532        updateExternalMediaStatusInner(true, false, false);
12533        if (mShouldRestoreconData) {
12534            SELinuxMMAC.setRestoreconDone();
12535            mShouldRestoreconData = false;
12536        }
12537    }
12538
12539    /*
12540     * Collect information of applications on external media, map them against
12541     * existing containers and update information based on current mount status.
12542     * Please note that we always have to report status if reportStatus has been
12543     * set to true especially when unloading packages.
12544     */
12545    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12546            boolean externalStorage) {
12547        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12548        int[] uidArr = EmptyArray.INT;
12549
12550        final String[] list = PackageHelper.getSecureContainerList();
12551        if (ArrayUtils.isEmpty(list)) {
12552            Log.i(TAG, "No secure containers found");
12553        } else {
12554            // Process list of secure containers and categorize them
12555            // as active or stale based on their package internal state.
12556
12557            // reader
12558            synchronized (mPackages) {
12559                for (String cid : list) {
12560                    // Leave stages untouched for now; installer service owns them
12561                    if (PackageInstallerService.isStageName(cid)) continue;
12562
12563                    if (DEBUG_SD_INSTALL)
12564                        Log.i(TAG, "Processing container " + cid);
12565                    String pkgName = getAsecPackageName(cid);
12566                    if (pkgName == null) {
12567                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12568                        continue;
12569                    }
12570                    if (DEBUG_SD_INSTALL)
12571                        Log.i(TAG, "Looking for pkg : " + pkgName);
12572
12573                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12574                    if (ps == null) {
12575                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12576                        continue;
12577                    }
12578
12579                    /*
12580                     * Skip packages that are not external if we're unmounting
12581                     * external storage.
12582                     */
12583                    if (externalStorage && !isMounted && !isExternal(ps)) {
12584                        continue;
12585                    }
12586
12587                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12588                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12589                    // The package status is changed only if the code path
12590                    // matches between settings and the container id.
12591                    if (ps.codePathString != null
12592                            && ps.codePathString.startsWith(args.getCodePath())) {
12593                        if (DEBUG_SD_INSTALL) {
12594                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12595                                    + " at code path: " + ps.codePathString);
12596                        }
12597
12598                        // We do have a valid package installed on sdcard
12599                        processCids.put(args, ps.codePathString);
12600                        final int uid = ps.appId;
12601                        if (uid != -1) {
12602                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12603                        }
12604                    } else {
12605                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12606                                + ps.codePathString);
12607                    }
12608                }
12609            }
12610
12611            Arrays.sort(uidArr);
12612        }
12613
12614        // Process packages with valid entries.
12615        if (isMounted) {
12616            if (DEBUG_SD_INSTALL)
12617                Log.i(TAG, "Loading packages");
12618            loadMediaPackages(processCids, uidArr);
12619            startCleaningPackages();
12620            mInstallerService.onSecureContainersAvailable();
12621        } else {
12622            if (DEBUG_SD_INSTALL)
12623                Log.i(TAG, "Unloading packages");
12624            unloadMediaPackages(processCids, uidArr, reportStatus);
12625        }
12626    }
12627
12628    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12629            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12630        int size = pkgList.size();
12631        if (size > 0) {
12632            // Send broadcasts here
12633            Bundle extras = new Bundle();
12634            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12635                    .toArray(new String[size]));
12636            if (uidArr != null) {
12637                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12638            }
12639            if (replacing) {
12640                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12641            }
12642            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12643                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12644            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12645        }
12646    }
12647
12648   /*
12649     * Look at potentially valid container ids from processCids If package
12650     * information doesn't match the one on record or package scanning fails,
12651     * the cid is added to list of removeCids. We currently don't delete stale
12652     * containers.
12653     */
12654    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12655        ArrayList<String> pkgList = new ArrayList<String>();
12656        Set<AsecInstallArgs> keys = processCids.keySet();
12657
12658        for (AsecInstallArgs args : keys) {
12659            String codePath = processCids.get(args);
12660            if (DEBUG_SD_INSTALL)
12661                Log.i(TAG, "Loading container : " + args.cid);
12662            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12663            try {
12664                // Make sure there are no container errors first.
12665                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12666                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12667                            + " when installing from sdcard");
12668                    continue;
12669                }
12670                // Check code path here.
12671                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12672                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12673                            + " does not match one in settings " + codePath);
12674                    continue;
12675                }
12676                // Parse package
12677                int parseFlags = mDefParseFlags;
12678                if (args.isExternal()) {
12679                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12680                }
12681                if (args.isFwdLocked()) {
12682                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12683                }
12684
12685                synchronized (mInstallLock) {
12686                    PackageParser.Package pkg = null;
12687                    try {
12688                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12689                    } catch (PackageManagerException e) {
12690                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12691                    }
12692                    // Scan the package
12693                    if (pkg != null) {
12694                        /*
12695                         * TODO why is the lock being held? doPostInstall is
12696                         * called in other places without the lock. This needs
12697                         * to be straightened out.
12698                         */
12699                        // writer
12700                        synchronized (mPackages) {
12701                            retCode = PackageManager.INSTALL_SUCCEEDED;
12702                            pkgList.add(pkg.packageName);
12703                            // Post process args
12704                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12705                                    pkg.applicationInfo.uid);
12706                        }
12707                    } else {
12708                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12709                    }
12710                }
12711
12712            } finally {
12713                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12714                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12715                }
12716            }
12717        }
12718        // writer
12719        synchronized (mPackages) {
12720            // If the platform SDK has changed since the last time we booted,
12721            // we need to re-grant app permission to catch any new ones that
12722            // appear. This is really a hack, and means that apps can in some
12723            // cases get permissions that the user didn't initially explicitly
12724            // allow... it would be nice to have some better way to handle
12725            // this situation.
12726            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12727            if (regrantPermissions)
12728                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12729                        + mSdkVersion + "; regranting permissions for external storage");
12730            mSettings.mExternalSdkPlatform = mSdkVersion;
12731
12732            // Make sure group IDs have been assigned, and any permission
12733            // changes in other apps are accounted for
12734            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12735                    | (regrantPermissions
12736                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12737                            : 0));
12738
12739            mSettings.updateExternalDatabaseVersion();
12740
12741            // can downgrade to reader
12742            // Persist settings
12743            mSettings.writeLPr();
12744        }
12745        // Send a broadcast to let everyone know we are done processing
12746        if (pkgList.size() > 0) {
12747            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12748        }
12749    }
12750
12751   /*
12752     * Utility method to unload a list of specified containers
12753     */
12754    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12755        // Just unmount all valid containers.
12756        for (AsecInstallArgs arg : cidArgs) {
12757            synchronized (mInstallLock) {
12758                arg.doPostDeleteLI(false);
12759           }
12760       }
12761   }
12762
12763    /*
12764     * Unload packages mounted on external media. This involves deleting package
12765     * data from internal structures, sending broadcasts about diabled packages,
12766     * gc'ing to free up references, unmounting all secure containers
12767     * corresponding to packages on external media, and posting a
12768     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12769     * that we always have to post this message if status has been requested no
12770     * matter what.
12771     */
12772    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12773            final boolean reportStatus) {
12774        if (DEBUG_SD_INSTALL)
12775            Log.i(TAG, "unloading media packages");
12776        ArrayList<String> pkgList = new ArrayList<String>();
12777        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12778        final Set<AsecInstallArgs> keys = processCids.keySet();
12779        for (AsecInstallArgs args : keys) {
12780            String pkgName = args.getPackageName();
12781            if (DEBUG_SD_INSTALL)
12782                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12783            // Delete package internally
12784            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12785            synchronized (mInstallLock) {
12786                boolean res = deletePackageLI(pkgName, null, false, null, null,
12787                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12788                if (res) {
12789                    pkgList.add(pkgName);
12790                } else {
12791                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12792                    failedList.add(args);
12793                }
12794            }
12795        }
12796
12797        // reader
12798        synchronized (mPackages) {
12799            // We didn't update the settings after removing each package;
12800            // write them now for all packages.
12801            mSettings.writeLPr();
12802        }
12803
12804        // We have to absolutely send UPDATED_MEDIA_STATUS only
12805        // after confirming that all the receivers processed the ordered
12806        // broadcast when packages get disabled, force a gc to clean things up.
12807        // and unload all the containers.
12808        if (pkgList.size() > 0) {
12809            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12810                    new IIntentReceiver.Stub() {
12811                public void performReceive(Intent intent, int resultCode, String data,
12812                        Bundle extras, boolean ordered, boolean sticky,
12813                        int sendingUser) throws RemoteException {
12814                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12815                            reportStatus ? 1 : 0, 1, keys);
12816                    mHandler.sendMessage(msg);
12817                }
12818            });
12819        } else {
12820            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12821                    keys);
12822            mHandler.sendMessage(msg);
12823        }
12824    }
12825
12826    /** Binder call */
12827    @Override
12828    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12829            final int flags) {
12830        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12831        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12832        int returnCode = PackageManager.MOVE_SUCCEEDED;
12833        int currInstallFlags = 0;
12834        int newInstallFlags = 0;
12835
12836        File codeFile = null;
12837        String installerPackageName = null;
12838        String packageAbiOverride = null;
12839
12840        // reader
12841        synchronized (mPackages) {
12842            final PackageParser.Package pkg = mPackages.get(packageName);
12843            final PackageSetting ps = mSettings.mPackages.get(packageName);
12844            if (pkg == null || ps == null) {
12845                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12846            } else {
12847                // Disable moving fwd locked apps and system packages
12848                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12849                    Slog.w(TAG, "Cannot move system application");
12850                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12851                } else if (pkg.mOperationPending) {
12852                    Slog.w(TAG, "Attempt to move package which has pending operations");
12853                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12854                } else {
12855                    // Find install location first
12856                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12857                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12858                        Slog.w(TAG, "Ambigous flags specified for move location.");
12859                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12860                    } else {
12861                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12862                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12863                        currInstallFlags = isExternal(pkg)
12864                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12865
12866                        if (newInstallFlags == currInstallFlags) {
12867                            Slog.w(TAG, "No move required. Trying to move to same location");
12868                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12869                        } else {
12870                            if (isForwardLocked(pkg)) {
12871                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12872                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12873                            }
12874                        }
12875                    }
12876                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12877                        pkg.mOperationPending = true;
12878                    }
12879                }
12880
12881                codeFile = new File(pkg.codePath);
12882                installerPackageName = ps.installerPackageName;
12883                packageAbiOverride = ps.cpuAbiOverrideString;
12884            }
12885        }
12886
12887        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12888            try {
12889                observer.packageMoved(packageName, returnCode);
12890            } catch (RemoteException ignored) {
12891            }
12892            return;
12893        }
12894
12895        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
12896            @Override
12897            public void onUserActionRequired(Intent intent) throws RemoteException {
12898                throw new IllegalStateException();
12899            }
12900
12901            @Override
12902            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
12903                    Bundle extras) throws RemoteException {
12904                Slog.d(TAG, "Install result for move: "
12905                        + PackageManager.installStatusToString(returnCode, msg));
12906
12907                // We usually have a new package now after the install, but if
12908                // we failed we need to clear the pending flag on the original
12909                // package object.
12910                synchronized (mPackages) {
12911                    final PackageParser.Package pkg = mPackages.get(packageName);
12912                    if (pkg != null) {
12913                        pkg.mOperationPending = false;
12914                    }
12915                }
12916
12917                final int status = PackageManager.installStatusToPublicStatus(returnCode);
12918                switch (status) {
12919                    case PackageInstaller.STATUS_SUCCESS:
12920                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
12921                        break;
12922                    case PackageInstaller.STATUS_FAILURE_STORAGE:
12923                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
12924                        break;
12925                    default:
12926                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
12927                        break;
12928                }
12929            }
12930        };
12931
12932        // Treat a move like reinstalling an existing app, which ensures that we
12933        // process everythign uniformly, like unpacking native libraries.
12934        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
12935
12936        final Message msg = mHandler.obtainMessage(INIT_COPY);
12937        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
12938        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
12939                installerPackageName, null, user, packageAbiOverride);
12940        mHandler.sendMessage(msg);
12941    }
12942
12943    @Override
12944    public boolean setInstallLocation(int loc) {
12945        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12946                null);
12947        if (getInstallLocation() == loc) {
12948            return true;
12949        }
12950        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12951                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12952            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12953                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12954            return true;
12955        }
12956        return false;
12957   }
12958
12959    @Override
12960    public int getInstallLocation() {
12961        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12962                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12963                PackageHelper.APP_INSTALL_AUTO);
12964    }
12965
12966    /** Called by UserManagerService */
12967    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
12968        mDirtyUsers.remove(userHandle);
12969        mSettings.removeUserLPw(userHandle);
12970        mPendingBroadcasts.remove(userHandle);
12971        if (mInstaller != null) {
12972            // Technically, we shouldn't be doing this with the package lock
12973            // held.  However, this is very rare, and there is already so much
12974            // other disk I/O going on, that we'll let it slide for now.
12975            mInstaller.removeUserDataDirs(userHandle);
12976        }
12977        mUserNeedsBadging.delete(userHandle);
12978        removeUnusedPackagesLILPw(userManager, userHandle);
12979    }
12980
12981    /**
12982     * We're removing userHandle and would like to remove any downloaded packages
12983     * that are no longer in use by any other user.
12984     * @param userHandle the user being removed
12985     */
12986    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
12987        final boolean DEBUG_CLEAN_APKS = false;
12988        int [] users = userManager.getUserIdsLPr();
12989        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
12990        while (psit.hasNext()) {
12991            PackageSetting ps = psit.next();
12992            if (ps.pkg == null) {
12993                continue;
12994            }
12995            final String packageName = ps.pkg.packageName;
12996            // Skip over if system app
12997            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12998                continue;
12999            }
13000            if (DEBUG_CLEAN_APKS) {
13001                Slog.i(TAG, "Checking package " + packageName);
13002            }
13003            boolean keep = false;
13004            for (int i = 0; i < users.length; i++) {
13005                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13006                    keep = true;
13007                    if (DEBUG_CLEAN_APKS) {
13008                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13009                                + users[i]);
13010                    }
13011                    break;
13012                }
13013            }
13014            if (!keep) {
13015                if (DEBUG_CLEAN_APKS) {
13016                    Slog.i(TAG, "  Removing package " + packageName);
13017                }
13018                mHandler.post(new Runnable() {
13019                    public void run() {
13020                        deletePackageX(packageName, userHandle, 0);
13021                    } //end run
13022                });
13023            }
13024        }
13025    }
13026
13027    /** Called by UserManagerService */
13028    void createNewUserLILPw(int userHandle, File path) {
13029        if (mInstaller != null) {
13030            mInstaller.createUserConfig(userHandle);
13031            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13032        }
13033    }
13034
13035    @Override
13036    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13037        mContext.enforceCallingOrSelfPermission(
13038                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13039                "Only package verification agents can read the verifier device identity");
13040
13041        synchronized (mPackages) {
13042            return mSettings.getVerifierDeviceIdentityLPw();
13043        }
13044    }
13045
13046    @Override
13047    public void setPermissionEnforced(String permission, boolean enforced) {
13048        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13049        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13050            synchronized (mPackages) {
13051                if (mSettings.mReadExternalStorageEnforced == null
13052                        || mSettings.mReadExternalStorageEnforced != enforced) {
13053                    mSettings.mReadExternalStorageEnforced = enforced;
13054                    mSettings.writeLPr();
13055                }
13056            }
13057            // kill any non-foreground processes so we restart them and
13058            // grant/revoke the GID.
13059            final IActivityManager am = ActivityManagerNative.getDefault();
13060            if (am != null) {
13061                final long token = Binder.clearCallingIdentity();
13062                try {
13063                    am.killProcessesBelowForeground("setPermissionEnforcement");
13064                } catch (RemoteException e) {
13065                } finally {
13066                    Binder.restoreCallingIdentity(token);
13067                }
13068            }
13069        } else {
13070            throw new IllegalArgumentException("No selective enforcement for " + permission);
13071        }
13072    }
13073
13074    @Override
13075    @Deprecated
13076    public boolean isPermissionEnforced(String permission) {
13077        return true;
13078    }
13079
13080    @Override
13081    public boolean isStorageLow() {
13082        final long token = Binder.clearCallingIdentity();
13083        try {
13084            final DeviceStorageMonitorInternal
13085                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13086            if (dsm != null) {
13087                return dsm.isMemoryLow();
13088            } else {
13089                return false;
13090            }
13091        } finally {
13092            Binder.restoreCallingIdentity(token);
13093        }
13094    }
13095
13096    @Override
13097    public IPackageInstaller getPackageInstaller() {
13098        return mInstallerService;
13099    }
13100
13101    private boolean userNeedsBadging(int userId) {
13102        int index = mUserNeedsBadging.indexOfKey(userId);
13103        if (index < 0) {
13104            final UserInfo userInfo;
13105            final long token = Binder.clearCallingIdentity();
13106            try {
13107                userInfo = sUserManager.getUserInfo(userId);
13108            } finally {
13109                Binder.restoreCallingIdentity(token);
13110            }
13111            final boolean b;
13112            if (userInfo != null && userInfo.isManagedProfile()) {
13113                b = true;
13114            } else {
13115                b = false;
13116            }
13117            mUserNeedsBadging.put(userId, b);
13118            return b;
13119        }
13120        return mUserNeedsBadging.valueAt(index);
13121    }
13122
13123    @Override
13124    public KeySet getKeySetByAlias(String packageName, String alias) {
13125        if (packageName == null || alias == null) {
13126            return null;
13127        }
13128        synchronized(mPackages) {
13129            final PackageParser.Package pkg = mPackages.get(packageName);
13130            if (pkg == null) {
13131                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13132                throw new IllegalArgumentException("Unknown package: " + packageName);
13133            }
13134            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13135            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13136        }
13137    }
13138
13139    @Override
13140    public KeySet getSigningKeySet(String packageName) {
13141        if (packageName == null) {
13142            return null;
13143        }
13144        synchronized(mPackages) {
13145            final PackageParser.Package pkg = mPackages.get(packageName);
13146            if (pkg == null) {
13147                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13148                throw new IllegalArgumentException("Unknown package: " + packageName);
13149            }
13150            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13151                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13152                throw new SecurityException("May not access signing KeySet of other apps.");
13153            }
13154            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13155            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13156        }
13157    }
13158
13159    @Override
13160    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13161        if (packageName == null || ks == null) {
13162            return false;
13163        }
13164        synchronized(mPackages) {
13165            final PackageParser.Package pkg = mPackages.get(packageName);
13166            if (pkg == null) {
13167                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13168                throw new IllegalArgumentException("Unknown package: " + packageName);
13169            }
13170            IBinder ksh = ks.getToken();
13171            if (ksh instanceof KeySetHandle) {
13172                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13173                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13174            }
13175            return false;
13176        }
13177    }
13178
13179    @Override
13180    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13181        if (packageName == null || ks == null) {
13182            return false;
13183        }
13184        synchronized(mPackages) {
13185            final PackageParser.Package pkg = mPackages.get(packageName);
13186            if (pkg == null) {
13187                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13188                throw new IllegalArgumentException("Unknown package: " + packageName);
13189            }
13190            IBinder ksh = ks.getToken();
13191            if (ksh instanceof KeySetHandle) {
13192                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13193                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13194            }
13195            return false;
13196        }
13197    }
13198}
13199