PackageManagerService.java revision d594197868c4a51bb8f8bd62479999debc72bf2a
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 String[] getAppOpPermissionPackages(String permissionName) {
2884        synchronized (mPackages) {
2885            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2886            if (pkgs == null) {
2887                return null;
2888            }
2889            return pkgs.toArray(new String[pkgs.size()]);
2890        }
2891    }
2892
2893    @Override
2894    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2895            int flags, int userId) {
2896        if (!sUserManager.exists(userId)) return null;
2897        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
2898        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2899        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2900    }
2901
2902    @Override
2903    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2904            IntentFilter filter, int match, ComponentName activity) {
2905        final int userId = UserHandle.getCallingUserId();
2906        if (DEBUG_PREFERRED) {
2907            Log.v(TAG, "setLastChosenActivity intent=" + intent
2908                + " resolvedType=" + resolvedType
2909                + " flags=" + flags
2910                + " filter=" + filter
2911                + " match=" + match
2912                + " activity=" + activity);
2913            filter.dump(new PrintStreamPrinter(System.out), "    ");
2914        }
2915        intent.setComponent(null);
2916        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2917        // Find any earlier preferred or last chosen entries and nuke them
2918        findPreferredActivity(intent, resolvedType,
2919                flags, query, 0, false, true, false, userId);
2920        // Add the new activity as the last chosen for this filter
2921        addPreferredActivityInternal(filter, match, null, activity, false, userId,
2922                "Setting last chosen");
2923    }
2924
2925    @Override
2926    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
2927        final int userId = UserHandle.getCallingUserId();
2928        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
2929        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2930        return findPreferredActivity(intent, resolvedType, flags, query, 0,
2931                false, false, false, userId);
2932    }
2933
2934    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
2935            int flags, List<ResolveInfo> query, int userId) {
2936        if (query != null) {
2937            final int N = query.size();
2938            if (N == 1) {
2939                return query.get(0);
2940            } else if (N > 1) {
2941                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
2942                // If there is more than one activity with the same priority,
2943                // then let the user decide between them.
2944                ResolveInfo r0 = query.get(0);
2945                ResolveInfo r1 = query.get(1);
2946                if (DEBUG_INTENT_MATCHING || debug) {
2947                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
2948                            + r1.activityInfo.name + "=" + r1.priority);
2949                }
2950                // If the first activity has a higher priority, or a different
2951                // default, then it is always desireable to pick it.
2952                if (r0.priority != r1.priority
2953                        || r0.preferredOrder != r1.preferredOrder
2954                        || r0.isDefault != r1.isDefault) {
2955                    return query.get(0);
2956                }
2957                // If we have saved a preference for a preferred activity for
2958                // this Intent, use that.
2959                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
2960                        flags, query, r0.priority, true, false, debug, userId);
2961                if (ri != null) {
2962                    return ri;
2963                }
2964                if (userId != 0) {
2965                    ri = new ResolveInfo(mResolveInfo);
2966                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
2967                    ri.activityInfo.applicationInfo = new ApplicationInfo(
2968                            ri.activityInfo.applicationInfo);
2969                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
2970                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
2971                    return ri;
2972                }
2973                return mResolveInfo;
2974            }
2975        }
2976        return null;
2977    }
2978
2979    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
2980            int flags, List<ResolveInfo> query, boolean debug, int userId) {
2981        final int N = query.size();
2982        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
2983                .get(userId);
2984        // Get the list of persistent preferred activities that handle the intent
2985        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
2986        List<PersistentPreferredActivity> pprefs = ppir != null
2987                ? ppir.queryIntent(intent, resolvedType,
2988                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
2989                : null;
2990        if (pprefs != null && pprefs.size() > 0) {
2991            final int M = pprefs.size();
2992            for (int i=0; i<M; i++) {
2993                final PersistentPreferredActivity ppa = pprefs.get(i);
2994                if (DEBUG_PREFERRED || debug) {
2995                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
2996                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
2997                            + "\n  component=" + ppa.mComponent);
2998                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
2999                }
3000                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3001                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3002                if (DEBUG_PREFERRED || debug) {
3003                    Slog.v(TAG, "Found persistent preferred activity:");
3004                    if (ai != null) {
3005                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3006                    } else {
3007                        Slog.v(TAG, "  null");
3008                    }
3009                }
3010                if (ai == null) {
3011                    // This previously registered persistent preferred activity
3012                    // component is no longer known. Ignore it and do NOT remove it.
3013                    continue;
3014                }
3015                for (int j=0; j<N; j++) {
3016                    final ResolveInfo ri = query.get(j);
3017                    if (!ri.activityInfo.applicationInfo.packageName
3018                            .equals(ai.applicationInfo.packageName)) {
3019                        continue;
3020                    }
3021                    if (!ri.activityInfo.name.equals(ai.name)) {
3022                        continue;
3023                    }
3024                    //  Found a persistent preference that can handle the intent.
3025                    if (DEBUG_PREFERRED || debug) {
3026                        Slog.v(TAG, "Returning persistent preferred activity: " +
3027                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3028                    }
3029                    return ri;
3030                }
3031            }
3032        }
3033        return null;
3034    }
3035
3036    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3037            List<ResolveInfo> query, int priority, boolean always,
3038            boolean removeMatches, boolean debug, int userId) {
3039        if (!sUserManager.exists(userId)) return null;
3040        // writer
3041        synchronized (mPackages) {
3042            if (intent.getSelector() != null) {
3043                intent = intent.getSelector();
3044            }
3045            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3046
3047            // Try to find a matching persistent preferred activity.
3048            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3049                    debug, userId);
3050
3051            // If a persistent preferred activity matched, use it.
3052            if (pri != null) {
3053                return pri;
3054            }
3055
3056            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3057            // Get the list of preferred activities that handle the intent
3058            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3059            List<PreferredActivity> prefs = pir != null
3060                    ? pir.queryIntent(intent, resolvedType,
3061                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3062                    : null;
3063            if (prefs != null && prefs.size() > 0) {
3064                boolean changed = false;
3065                try {
3066                    // First figure out how good the original match set is.
3067                    // We will only allow preferred activities that came
3068                    // from the same match quality.
3069                    int match = 0;
3070
3071                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3072
3073                    final int N = query.size();
3074                    for (int j=0; j<N; j++) {
3075                        final ResolveInfo ri = query.get(j);
3076                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3077                                + ": 0x" + Integer.toHexString(match));
3078                        if (ri.match > match) {
3079                            match = ri.match;
3080                        }
3081                    }
3082
3083                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3084                            + Integer.toHexString(match));
3085
3086                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3087                    final int M = prefs.size();
3088                    for (int i=0; i<M; i++) {
3089                        final PreferredActivity pa = prefs.get(i);
3090                        if (DEBUG_PREFERRED || debug) {
3091                            Slog.v(TAG, "Checking PreferredActivity ds="
3092                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3093                                    + "\n  component=" + pa.mPref.mComponent);
3094                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3095                        }
3096                        if (pa.mPref.mMatch != match) {
3097                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3098                                    + Integer.toHexString(pa.mPref.mMatch));
3099                            continue;
3100                        }
3101                        // If it's not an "always" type preferred activity and that's what we're
3102                        // looking for, skip it.
3103                        if (always && !pa.mPref.mAlways) {
3104                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3105                            continue;
3106                        }
3107                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3108                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3109                        if (DEBUG_PREFERRED || debug) {
3110                            Slog.v(TAG, "Found preferred activity:");
3111                            if (ai != null) {
3112                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3113                            } else {
3114                                Slog.v(TAG, "  null");
3115                            }
3116                        }
3117                        if (ai == null) {
3118                            // This previously registered preferred activity
3119                            // component is no longer known.  Most likely an update
3120                            // to the app was installed and in the new version this
3121                            // component no longer exists.  Clean it up by removing
3122                            // it from the preferred activities list, and skip it.
3123                            Slog.w(TAG, "Removing dangling preferred activity: "
3124                                    + pa.mPref.mComponent);
3125                            pir.removeFilter(pa);
3126                            changed = true;
3127                            continue;
3128                        }
3129                        for (int j=0; j<N; j++) {
3130                            final ResolveInfo ri = query.get(j);
3131                            if (!ri.activityInfo.applicationInfo.packageName
3132                                    .equals(ai.applicationInfo.packageName)) {
3133                                continue;
3134                            }
3135                            if (!ri.activityInfo.name.equals(ai.name)) {
3136                                continue;
3137                            }
3138
3139                            if (removeMatches) {
3140                                pir.removeFilter(pa);
3141                                changed = true;
3142                                if (DEBUG_PREFERRED) {
3143                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3144                                }
3145                                break;
3146                            }
3147
3148                            // Okay we found a previously set preferred or last chosen app.
3149                            // If the result set is different from when this
3150                            // was created, we need to clear it and re-ask the
3151                            // user their preference, if we're looking for an "always" type entry.
3152                            if (always && !pa.mPref.sameSet(query, priority)) {
3153                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3154                                        + intent + " type " + resolvedType);
3155                                if (DEBUG_PREFERRED) {
3156                                    Slog.v(TAG, "Removing preferred activity since set changed "
3157                                            + pa.mPref.mComponent);
3158                                }
3159                                pir.removeFilter(pa);
3160                                // Re-add the filter as a "last chosen" entry (!always)
3161                                PreferredActivity lastChosen = new PreferredActivity(
3162                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3163                                pir.addFilter(lastChosen);
3164                                changed = true;
3165                                return null;
3166                            }
3167
3168                            // Yay! Either the set matched or we're looking for the last chosen
3169                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3170                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3171                            return ri;
3172                        }
3173                    }
3174                } finally {
3175                    if (changed) {
3176                        if (DEBUG_PREFERRED) {
3177                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3178                        }
3179                        mSettings.writePackageRestrictionsLPr(userId);
3180                    }
3181                }
3182            }
3183        }
3184        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3185        return null;
3186    }
3187
3188    /*
3189     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3190     */
3191    @Override
3192    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3193            int targetUserId) {
3194        mContext.enforceCallingOrSelfPermission(
3195                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3196        List<CrossProfileIntentFilter> matches =
3197                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3198        if (matches != null) {
3199            int size = matches.size();
3200            for (int i = 0; i < size; i++) {
3201                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3202            }
3203        }
3204        return false;
3205    }
3206
3207    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3208            String resolvedType, int userId) {
3209        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3210        if (resolver != null) {
3211            return resolver.queryIntent(intent, resolvedType, false, userId);
3212        }
3213        return null;
3214    }
3215
3216    @Override
3217    public List<ResolveInfo> queryIntentActivities(Intent intent,
3218            String resolvedType, int flags, int userId) {
3219        if (!sUserManager.exists(userId)) return Collections.emptyList();
3220        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3221        ComponentName comp = intent.getComponent();
3222        if (comp == null) {
3223            if (intent.getSelector() != null) {
3224                intent = intent.getSelector();
3225                comp = intent.getComponent();
3226            }
3227        }
3228
3229        if (comp != null) {
3230            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3231            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3232            if (ai != null) {
3233                final ResolveInfo ri = new ResolveInfo();
3234                ri.activityInfo = ai;
3235                list.add(ri);
3236            }
3237            return list;
3238        }
3239
3240        // reader
3241        synchronized (mPackages) {
3242            final String pkgName = intent.getPackage();
3243            if (pkgName == null) {
3244                List<CrossProfileIntentFilter> matchingFilters =
3245                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3246                // Check for results that need to skip the current profile.
3247                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3248                        resolvedType, flags, userId);
3249                if (resolveInfo != null) {
3250                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3251                    result.add(resolveInfo);
3252                    return result;
3253                }
3254                // Check for cross profile results.
3255                resolveInfo = queryCrossProfileIntents(
3256                        matchingFilters, intent, resolvedType, flags, userId);
3257
3258                // Check for results in the current profile.
3259                List<ResolveInfo> result = mActivities.queryIntent(
3260                        intent, resolvedType, flags, userId);
3261                if (resolveInfo != null) {
3262                    result.add(resolveInfo);
3263                    Collections.sort(result, mResolvePrioritySorter);
3264                }
3265                return result;
3266            }
3267            final PackageParser.Package pkg = mPackages.get(pkgName);
3268            if (pkg != null) {
3269                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3270                        pkg.activities, userId);
3271            }
3272            return new ArrayList<ResolveInfo>();
3273        }
3274    }
3275
3276    private ResolveInfo querySkipCurrentProfileIntents(
3277            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3278            int flags, int sourceUserId) {
3279        if (matchingFilters != null) {
3280            int size = matchingFilters.size();
3281            for (int i = 0; i < size; i ++) {
3282                CrossProfileIntentFilter filter = matchingFilters.get(i);
3283                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3284                    // Checking if there are activities in the target user that can handle the
3285                    // intent.
3286                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3287                            flags, sourceUserId);
3288                    if (resolveInfo != null) {
3289                        return resolveInfo;
3290                    }
3291                }
3292            }
3293        }
3294        return null;
3295    }
3296
3297    // Return matching ResolveInfo if any for skip current profile intent filters.
3298    private ResolveInfo queryCrossProfileIntents(
3299            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3300            int flags, int sourceUserId) {
3301        if (matchingFilters != null) {
3302            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3303            // match the same intent. For performance reasons, it is better not to
3304            // run queryIntent twice for the same userId
3305            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3306            int size = matchingFilters.size();
3307            for (int i = 0; i < size; i++) {
3308                CrossProfileIntentFilter filter = matchingFilters.get(i);
3309                int targetUserId = filter.getTargetUserId();
3310                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3311                        && !alreadyTriedUserIds.get(targetUserId)) {
3312                    // Checking if there are activities in the target user that can handle the
3313                    // intent.
3314                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3315                            flags, sourceUserId);
3316                    if (resolveInfo != null) return resolveInfo;
3317                    alreadyTriedUserIds.put(targetUserId, true);
3318                }
3319            }
3320        }
3321        return null;
3322    }
3323
3324    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3325            String resolvedType, int flags, int sourceUserId) {
3326        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3327                resolvedType, flags, filter.getTargetUserId());
3328        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3329            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3330        }
3331        return null;
3332    }
3333
3334    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3335            int sourceUserId, int targetUserId) {
3336        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3337        String className;
3338        if (targetUserId == UserHandle.USER_OWNER) {
3339            className = FORWARD_INTENT_TO_USER_OWNER;
3340        } else {
3341            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3342        }
3343        ComponentName forwardingActivityComponentName = new ComponentName(
3344                mAndroidApplication.packageName, className);
3345        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3346                sourceUserId);
3347        if (targetUserId == UserHandle.USER_OWNER) {
3348            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3349            forwardingResolveInfo.noResourceId = true;
3350        }
3351        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3352        forwardingResolveInfo.priority = 0;
3353        forwardingResolveInfo.preferredOrder = 0;
3354        forwardingResolveInfo.match = 0;
3355        forwardingResolveInfo.isDefault = true;
3356        forwardingResolveInfo.filter = filter;
3357        forwardingResolveInfo.targetUserId = targetUserId;
3358        return forwardingResolveInfo;
3359    }
3360
3361    @Override
3362    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3363            Intent[] specifics, String[] specificTypes, Intent intent,
3364            String resolvedType, int flags, int userId) {
3365        if (!sUserManager.exists(userId)) return Collections.emptyList();
3366        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3367                false, "query intent activity options");
3368        final String resultsAction = intent.getAction();
3369
3370        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3371                | PackageManager.GET_RESOLVED_FILTER, userId);
3372
3373        if (DEBUG_INTENT_MATCHING) {
3374            Log.v(TAG, "Query " + intent + ": " + results);
3375        }
3376
3377        int specificsPos = 0;
3378        int N;
3379
3380        // todo: note that the algorithm used here is O(N^2).  This
3381        // isn't a problem in our current environment, but if we start running
3382        // into situations where we have more than 5 or 10 matches then this
3383        // should probably be changed to something smarter...
3384
3385        // First we go through and resolve each of the specific items
3386        // that were supplied, taking care of removing any corresponding
3387        // duplicate items in the generic resolve list.
3388        if (specifics != null) {
3389            for (int i=0; i<specifics.length; i++) {
3390                final Intent sintent = specifics[i];
3391                if (sintent == null) {
3392                    continue;
3393                }
3394
3395                if (DEBUG_INTENT_MATCHING) {
3396                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3397                }
3398
3399                String action = sintent.getAction();
3400                if (resultsAction != null && resultsAction.equals(action)) {
3401                    // If this action was explicitly requested, then don't
3402                    // remove things that have it.
3403                    action = null;
3404                }
3405
3406                ResolveInfo ri = null;
3407                ActivityInfo ai = null;
3408
3409                ComponentName comp = sintent.getComponent();
3410                if (comp == null) {
3411                    ri = resolveIntent(
3412                        sintent,
3413                        specificTypes != null ? specificTypes[i] : null,
3414                            flags, userId);
3415                    if (ri == null) {
3416                        continue;
3417                    }
3418                    if (ri == mResolveInfo) {
3419                        // ACK!  Must do something better with this.
3420                    }
3421                    ai = ri.activityInfo;
3422                    comp = new ComponentName(ai.applicationInfo.packageName,
3423                            ai.name);
3424                } else {
3425                    ai = getActivityInfo(comp, flags, userId);
3426                    if (ai == null) {
3427                        continue;
3428                    }
3429                }
3430
3431                // Look for any generic query activities that are duplicates
3432                // of this specific one, and remove them from the results.
3433                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3434                N = results.size();
3435                int j;
3436                for (j=specificsPos; j<N; j++) {
3437                    ResolveInfo sri = results.get(j);
3438                    if ((sri.activityInfo.name.equals(comp.getClassName())
3439                            && sri.activityInfo.applicationInfo.packageName.equals(
3440                                    comp.getPackageName()))
3441                        || (action != null && sri.filter.matchAction(action))) {
3442                        results.remove(j);
3443                        if (DEBUG_INTENT_MATCHING) Log.v(
3444                            TAG, "Removing duplicate item from " + j
3445                            + " due to specific " + specificsPos);
3446                        if (ri == null) {
3447                            ri = sri;
3448                        }
3449                        j--;
3450                        N--;
3451                    }
3452                }
3453
3454                // Add this specific item to its proper place.
3455                if (ri == null) {
3456                    ri = new ResolveInfo();
3457                    ri.activityInfo = ai;
3458                }
3459                results.add(specificsPos, ri);
3460                ri.specificIndex = i;
3461                specificsPos++;
3462            }
3463        }
3464
3465        // Now we go through the remaining generic results and remove any
3466        // duplicate actions that are found here.
3467        N = results.size();
3468        for (int i=specificsPos; i<N-1; i++) {
3469            final ResolveInfo rii = results.get(i);
3470            if (rii.filter == null) {
3471                continue;
3472            }
3473
3474            // Iterate over all of the actions of this result's intent
3475            // filter...  typically this should be just one.
3476            final Iterator<String> it = rii.filter.actionsIterator();
3477            if (it == null) {
3478                continue;
3479            }
3480            while (it.hasNext()) {
3481                final String action = it.next();
3482                if (resultsAction != null && resultsAction.equals(action)) {
3483                    // If this action was explicitly requested, then don't
3484                    // remove things that have it.
3485                    continue;
3486                }
3487                for (int j=i+1; j<N; j++) {
3488                    final ResolveInfo rij = results.get(j);
3489                    if (rij.filter != null && rij.filter.hasAction(action)) {
3490                        results.remove(j);
3491                        if (DEBUG_INTENT_MATCHING) Log.v(
3492                            TAG, "Removing duplicate item from " + j
3493                            + " due to action " + action + " at " + i);
3494                        j--;
3495                        N--;
3496                    }
3497                }
3498            }
3499
3500            // If the caller didn't request filter information, drop it now
3501            // so we don't have to marshall/unmarshall it.
3502            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3503                rii.filter = null;
3504            }
3505        }
3506
3507        // Filter out the caller activity if so requested.
3508        if (caller != null) {
3509            N = results.size();
3510            for (int i=0; i<N; i++) {
3511                ActivityInfo ainfo = results.get(i).activityInfo;
3512                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3513                        && caller.getClassName().equals(ainfo.name)) {
3514                    results.remove(i);
3515                    break;
3516                }
3517            }
3518        }
3519
3520        // If the caller didn't request filter information,
3521        // drop them now so we don't have to
3522        // marshall/unmarshall it.
3523        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3524            N = results.size();
3525            for (int i=0; i<N; i++) {
3526                results.get(i).filter = null;
3527            }
3528        }
3529
3530        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3531        return results;
3532    }
3533
3534    @Override
3535    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3536            int userId) {
3537        if (!sUserManager.exists(userId)) return Collections.emptyList();
3538        ComponentName comp = intent.getComponent();
3539        if (comp == null) {
3540            if (intent.getSelector() != null) {
3541                intent = intent.getSelector();
3542                comp = intent.getComponent();
3543            }
3544        }
3545        if (comp != null) {
3546            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3547            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3548            if (ai != null) {
3549                ResolveInfo ri = new ResolveInfo();
3550                ri.activityInfo = ai;
3551                list.add(ri);
3552            }
3553            return list;
3554        }
3555
3556        // reader
3557        synchronized (mPackages) {
3558            String pkgName = intent.getPackage();
3559            if (pkgName == null) {
3560                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3561            }
3562            final PackageParser.Package pkg = mPackages.get(pkgName);
3563            if (pkg != null) {
3564                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3565                        userId);
3566            }
3567            return null;
3568        }
3569    }
3570
3571    @Override
3572    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3573        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3574        if (!sUserManager.exists(userId)) return null;
3575        if (query != null) {
3576            if (query.size() >= 1) {
3577                // If there is more than one service with the same priority,
3578                // just arbitrarily pick the first one.
3579                return query.get(0);
3580            }
3581        }
3582        return null;
3583    }
3584
3585    @Override
3586    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3587            int userId) {
3588        if (!sUserManager.exists(userId)) return Collections.emptyList();
3589        ComponentName comp = intent.getComponent();
3590        if (comp == null) {
3591            if (intent.getSelector() != null) {
3592                intent = intent.getSelector();
3593                comp = intent.getComponent();
3594            }
3595        }
3596        if (comp != null) {
3597            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3598            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3599            if (si != null) {
3600                final ResolveInfo ri = new ResolveInfo();
3601                ri.serviceInfo = si;
3602                list.add(ri);
3603            }
3604            return list;
3605        }
3606
3607        // reader
3608        synchronized (mPackages) {
3609            String pkgName = intent.getPackage();
3610            if (pkgName == null) {
3611                return mServices.queryIntent(intent, resolvedType, flags, userId);
3612            }
3613            final PackageParser.Package pkg = mPackages.get(pkgName);
3614            if (pkg != null) {
3615                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3616                        userId);
3617            }
3618            return null;
3619        }
3620    }
3621
3622    @Override
3623    public List<ResolveInfo> queryIntentContentProviders(
3624            Intent intent, String resolvedType, int flags, int userId) {
3625        if (!sUserManager.exists(userId)) return Collections.emptyList();
3626        ComponentName comp = intent.getComponent();
3627        if (comp == null) {
3628            if (intent.getSelector() != null) {
3629                intent = intent.getSelector();
3630                comp = intent.getComponent();
3631            }
3632        }
3633        if (comp != null) {
3634            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3635            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3636            if (pi != null) {
3637                final ResolveInfo ri = new ResolveInfo();
3638                ri.providerInfo = pi;
3639                list.add(ri);
3640            }
3641            return list;
3642        }
3643
3644        // reader
3645        synchronized (mPackages) {
3646            String pkgName = intent.getPackage();
3647            if (pkgName == null) {
3648                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3649            }
3650            final PackageParser.Package pkg = mPackages.get(pkgName);
3651            if (pkg != null) {
3652                return mProviders.queryIntentForPackage(
3653                        intent, resolvedType, flags, pkg.providers, userId);
3654            }
3655            return null;
3656        }
3657    }
3658
3659    @Override
3660    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3661        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3662
3663        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3664
3665        // writer
3666        synchronized (mPackages) {
3667            ArrayList<PackageInfo> list;
3668            if (listUninstalled) {
3669                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3670                for (PackageSetting ps : mSettings.mPackages.values()) {
3671                    PackageInfo pi;
3672                    if (ps.pkg != null) {
3673                        pi = generatePackageInfo(ps.pkg, flags, userId);
3674                    } else {
3675                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3676                    }
3677                    if (pi != null) {
3678                        list.add(pi);
3679                    }
3680                }
3681            } else {
3682                list = new ArrayList<PackageInfo>(mPackages.size());
3683                for (PackageParser.Package p : mPackages.values()) {
3684                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3685                    if (pi != null) {
3686                        list.add(pi);
3687                    }
3688                }
3689            }
3690
3691            return new ParceledListSlice<PackageInfo>(list);
3692        }
3693    }
3694
3695    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3696            String[] permissions, boolean[] tmp, int flags, int userId) {
3697        int numMatch = 0;
3698        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3699        for (int i=0; i<permissions.length; i++) {
3700            if (gp.grantedPermissions.contains(permissions[i])) {
3701                tmp[i] = true;
3702                numMatch++;
3703            } else {
3704                tmp[i] = false;
3705            }
3706        }
3707        if (numMatch == 0) {
3708            return;
3709        }
3710        PackageInfo pi;
3711        if (ps.pkg != null) {
3712            pi = generatePackageInfo(ps.pkg, flags, userId);
3713        } else {
3714            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3715        }
3716        // The above might return null in cases of uninstalled apps or install-state
3717        // skew across users/profiles.
3718        if (pi != null) {
3719            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3720                if (numMatch == permissions.length) {
3721                    pi.requestedPermissions = permissions;
3722                } else {
3723                    pi.requestedPermissions = new String[numMatch];
3724                    numMatch = 0;
3725                    for (int i=0; i<permissions.length; i++) {
3726                        if (tmp[i]) {
3727                            pi.requestedPermissions[numMatch] = permissions[i];
3728                            numMatch++;
3729                        }
3730                    }
3731                }
3732            }
3733            list.add(pi);
3734        }
3735    }
3736
3737    @Override
3738    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3739            String[] permissions, int flags, int userId) {
3740        if (!sUserManager.exists(userId)) return null;
3741        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3742
3743        // writer
3744        synchronized (mPackages) {
3745            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3746            boolean[] tmpBools = new boolean[permissions.length];
3747            if (listUninstalled) {
3748                for (PackageSetting ps : mSettings.mPackages.values()) {
3749                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3750                }
3751            } else {
3752                for (PackageParser.Package pkg : mPackages.values()) {
3753                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3754                    if (ps != null) {
3755                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3756                                userId);
3757                    }
3758                }
3759            }
3760
3761            return new ParceledListSlice<PackageInfo>(list);
3762        }
3763    }
3764
3765    @Override
3766    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3767        if (!sUserManager.exists(userId)) return null;
3768        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3769
3770        // writer
3771        synchronized (mPackages) {
3772            ArrayList<ApplicationInfo> list;
3773            if (listUninstalled) {
3774                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3775                for (PackageSetting ps : mSettings.mPackages.values()) {
3776                    ApplicationInfo ai;
3777                    if (ps.pkg != null) {
3778                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3779                                ps.readUserState(userId), userId);
3780                    } else {
3781                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3782                    }
3783                    if (ai != null) {
3784                        list.add(ai);
3785                    }
3786                }
3787            } else {
3788                list = new ArrayList<ApplicationInfo>(mPackages.size());
3789                for (PackageParser.Package p : mPackages.values()) {
3790                    if (p.mExtras != null) {
3791                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3792                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3793                        if (ai != null) {
3794                            list.add(ai);
3795                        }
3796                    }
3797                }
3798            }
3799
3800            return new ParceledListSlice<ApplicationInfo>(list);
3801        }
3802    }
3803
3804    public List<ApplicationInfo> getPersistentApplications(int flags) {
3805        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3806
3807        // reader
3808        synchronized (mPackages) {
3809            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3810            final int userId = UserHandle.getCallingUserId();
3811            while (i.hasNext()) {
3812                final PackageParser.Package p = i.next();
3813                if (p.applicationInfo != null
3814                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3815                        && (!mSafeMode || isSystemApp(p))) {
3816                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3817                    if (ps != null) {
3818                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3819                                ps.readUserState(userId), userId);
3820                        if (ai != null) {
3821                            finalList.add(ai);
3822                        }
3823                    }
3824                }
3825            }
3826        }
3827
3828        return finalList;
3829    }
3830
3831    @Override
3832    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3833        if (!sUserManager.exists(userId)) return null;
3834        // reader
3835        synchronized (mPackages) {
3836            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3837            PackageSetting ps = provider != null
3838                    ? mSettings.mPackages.get(provider.owner.packageName)
3839                    : null;
3840            return ps != null
3841                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3842                    && (!mSafeMode || (provider.info.applicationInfo.flags
3843                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3844                    ? PackageParser.generateProviderInfo(provider, flags,
3845                            ps.readUserState(userId), userId)
3846                    : null;
3847        }
3848    }
3849
3850    /**
3851     * @deprecated
3852     */
3853    @Deprecated
3854    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3855        // reader
3856        synchronized (mPackages) {
3857            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3858                    .entrySet().iterator();
3859            final int userId = UserHandle.getCallingUserId();
3860            while (i.hasNext()) {
3861                Map.Entry<String, PackageParser.Provider> entry = i.next();
3862                PackageParser.Provider p = entry.getValue();
3863                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3864
3865                if (ps != null && p.syncable
3866                        && (!mSafeMode || (p.info.applicationInfo.flags
3867                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3868                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3869                            ps.readUserState(userId), userId);
3870                    if (info != null) {
3871                        outNames.add(entry.getKey());
3872                        outInfo.add(info);
3873                    }
3874                }
3875            }
3876        }
3877    }
3878
3879    @Override
3880    public List<ProviderInfo> queryContentProviders(String processName,
3881            int uid, int flags) {
3882        ArrayList<ProviderInfo> finalList = null;
3883        // reader
3884        synchronized (mPackages) {
3885            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3886            final int userId = processName != null ?
3887                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3888            while (i.hasNext()) {
3889                final PackageParser.Provider p = i.next();
3890                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3891                if (ps != null && p.info.authority != null
3892                        && (processName == null
3893                                || (p.info.processName.equals(processName)
3894                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3895                        && mSettings.isEnabledLPr(p.info, flags, userId)
3896                        && (!mSafeMode
3897                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3898                    if (finalList == null) {
3899                        finalList = new ArrayList<ProviderInfo>(3);
3900                    }
3901                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3902                            ps.readUserState(userId), userId);
3903                    if (info != null) {
3904                        finalList.add(info);
3905                    }
3906                }
3907            }
3908        }
3909
3910        if (finalList != null) {
3911            Collections.sort(finalList, mProviderInitOrderSorter);
3912        }
3913
3914        return finalList;
3915    }
3916
3917    @Override
3918    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3919            int flags) {
3920        // reader
3921        synchronized (mPackages) {
3922            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3923            return PackageParser.generateInstrumentationInfo(i, flags);
3924        }
3925    }
3926
3927    @Override
3928    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
3929            int flags) {
3930        ArrayList<InstrumentationInfo> finalList =
3931            new ArrayList<InstrumentationInfo>();
3932
3933        // reader
3934        synchronized (mPackages) {
3935            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
3936            while (i.hasNext()) {
3937                final PackageParser.Instrumentation p = i.next();
3938                if (targetPackage == null
3939                        || targetPackage.equals(p.info.targetPackage)) {
3940                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
3941                            flags);
3942                    if (ii != null) {
3943                        finalList.add(ii);
3944                    }
3945                }
3946            }
3947        }
3948
3949        return finalList;
3950    }
3951
3952    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
3953        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
3954        if (overlays == null) {
3955            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
3956            return;
3957        }
3958        for (PackageParser.Package opkg : overlays.values()) {
3959            // Not much to do if idmap fails: we already logged the error
3960            // and we certainly don't want to abort installation of pkg simply
3961            // because an overlay didn't fit properly. For these reasons,
3962            // ignore the return value of createIdmapForPackagePairLI.
3963            createIdmapForPackagePairLI(pkg, opkg);
3964        }
3965    }
3966
3967    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
3968            PackageParser.Package opkg) {
3969        if (!opkg.mTrustedOverlay) {
3970            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
3971                    opkg.baseCodePath + ": overlay not trusted");
3972            return false;
3973        }
3974        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
3975        if (overlaySet == null) {
3976            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
3977                    opkg.baseCodePath + " but target package has no known overlays");
3978            return false;
3979        }
3980        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
3981        // TODO: generate idmap for split APKs
3982        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
3983            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
3984                    + opkg.baseCodePath);
3985            return false;
3986        }
3987        PackageParser.Package[] overlayArray =
3988            overlaySet.values().toArray(new PackageParser.Package[0]);
3989        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
3990            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
3991                return p1.mOverlayPriority - p2.mOverlayPriority;
3992            }
3993        };
3994        Arrays.sort(overlayArray, cmp);
3995
3996        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
3997        int i = 0;
3998        for (PackageParser.Package p : overlayArray) {
3999            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4000        }
4001        return true;
4002    }
4003
4004    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4005        final File[] files = dir.listFiles();
4006        if (ArrayUtils.isEmpty(files)) {
4007            Log.d(TAG, "No files in app dir " + dir);
4008            return;
4009        }
4010
4011        if (DEBUG_PACKAGE_SCANNING) {
4012            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4013                    + " flags=0x" + Integer.toHexString(parseFlags));
4014        }
4015
4016        for (File file : files) {
4017            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4018                    && !PackageInstallerService.isStageName(file.getName());
4019            if (!isPackage) {
4020                // Ignore entries which are not packages
4021                continue;
4022            }
4023            try {
4024                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4025                        scanFlags, currentTime, null);
4026            } catch (PackageManagerException e) {
4027                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4028
4029                // Delete invalid userdata apps
4030                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4031                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4032                    Slog.w(TAG, "Deleting invalid package at " + file);
4033                    if (file.isDirectory()) {
4034                        FileUtils.deleteContents(file);
4035                    }
4036                    file.delete();
4037                }
4038            }
4039        }
4040    }
4041
4042    private static File getSettingsProblemFile() {
4043        File dataDir = Environment.getDataDirectory();
4044        File systemDir = new File(dataDir, "system");
4045        File fname = new File(systemDir, "uiderrors.txt");
4046        return fname;
4047    }
4048
4049    static void reportSettingsProblem(int priority, String msg) {
4050        try {
4051            File fname = getSettingsProblemFile();
4052            FileOutputStream out = new FileOutputStream(fname, true);
4053            PrintWriter pw = new FastPrintWriter(out);
4054            SimpleDateFormat formatter = new SimpleDateFormat();
4055            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4056            pw.println(dateString + ": " + msg);
4057            pw.close();
4058            FileUtils.setPermissions(
4059                    fname.toString(),
4060                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4061                    -1, -1);
4062        } catch (java.io.IOException e) {
4063        }
4064        Slog.println(priority, TAG, msg);
4065    }
4066
4067    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4068            PackageParser.Package pkg, File srcFile, int parseFlags)
4069            throws PackageManagerException {
4070        if (ps != null
4071                && ps.codePath.equals(srcFile)
4072                && ps.timeStamp == srcFile.lastModified()
4073                && !isCompatSignatureUpdateNeeded(pkg)) {
4074            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4075            if (ps.signatures.mSignatures != null
4076                    && ps.signatures.mSignatures.length != 0
4077                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4078                // Optimization: reuse the existing cached certificates
4079                // if the package appears to be unchanged.
4080                pkg.mSignatures = ps.signatures.mSignatures;
4081                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4082                synchronized (mPackages) {
4083                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4084                }
4085                return;
4086            }
4087
4088            Slog.w(TAG, "PackageSetting for " + ps.name
4089                    + " is missing signatures.  Collecting certs again to recover them.");
4090        } else {
4091            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4092        }
4093
4094        try {
4095            pp.collectCertificates(pkg, parseFlags);
4096            pp.collectManifestDigest(pkg);
4097        } catch (PackageParserException e) {
4098            throw PackageManagerException.from(e);
4099        }
4100    }
4101
4102    /*
4103     *  Scan a package and return the newly parsed package.
4104     *  Returns null in case of errors and the error code is stored in mLastScanError
4105     */
4106    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4107            long currentTime, UserHandle user) throws PackageManagerException {
4108        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4109        parseFlags |= mDefParseFlags;
4110        PackageParser pp = new PackageParser();
4111        pp.setSeparateProcesses(mSeparateProcesses);
4112        pp.setOnlyCoreApps(mOnlyCore);
4113        pp.setDisplayMetrics(mMetrics);
4114
4115        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4116            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4117        }
4118
4119        final PackageParser.Package pkg;
4120        try {
4121            pkg = pp.parsePackage(scanFile, parseFlags);
4122        } catch (PackageParserException e) {
4123            throw PackageManagerException.from(e);
4124        }
4125
4126        PackageSetting ps = null;
4127        PackageSetting updatedPkg;
4128        // reader
4129        synchronized (mPackages) {
4130            // Look to see if we already know about this package.
4131            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4132            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4133                // This package has been renamed to its original name.  Let's
4134                // use that.
4135                ps = mSettings.peekPackageLPr(oldName);
4136            }
4137            // If there was no original package, see one for the real package name.
4138            if (ps == null) {
4139                ps = mSettings.peekPackageLPr(pkg.packageName);
4140            }
4141            // Check to see if this package could be hiding/updating a system
4142            // package.  Must look for it either under the original or real
4143            // package name depending on our state.
4144            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4145            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4146        }
4147        boolean updatedPkgBetter = false;
4148        // First check if this is a system package that may involve an update
4149        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4150            if (ps != null && !ps.codePath.equals(scanFile)) {
4151                // The path has changed from what was last scanned...  check the
4152                // version of the new path against what we have stored to determine
4153                // what to do.
4154                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4155                if (pkg.mVersionCode < ps.versionCode) {
4156                    // The system package has been updated and the code path does not match
4157                    // Ignore entry. Skip it.
4158                    Log.i(TAG, "Package " + ps.name + " at " + scanFile
4159                            + " ignored: updated version " + ps.versionCode
4160                            + " better than this " + pkg.mVersionCode);
4161                    if (!updatedPkg.codePath.equals(scanFile)) {
4162                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4163                                + ps.name + " changing from " + updatedPkg.codePathString
4164                                + " to " + scanFile);
4165                        updatedPkg.codePath = scanFile;
4166                        updatedPkg.codePathString = scanFile.toString();
4167                        // This is the point at which we know that the system-disk APK
4168                        // for this package has moved during a reboot (e.g. due to an OTA),
4169                        // so we need to reevaluate it for privilege policy.
4170                        if (locationIsPrivileged(scanFile)) {
4171                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4172                        }
4173                    }
4174                    updatedPkg.pkg = pkg;
4175                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4176                } else {
4177                    // The current app on the system partition is better than
4178                    // what we have updated to on the data partition; switch
4179                    // back to the system partition version.
4180                    // At this point, its safely assumed that package installation for
4181                    // apps in system partition will go through. If not there won't be a working
4182                    // version of the app
4183                    // writer
4184                    synchronized (mPackages) {
4185                        // Just remove the loaded entries from package lists.
4186                        mPackages.remove(ps.name);
4187                    }
4188                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile
4189                            + "reverting from " + ps.codePathString
4190                            + ": new version " + pkg.mVersionCode
4191                            + " better than installed " + ps.versionCode);
4192
4193                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4194                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4195                            getAppDexInstructionSets(ps));
4196                    synchronized (mInstallLock) {
4197                        args.cleanUpResourcesLI();
4198                    }
4199                    synchronized (mPackages) {
4200                        mSettings.enableSystemPackageLPw(ps.name);
4201                    }
4202                    updatedPkgBetter = true;
4203                }
4204            }
4205        }
4206
4207        if (updatedPkg != null) {
4208            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4209            // initially
4210            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4211
4212            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4213            // flag set initially
4214            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4215                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4216            }
4217        }
4218
4219        // Verify certificates against what was last scanned
4220        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4221
4222        /*
4223         * A new system app appeared, but we already had a non-system one of the
4224         * same name installed earlier.
4225         */
4226        boolean shouldHideSystemApp = false;
4227        if (updatedPkg == null && ps != null
4228                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4229            /*
4230             * Check to make sure the signatures match first. If they don't,
4231             * wipe the installed application and its data.
4232             */
4233            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4234                    != PackageManager.SIGNATURE_MATCH) {
4235                if (DEBUG_INSTALL) Slog.d(TAG, "Signature mismatch!");
4236                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4237                ps = null;
4238            } else {
4239                /*
4240                 * If the newly-added system app is an older version than the
4241                 * already installed version, hide it. It will be scanned later
4242                 * and re-added like an update.
4243                 */
4244                if (pkg.mVersionCode < ps.versionCode) {
4245                    shouldHideSystemApp = true;
4246                } else {
4247                    /*
4248                     * The newly found system app is a newer version that the
4249                     * one previously installed. Simply remove the
4250                     * already-installed application and replace it with our own
4251                     * while keeping the application data.
4252                     */
4253                    Slog.w(TAG, "Package " + ps.name + " at " + scanFile + "reverting from "
4254                            + ps.codePathString + ": new version " + pkg.mVersionCode
4255                            + " better than installed " + ps.versionCode);
4256                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4257                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4258                            getAppDexInstructionSets(ps));
4259                    synchronized (mInstallLock) {
4260                        args.cleanUpResourcesLI();
4261                    }
4262                }
4263            }
4264        }
4265
4266        // The apk is forward locked (not public) if its code and resources
4267        // are kept in different files. (except for app in either system or
4268        // vendor path).
4269        // TODO grab this value from PackageSettings
4270        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4271            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4272                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4273            }
4274        }
4275
4276        // TODO: extend to support forward-locked splits
4277        String resourcePath = null;
4278        String baseResourcePath = null;
4279        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4280            if (ps != null && ps.resourcePathString != null) {
4281                resourcePath = ps.resourcePathString;
4282                baseResourcePath = ps.resourcePathString;
4283            } else {
4284                // Should not happen at all. Just log an error.
4285                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4286            }
4287        } else {
4288            resourcePath = pkg.codePath;
4289            baseResourcePath = pkg.baseCodePath;
4290        }
4291
4292        // Set application objects path explicitly.
4293        pkg.applicationInfo.setCodePath(pkg.codePath);
4294        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4295        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4296        pkg.applicationInfo.setResourcePath(resourcePath);
4297        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4298        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4299
4300        // Note that we invoke the following method only if we are about to unpack an application
4301        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4302                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4303
4304        /*
4305         * If the system app should be overridden by a previously installed
4306         * data, hide the system app now and let the /data/app scan pick it up
4307         * again.
4308         */
4309        if (shouldHideSystemApp) {
4310            synchronized (mPackages) {
4311                /*
4312                 * We have to grant systems permissions before we hide, because
4313                 * grantPermissions will assume the package update is trying to
4314                 * expand its permissions.
4315                 */
4316                grantPermissionsLPw(pkg, true, pkg.packageName);
4317                mSettings.disableSystemPackageLPw(pkg.packageName);
4318            }
4319        }
4320
4321        return scannedPkg;
4322    }
4323
4324    private static String fixProcessName(String defProcessName,
4325            String processName, int uid) {
4326        if (processName == null) {
4327            return defProcessName;
4328        }
4329        return processName;
4330    }
4331
4332    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4333            throws PackageManagerException {
4334        if (pkgSetting.signatures.mSignatures != null) {
4335            // Already existing package. Make sure signatures match
4336            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4337                    == PackageManager.SIGNATURE_MATCH;
4338            if (!match) {
4339                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4340                        == PackageManager.SIGNATURE_MATCH;
4341            }
4342            if (!match) {
4343                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4344                        + pkg.packageName + " signatures do not match the "
4345                        + "previously installed version; ignoring!");
4346            }
4347        }
4348
4349        // Check for shared user signatures
4350        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4351            // Already existing package. Make sure signatures match
4352            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4353                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4354            if (!match) {
4355                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4356                        == PackageManager.SIGNATURE_MATCH;
4357            }
4358            if (!match) {
4359                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4360                        "Package " + pkg.packageName
4361                        + " has no signatures that match those in shared user "
4362                        + pkgSetting.sharedUser.name + "; ignoring!");
4363            }
4364        }
4365    }
4366
4367    /**
4368     * Enforces that only the system UID or root's UID can call a method exposed
4369     * via Binder.
4370     *
4371     * @param message used as message if SecurityException is thrown
4372     * @throws SecurityException if the caller is not system or root
4373     */
4374    private static final void enforceSystemOrRoot(String message) {
4375        final int uid = Binder.getCallingUid();
4376        if (uid != Process.SYSTEM_UID && uid != 0) {
4377            throw new SecurityException(message);
4378        }
4379    }
4380
4381    @Override
4382    public void performBootDexOpt() {
4383        enforceSystemOrRoot("Only the system can request dexopt be performed");
4384
4385        final HashSet<PackageParser.Package> pkgs;
4386        synchronized (mPackages) {
4387            pkgs = mDeferredDexOpt;
4388            mDeferredDexOpt = null;
4389        }
4390
4391        if (pkgs != null) {
4392            // Filter out packages that aren't recently used.
4393            //
4394            // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4395            // should do a full dexopt.
4396            if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4397                // TODO: add a property to control this?
4398                long dexOptLRUThresholdInMinutes;
4399                if (mLazyDexOpt) {
4400                    dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4401                } else {
4402                    dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4403                }
4404                long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4405
4406                int total = pkgs.size();
4407                int skipped = 0;
4408                long now = System.currentTimeMillis();
4409                for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4410                    PackageParser.Package pkg = i.next();
4411                    long then = pkg.mLastPackageUsageTimeInMills;
4412                    if (then + dexOptLRUThresholdInMills < now) {
4413                        if (DEBUG_DEXOPT) {
4414                            Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4415                                  ((then == 0) ? "never" : new Date(then)));
4416                        }
4417                        i.remove();
4418                        skipped++;
4419                    }
4420                }
4421                if (DEBUG_DEXOPT) {
4422                    Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4423                }
4424            }
4425
4426            int i = 0;
4427            for (PackageParser.Package pkg : pkgs) {
4428                i++;
4429                if (DEBUG_DEXOPT) {
4430                    Log.i(TAG, "Optimizing app " + i + " of " + pkgs.size()
4431                          + ": " + pkg.packageName);
4432                }
4433                if (!isFirstBoot()) {
4434                    try {
4435                        ActivityManagerNative.getDefault().showBootMessage(
4436                                mContext.getResources().getString(
4437                                        R.string.android_upgrading_apk,
4438                                        i, pkgs.size()), true);
4439                    } catch (RemoteException e) {
4440                    }
4441                }
4442                PackageParser.Package p = pkg;
4443                synchronized (mInstallLock) {
4444                    performDexOptLI(p, null /* instruction sets */, false /* force dex */, false /* defer */,
4445                            true /* include dependencies */);
4446                }
4447            }
4448        }
4449    }
4450
4451    @Override
4452    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4453        return performDexOpt(packageName, instructionSet, false);
4454    }
4455
4456    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4457        if (info.primaryCpuAbi == null) {
4458            return getPreferredInstructionSet();
4459        }
4460
4461        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4462    }
4463
4464    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4465        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4466        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4467        if (!dexopt && !updateUsage) {
4468            // We aren't going to dexopt or update usage, so bail early.
4469            return false;
4470        }
4471        PackageParser.Package p;
4472        final String targetInstructionSet;
4473        synchronized (mPackages) {
4474            p = mPackages.get(packageName);
4475            if (p == null) {
4476                return false;
4477            }
4478            if (updateUsage) {
4479                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4480            }
4481            mPackageUsage.write(false);
4482            if (!dexopt) {
4483                // We aren't going to dexopt, so bail early.
4484                return false;
4485            }
4486
4487            targetInstructionSet = instructionSet != null ? instructionSet :
4488                    getPrimaryInstructionSet(p.applicationInfo);
4489            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4490                return false;
4491            }
4492        }
4493
4494        synchronized (mInstallLock) {
4495            final String[] instructionSets = new String[] { targetInstructionSet };
4496            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4497                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4498        }
4499    }
4500
4501    public HashSet<String> getPackagesThatNeedDexOpt() {
4502        HashSet<String> pkgs = null;
4503        synchronized (mPackages) {
4504            for (PackageParser.Package p : mPackages.values()) {
4505                if (DEBUG_DEXOPT) {
4506                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4507                }
4508                if (!p.mDexOptPerformed.isEmpty()) {
4509                    continue;
4510                }
4511                if (pkgs == null) {
4512                    pkgs = new HashSet<String>();
4513                }
4514                pkgs.add(p.packageName);
4515            }
4516        }
4517        return pkgs;
4518    }
4519
4520    public void shutdown() {
4521        mPackageUsage.write(true);
4522    }
4523
4524    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4525             boolean forceDex, boolean defer, HashSet<String> done) {
4526        for (int i=0; i<libs.size(); i++) {
4527            PackageParser.Package libPkg;
4528            String libName;
4529            synchronized (mPackages) {
4530                libName = libs.get(i);
4531                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4532                if (lib != null && lib.apk != null) {
4533                    libPkg = mPackages.get(lib.apk);
4534                } else {
4535                    libPkg = null;
4536                }
4537            }
4538            if (libPkg != null && !done.contains(libName)) {
4539                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4540            }
4541        }
4542    }
4543
4544    static final int DEX_OPT_SKIPPED = 0;
4545    static final int DEX_OPT_PERFORMED = 1;
4546    static final int DEX_OPT_DEFERRED = 2;
4547    static final int DEX_OPT_FAILED = -1;
4548
4549    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4550            boolean forceDex, boolean defer, HashSet<String> done) {
4551        final String[] instructionSets = targetInstructionSets != null ?
4552                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4553
4554        if (done != null) {
4555            done.add(pkg.packageName);
4556            if (pkg.usesLibraries != null) {
4557                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4558            }
4559            if (pkg.usesOptionalLibraries != null) {
4560                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4561            }
4562        }
4563
4564        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4565            return DEX_OPT_SKIPPED;
4566        }
4567
4568        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4569
4570        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4571        boolean performedDexOpt = false;
4572        // There are three basic cases here:
4573        // 1.) we need to dexopt, either because we are forced or it is needed
4574        // 2.) we are defering a needed dexopt
4575        // 3.) we are skipping an unneeded dexopt
4576        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4577        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4578            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4579                continue;
4580            }
4581
4582            for (String path : paths) {
4583                try {
4584                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4585                    // patckage or the one we find does not match the image checksum (i.e. it was
4586                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4587                    // odex file and it matches the checksum of the image but not its base address,
4588                    // meaning we need to move it.
4589                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4590                            pkg.packageName, dexCodeInstructionSet, defer);
4591                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4592                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4593                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4594                                + " vmSafeMode=" + vmSafeMode);
4595                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4596                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4597                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4598
4599                        if (ret < 0) {
4600                            // Don't bother running dexopt again if we failed, it will probably
4601                            // just result in an error again. Also, don't bother dexopting for other
4602                            // paths & ISAs.
4603                            return DEX_OPT_FAILED;
4604                        }
4605
4606                        performedDexOpt = true;
4607                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4608                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4609                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4610                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4611                                pkg.packageName, dexCodeInstructionSet);
4612
4613                        if (ret < 0) {
4614                            // Don't bother running patchoat again if we failed, it will probably
4615                            // just result in an error again. Also, don't bother dexopting for other
4616                            // paths & ISAs.
4617                            return DEX_OPT_FAILED;
4618                        }
4619
4620                        performedDexOpt = true;
4621                    }
4622
4623                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4624                    // paths and instruction sets. We'll deal with them all together when we process
4625                    // our list of deferred dexopts.
4626                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4627                        if (mDeferredDexOpt == null) {
4628                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4629                        }
4630                        mDeferredDexOpt.add(pkg);
4631                        return DEX_OPT_DEFERRED;
4632                    }
4633                } catch (FileNotFoundException e) {
4634                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4635                    return DEX_OPT_FAILED;
4636                } catch (IOException e) {
4637                    Slog.w(TAG, "IOException reading apk: " + path, e);
4638                    return DEX_OPT_FAILED;
4639                } catch (StaleDexCacheError e) {
4640                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4641                    return DEX_OPT_FAILED;
4642                } catch (Exception e) {
4643                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4644                    return DEX_OPT_FAILED;
4645                }
4646            }
4647
4648            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4649            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4650            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4651            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4652            // it.
4653            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4654        }
4655
4656        // If we've gotten here, we're sure that no error occurred and that we haven't
4657        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4658        // we've skipped all of them because they are up to date. In both cases this
4659        // package doesn't need dexopt any longer.
4660        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4661    }
4662
4663    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4664        if (info.primaryCpuAbi != null) {
4665            if (info.secondaryCpuAbi != null) {
4666                return new String[] {
4667                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4668                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4669            } else {
4670                return new String[] {
4671                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4672            }
4673        }
4674
4675        return new String[] { getPreferredInstructionSet() };
4676    }
4677
4678    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4679        if (ps.primaryCpuAbiString != null) {
4680            if (ps.secondaryCpuAbiString != null) {
4681                return new String[] {
4682                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4683                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4684            } else {
4685                return new String[] {
4686                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4687            }
4688        }
4689
4690        return new String[] { getPreferredInstructionSet() };
4691    }
4692
4693    private static String getPreferredInstructionSet() {
4694        if (sPreferredInstructionSet == null) {
4695            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4696        }
4697
4698        return sPreferredInstructionSet;
4699    }
4700
4701    private static List<String> getAllInstructionSets() {
4702        final String[] allAbis = Build.SUPPORTED_ABIS;
4703        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4704
4705        for (String abi : allAbis) {
4706            final String instructionSet = VMRuntime.getInstructionSet(abi);
4707            if (!allInstructionSets.contains(instructionSet)) {
4708                allInstructionSets.add(instructionSet);
4709            }
4710        }
4711
4712        return allInstructionSets;
4713    }
4714
4715    /**
4716     * Returns the instruction set that should be used to compile dex code. In the presence of
4717     * a native bridge this might be different than the one shared libraries use.
4718     */
4719    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4720        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4721        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4722    }
4723
4724    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4725        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4726        for (String instructionSet : instructionSets) {
4727            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4728        }
4729        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4730    }
4731
4732    /**
4733     * Returns deduplicated list of supported instructions for dex code.
4734     */
4735    public static String[] getAllDexCodeInstructionSets() {
4736        String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length];
4737        for (int i = 0; i < supportedInstructionSets.length; i++) {
4738            String abi = Build.SUPPORTED_ABIS[i];
4739            supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi);
4740        }
4741        return getDexCodeInstructionSets(supportedInstructionSets);
4742    }
4743
4744    @Override
4745    public void forceDexOpt(String packageName) {
4746        enforceSystemOrRoot("forceDexOpt");
4747
4748        PackageParser.Package pkg;
4749        synchronized (mPackages) {
4750            pkg = mPackages.get(packageName);
4751            if (pkg == null) {
4752                throw new IllegalArgumentException("Missing package: " + packageName);
4753            }
4754        }
4755
4756        synchronized (mInstallLock) {
4757            final String[] instructionSets = new String[] {
4758                    getPrimaryInstructionSet(pkg.applicationInfo) };
4759            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4760            if (res != DEX_OPT_PERFORMED) {
4761                throw new IllegalStateException("Failed to dexopt: " + res);
4762            }
4763        }
4764    }
4765
4766    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4767                                boolean forceDex, boolean defer, boolean inclDependencies) {
4768        HashSet<String> done;
4769        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4770            done = new HashSet<String>();
4771            done.add(pkg.packageName);
4772        } else {
4773            done = null;
4774        }
4775        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4776    }
4777
4778    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4779        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4780            Slog.w(TAG, "Unable to update from " + oldPkg.name
4781                    + " to " + newPkg.packageName
4782                    + ": old package not in system partition");
4783            return false;
4784        } else if (mPackages.get(oldPkg.name) != null) {
4785            Slog.w(TAG, "Unable to update from " + oldPkg.name
4786                    + " to " + newPkg.packageName
4787                    + ": old package still exists");
4788            return false;
4789        }
4790        return true;
4791    }
4792
4793    File getDataPathForUser(int userId) {
4794        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4795    }
4796
4797    private File getDataPathForPackage(String packageName, int userId) {
4798        /*
4799         * Until we fully support multiple users, return the directory we
4800         * previously would have. The PackageManagerTests will need to be
4801         * revised when this is changed back..
4802         */
4803        if (userId == 0) {
4804            return new File(mAppDataDir, packageName);
4805        } else {
4806            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4807                + File.separator + packageName);
4808        }
4809    }
4810
4811    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4812        int[] users = sUserManager.getUserIds();
4813        int res = mInstaller.install(packageName, uid, uid, seinfo);
4814        if (res < 0) {
4815            return res;
4816        }
4817        for (int user : users) {
4818            if (user != 0) {
4819                res = mInstaller.createUserData(packageName,
4820                        UserHandle.getUid(user, uid), user, seinfo);
4821                if (res < 0) {
4822                    return res;
4823                }
4824            }
4825        }
4826        return res;
4827    }
4828
4829    private int removeDataDirsLI(String packageName) {
4830        int[] users = sUserManager.getUserIds();
4831        int res = 0;
4832        for (int user : users) {
4833            int resInner = mInstaller.remove(packageName, user);
4834            if (resInner < 0) {
4835                res = resInner;
4836            }
4837        }
4838
4839        return res;
4840    }
4841
4842    private int deleteCodeCacheDirsLI(String packageName) {
4843        int[] users = sUserManager.getUserIds();
4844        int res = 0;
4845        for (int user : users) {
4846            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
4847            if (resInner < 0) {
4848                res = resInner;
4849            }
4850        }
4851        return res;
4852    }
4853
4854    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
4855            PackageParser.Package changingLib) {
4856        if (file.path != null) {
4857            usesLibraryFiles.add(file.path);
4858            return;
4859        }
4860        PackageParser.Package p = mPackages.get(file.apk);
4861        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
4862            // If we are doing this while in the middle of updating a library apk,
4863            // then we need to make sure to use that new apk for determining the
4864            // dependencies here.  (We haven't yet finished committing the new apk
4865            // to the package manager state.)
4866            if (p == null || p.packageName.equals(changingLib.packageName)) {
4867                p = changingLib;
4868            }
4869        }
4870        if (p != null) {
4871            usesLibraryFiles.addAll(p.getAllCodePaths());
4872        }
4873    }
4874
4875    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
4876            PackageParser.Package changingLib) throws PackageManagerException {
4877        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
4878            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
4879            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
4880            for (int i=0; i<N; i++) {
4881                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
4882                if (file == null) {
4883                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
4884                            "Package " + pkg.packageName + " requires unavailable shared library "
4885                            + pkg.usesLibraries.get(i) + "; failing!");
4886                }
4887                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4888            }
4889            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
4890            for (int i=0; i<N; i++) {
4891                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
4892                if (file == null) {
4893                    Slog.w(TAG, "Package " + pkg.packageName
4894                            + " desires unavailable shared library "
4895                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
4896                } else {
4897                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
4898                }
4899            }
4900            N = usesLibraryFiles.size();
4901            if (N > 0) {
4902                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
4903            } else {
4904                pkg.usesLibraryFiles = null;
4905            }
4906        }
4907    }
4908
4909    private static boolean hasString(List<String> list, List<String> which) {
4910        if (list == null) {
4911            return false;
4912        }
4913        for (int i=list.size()-1; i>=0; i--) {
4914            for (int j=which.size()-1; j>=0; j--) {
4915                if (which.get(j).equals(list.get(i))) {
4916                    return true;
4917                }
4918            }
4919        }
4920        return false;
4921    }
4922
4923    private void updateAllSharedLibrariesLPw() {
4924        for (PackageParser.Package pkg : mPackages.values()) {
4925            try {
4926                updateSharedLibrariesLPw(pkg, null);
4927            } catch (PackageManagerException e) {
4928                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4929            }
4930        }
4931    }
4932
4933    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
4934            PackageParser.Package changingPkg) {
4935        ArrayList<PackageParser.Package> res = null;
4936        for (PackageParser.Package pkg : mPackages.values()) {
4937            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
4938                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
4939                if (res == null) {
4940                    res = new ArrayList<PackageParser.Package>();
4941                }
4942                res.add(pkg);
4943                try {
4944                    updateSharedLibrariesLPw(pkg, changingPkg);
4945                } catch (PackageManagerException e) {
4946                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
4947                }
4948            }
4949        }
4950        return res;
4951    }
4952
4953    /**
4954     * Derive the value of the {@code cpuAbiOverride} based on the provided
4955     * value and an optional stored value from the package settings.
4956     */
4957    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
4958        String cpuAbiOverride = null;
4959
4960        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
4961            cpuAbiOverride = null;
4962        } else if (abiOverride != null) {
4963            cpuAbiOverride = abiOverride;
4964        } else if (settings != null) {
4965            cpuAbiOverride = settings.cpuAbiOverrideString;
4966        }
4967
4968        return cpuAbiOverride;
4969    }
4970
4971    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
4972            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
4973        boolean success = false;
4974        try {
4975            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
4976                    currentTime, user);
4977            success = true;
4978            return res;
4979        } finally {
4980            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
4981                removeDataDirsLI(pkg.packageName);
4982            }
4983        }
4984    }
4985
4986    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
4987            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
4988        final File scanFile = new File(pkg.codePath);
4989        if (pkg.applicationInfo.getCodePath() == null ||
4990                pkg.applicationInfo.getResourcePath() == null) {
4991            // Bail out. The resource and code paths haven't been set.
4992            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
4993                    "Code and resource paths haven't been set correctly");
4994        }
4995
4996        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4997            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
4998        }
4999
5000        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5001            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5002        }
5003
5004        if (mCustomResolverComponentName != null &&
5005                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5006            setUpCustomResolverActivity(pkg);
5007        }
5008
5009        if (pkg.packageName.equals("android")) {
5010            synchronized (mPackages) {
5011                if (mAndroidApplication != null) {
5012                    Slog.w(TAG, "*************************************************");
5013                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5014                    Slog.w(TAG, " file=" + scanFile);
5015                    Slog.w(TAG, "*************************************************");
5016                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5017                            "Core android package being redefined.  Skipping.");
5018                }
5019
5020                // Set up information for our fall-back user intent resolution activity.
5021                mPlatformPackage = pkg;
5022                pkg.mVersionCode = mSdkVersion;
5023                mAndroidApplication = pkg.applicationInfo;
5024
5025                if (!mResolverReplaced) {
5026                    mResolveActivity.applicationInfo = mAndroidApplication;
5027                    mResolveActivity.name = ResolverActivity.class.getName();
5028                    mResolveActivity.packageName = mAndroidApplication.packageName;
5029                    mResolveActivity.processName = "system:ui";
5030                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5031                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5032                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5033                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5034                    mResolveActivity.exported = true;
5035                    mResolveActivity.enabled = true;
5036                    mResolveInfo.activityInfo = mResolveActivity;
5037                    mResolveInfo.priority = 0;
5038                    mResolveInfo.preferredOrder = 0;
5039                    mResolveInfo.match = 0;
5040                    mResolveComponentName = new ComponentName(
5041                            mAndroidApplication.packageName, mResolveActivity.name);
5042                }
5043            }
5044        }
5045
5046        if (DEBUG_PACKAGE_SCANNING) {
5047            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5048                Log.d(TAG, "Scanning package " + pkg.packageName);
5049        }
5050
5051        if (mPackages.containsKey(pkg.packageName)
5052                || mSharedLibraries.containsKey(pkg.packageName)) {
5053            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5054                    "Application package " + pkg.packageName
5055                    + " already installed.  Skipping duplicate.");
5056        }
5057
5058        // Initialize package source and resource directories
5059        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5060        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5061
5062        SharedUserSetting suid = null;
5063        PackageSetting pkgSetting = null;
5064
5065        if (!isSystemApp(pkg)) {
5066            // Only system apps can use these features.
5067            pkg.mOriginalPackages = null;
5068            pkg.mRealPackage = null;
5069            pkg.mAdoptPermissions = null;
5070        }
5071
5072        // writer
5073        synchronized (mPackages) {
5074            if (pkg.mSharedUserId != null) {
5075                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5076                if (suid == null) {
5077                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5078                            "Creating application package " + pkg.packageName
5079                            + " for shared user failed");
5080                }
5081                if (DEBUG_PACKAGE_SCANNING) {
5082                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5083                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5084                                + "): packages=" + suid.packages);
5085                }
5086            }
5087
5088            // Check if we are renaming from an original package name.
5089            PackageSetting origPackage = null;
5090            String realName = null;
5091            if (pkg.mOriginalPackages != null) {
5092                // This package may need to be renamed to a previously
5093                // installed name.  Let's check on that...
5094                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5095                if (pkg.mOriginalPackages.contains(renamed)) {
5096                    // This package had originally been installed as the
5097                    // original name, and we have already taken care of
5098                    // transitioning to the new one.  Just update the new
5099                    // one to continue using the old name.
5100                    realName = pkg.mRealPackage;
5101                    if (!pkg.packageName.equals(renamed)) {
5102                        // Callers into this function may have already taken
5103                        // care of renaming the package; only do it here if
5104                        // it is not already done.
5105                        pkg.setPackageName(renamed);
5106                    }
5107
5108                } else {
5109                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5110                        if ((origPackage = mSettings.peekPackageLPr(
5111                                pkg.mOriginalPackages.get(i))) != null) {
5112                            // We do have the package already installed under its
5113                            // original name...  should we use it?
5114                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5115                                // New package is not compatible with original.
5116                                origPackage = null;
5117                                continue;
5118                            } else if (origPackage.sharedUser != null) {
5119                                // Make sure uid is compatible between packages.
5120                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5121                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5122                                            + " to " + pkg.packageName + ": old uid "
5123                                            + origPackage.sharedUser.name
5124                                            + " differs from " + pkg.mSharedUserId);
5125                                    origPackage = null;
5126                                    continue;
5127                                }
5128                            } else {
5129                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5130                                        + pkg.packageName + " to old name " + origPackage.name);
5131                            }
5132                            break;
5133                        }
5134                    }
5135                }
5136            }
5137
5138            if (mTransferedPackages.contains(pkg.packageName)) {
5139                Slog.w(TAG, "Package " + pkg.packageName
5140                        + " was transferred to another, but its .apk remains");
5141            }
5142
5143            // Just create the setting, don't add it yet. For already existing packages
5144            // the PkgSetting exists already and doesn't have to be created.
5145            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5146                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5147                    pkg.applicationInfo.primaryCpuAbi,
5148                    pkg.applicationInfo.secondaryCpuAbi,
5149                    pkg.applicationInfo.flags, user, false);
5150            if (pkgSetting == null) {
5151                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5152                        "Creating application package " + pkg.packageName + " failed");
5153            }
5154
5155            if (pkgSetting.origPackage != null) {
5156                // If we are first transitioning from an original package,
5157                // fix up the new package's name now.  We need to do this after
5158                // looking up the package under its new name, so getPackageLP
5159                // can take care of fiddling things correctly.
5160                pkg.setPackageName(origPackage.name);
5161
5162                // File a report about this.
5163                String msg = "New package " + pkgSetting.realName
5164                        + " renamed to replace old package " + pkgSetting.name;
5165                reportSettingsProblem(Log.WARN, msg);
5166
5167                // Make a note of it.
5168                mTransferedPackages.add(origPackage.name);
5169
5170                // No longer need to retain this.
5171                pkgSetting.origPackage = null;
5172            }
5173
5174            if (realName != null) {
5175                // Make a note of it.
5176                mTransferedPackages.add(pkg.packageName);
5177            }
5178
5179            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5180                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5181            }
5182
5183            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5184                // Check all shared libraries and map to their actual file path.
5185                // We only do this here for apps not on a system dir, because those
5186                // are the only ones that can fail an install due to this.  We
5187                // will take care of the system apps by updating all of their
5188                // library paths after the scan is done.
5189                updateSharedLibrariesLPw(pkg, null);
5190            }
5191
5192            if (mFoundPolicyFile) {
5193                SELinuxMMAC.assignSeinfoValue(pkg);
5194            }
5195
5196            pkg.applicationInfo.uid = pkgSetting.appId;
5197            pkg.mExtras = pkgSetting;
5198            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5199                try {
5200                    verifySignaturesLP(pkgSetting, pkg);
5201                } catch (PackageManagerException e) {
5202                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5203                        throw e;
5204                    }
5205                    // The signature has changed, but this package is in the system
5206                    // image...  let's recover!
5207                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5208                    // However...  if this package is part of a shared user, but it
5209                    // doesn't match the signature of the shared user, let's fail.
5210                    // What this means is that you can't change the signatures
5211                    // associated with an overall shared user, which doesn't seem all
5212                    // that unreasonable.
5213                    if (pkgSetting.sharedUser != null) {
5214                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5215                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5216                            throw new PackageManagerException(
5217                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5218                                            "Signature mismatch for shared user : "
5219                                            + pkgSetting.sharedUser);
5220                        }
5221                    }
5222                    // File a report about this.
5223                    String msg = "System package " + pkg.packageName
5224                        + " signature changed; retaining data.";
5225                    reportSettingsProblem(Log.WARN, msg);
5226                }
5227            } else {
5228                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5229                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5230                            + pkg.packageName + " upgrade keys do not match the "
5231                            + "previously installed version");
5232                } else {
5233                    // signatures may have changed as result of upgrade
5234                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5235                }
5236            }
5237            // Verify that this new package doesn't have any content providers
5238            // that conflict with existing packages.  Only do this if the
5239            // package isn't already installed, since we don't want to break
5240            // things that are installed.
5241            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5242                final int N = pkg.providers.size();
5243                int i;
5244                for (i=0; i<N; i++) {
5245                    PackageParser.Provider p = pkg.providers.get(i);
5246                    if (p.info.authority != null) {
5247                        String names[] = p.info.authority.split(";");
5248                        for (int j = 0; j < names.length; j++) {
5249                            if (mProvidersByAuthority.containsKey(names[j])) {
5250                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5251                                final String otherPackageName =
5252                                        ((other != null && other.getComponentName() != null) ?
5253                                                other.getComponentName().getPackageName() : "?");
5254                                throw new PackageManagerException(
5255                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5256                                                "Can't install because provider name " + names[j]
5257                                                + " (in package " + pkg.applicationInfo.packageName
5258                                                + ") is already used by " + otherPackageName);
5259                            }
5260                        }
5261                    }
5262                }
5263            }
5264
5265            if (pkg.mAdoptPermissions != null) {
5266                // This package wants to adopt ownership of permissions from
5267                // another package.
5268                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5269                    final String origName = pkg.mAdoptPermissions.get(i);
5270                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5271                    if (orig != null) {
5272                        if (verifyPackageUpdateLPr(orig, pkg)) {
5273                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5274                                    + pkg.packageName);
5275                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5276                        }
5277                    }
5278                }
5279            }
5280        }
5281
5282        final String pkgName = pkg.packageName;
5283
5284        final long scanFileTime = scanFile.lastModified();
5285        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5286        pkg.applicationInfo.processName = fixProcessName(
5287                pkg.applicationInfo.packageName,
5288                pkg.applicationInfo.processName,
5289                pkg.applicationInfo.uid);
5290
5291        File dataPath;
5292        if (mPlatformPackage == pkg) {
5293            // The system package is special.
5294            dataPath = new File(Environment.getDataDirectory(), "system");
5295
5296            pkg.applicationInfo.dataDir = dataPath.getPath();
5297
5298        } else {
5299            // This is a normal package, need to make its data directory.
5300            dataPath = getDataPathForPackage(pkg.packageName, 0);
5301
5302            boolean uidError = false;
5303            if (dataPath.exists()) {
5304                int currentUid = 0;
5305                try {
5306                    StructStat stat = Os.stat(dataPath.getPath());
5307                    currentUid = stat.st_uid;
5308                } catch (ErrnoException e) {
5309                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5310                }
5311
5312                // If we have mismatched owners for the data path, we have a problem.
5313                if (currentUid != pkg.applicationInfo.uid) {
5314                    boolean recovered = false;
5315                    if (currentUid == 0) {
5316                        // The directory somehow became owned by root.  Wow.
5317                        // This is probably because the system was stopped while
5318                        // installd was in the middle of messing with its libs
5319                        // directory.  Ask installd to fix that.
5320                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5321                                pkg.applicationInfo.uid);
5322                        if (ret >= 0) {
5323                            recovered = true;
5324                            String msg = "Package " + pkg.packageName
5325                                    + " unexpectedly changed to uid 0; recovered to " +
5326                                    + pkg.applicationInfo.uid;
5327                            reportSettingsProblem(Log.WARN, msg);
5328                        }
5329                    }
5330                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5331                            || (scanFlags&SCAN_BOOTING) != 0)) {
5332                        // If this is a system app, we can at least delete its
5333                        // current data so the application will still work.
5334                        int ret = removeDataDirsLI(pkgName);
5335                        if (ret >= 0) {
5336                            // TODO: Kill the processes first
5337                            // Old data gone!
5338                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5339                                    ? "System package " : "Third party package ";
5340                            String msg = prefix + pkg.packageName
5341                                    + " has changed from uid: "
5342                                    + currentUid + " to "
5343                                    + pkg.applicationInfo.uid + "; old data erased";
5344                            reportSettingsProblem(Log.WARN, msg);
5345                            recovered = true;
5346
5347                            // And now re-install the app.
5348                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5349                                                   pkg.applicationInfo.seinfo);
5350                            if (ret == -1) {
5351                                // Ack should not happen!
5352                                msg = prefix + pkg.packageName
5353                                        + " could not have data directory re-created after delete.";
5354                                reportSettingsProblem(Log.WARN, msg);
5355                                throw new PackageManagerException(
5356                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5357                            }
5358                        }
5359                        if (!recovered) {
5360                            mHasSystemUidErrors = true;
5361                        }
5362                    } else if (!recovered) {
5363                        // If we allow this install to proceed, we will be broken.
5364                        // Abort, abort!
5365                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5366                                "scanPackageLI");
5367                    }
5368                    if (!recovered) {
5369                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5370                            + pkg.applicationInfo.uid + "/fs_"
5371                            + currentUid;
5372                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5373                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5374                        String msg = "Package " + pkg.packageName
5375                                + " has mismatched uid: "
5376                                + currentUid + " on disk, "
5377                                + pkg.applicationInfo.uid + " in settings";
5378                        // writer
5379                        synchronized (mPackages) {
5380                            mSettings.mReadMessages.append(msg);
5381                            mSettings.mReadMessages.append('\n');
5382                            uidError = true;
5383                            if (!pkgSetting.uidError) {
5384                                reportSettingsProblem(Log.ERROR, msg);
5385                            }
5386                        }
5387                    }
5388                }
5389                pkg.applicationInfo.dataDir = dataPath.getPath();
5390                if (mShouldRestoreconData) {
5391                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5392                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5393                                pkg.applicationInfo.uid);
5394                }
5395            } else {
5396                if (DEBUG_PACKAGE_SCANNING) {
5397                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5398                        Log.v(TAG, "Want this data dir: " + dataPath);
5399                }
5400                //invoke installer to do the actual installation
5401                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5402                                           pkg.applicationInfo.seinfo);
5403                if (ret < 0) {
5404                    // Error from installer
5405                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5406                            "Unable to create data dirs [errorCode=" + ret + "]");
5407                }
5408
5409                if (dataPath.exists()) {
5410                    pkg.applicationInfo.dataDir = dataPath.getPath();
5411                } else {
5412                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5413                    pkg.applicationInfo.dataDir = null;
5414                }
5415            }
5416
5417            pkgSetting.uidError = uidError;
5418        }
5419
5420        final String path = scanFile.getPath();
5421        final String codePath = pkg.applicationInfo.getCodePath();
5422        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5423        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5424            setBundledAppAbisAndRoots(pkg, pkgSetting);
5425
5426            // If we haven't found any native libraries for the app, check if it has
5427            // renderscript code. We'll need to force the app to 32 bit if it has
5428            // renderscript bitcode.
5429            if (pkg.applicationInfo.primaryCpuAbi == null
5430                    && pkg.applicationInfo.secondaryCpuAbi == null
5431                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5432                NativeLibraryHelper.Handle handle = null;
5433                try {
5434                    handle = NativeLibraryHelper.Handle.create(scanFile);
5435                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5436                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5437                    }
5438                } catch (IOException ioe) {
5439                    Slog.w(TAG, "Error scanning system app : " + ioe);
5440                } finally {
5441                    IoUtils.closeQuietly(handle);
5442                }
5443            }
5444
5445            setNativeLibraryPaths(pkg);
5446        } else {
5447            // TODO: We can probably be smarter about this stuff. For installed apps,
5448            // we can calculate this information at install time once and for all. For
5449            // system apps, we can probably assume that this information doesn't change
5450            // after the first boot scan. As things stand, we do lots of unnecessary work.
5451
5452            // Give ourselves some initial paths; we'll come back for another
5453            // pass once we've determined ABI below.
5454            setNativeLibraryPaths(pkg);
5455
5456            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5457            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5458            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5459
5460            NativeLibraryHelper.Handle handle = null;
5461            try {
5462                handle = NativeLibraryHelper.Handle.create(scanFile);
5463                // TODO(multiArch): This can be null for apps that didn't go through the
5464                // usual installation process. We can calculate it again, like we
5465                // do during install time.
5466                //
5467                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5468                // unnecessary.
5469                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5470
5471                // Null out the abis so that they can be recalculated.
5472                pkg.applicationInfo.primaryCpuAbi = null;
5473                pkg.applicationInfo.secondaryCpuAbi = null;
5474                if (isMultiArch(pkg.applicationInfo)) {
5475                    // Warn if we've set an abiOverride for multi-lib packages..
5476                    // By definition, we need to copy both 32 and 64 bit libraries for
5477                    // such packages.
5478                    if (pkg.cpuAbiOverride != null
5479                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5480                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5481                    }
5482
5483                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5484                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5485                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5486                        if (isAsec) {
5487                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5488                        } else {
5489                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5490                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5491                                    useIsaSpecificSubdirs);
5492                        }
5493                    }
5494
5495                    maybeThrowExceptionForMultiArchCopy(
5496                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5497
5498                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5499                        if (isAsec) {
5500                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5501                        } else {
5502                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5503                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5504                                    useIsaSpecificSubdirs);
5505                        }
5506                    }
5507
5508                    maybeThrowExceptionForMultiArchCopy(
5509                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5510
5511                    if (abi64 >= 0) {
5512                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5513                    }
5514
5515                    if (abi32 >= 0) {
5516                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5517                        if (abi64 >= 0) {
5518                            pkg.applicationInfo.secondaryCpuAbi = abi;
5519                        } else {
5520                            pkg.applicationInfo.primaryCpuAbi = abi;
5521                        }
5522                    }
5523                } else {
5524                    String[] abiList = (cpuAbiOverride != null) ?
5525                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5526
5527                    // Enable gross and lame hacks for apps that are built with old
5528                    // SDK tools. We must scan their APKs for renderscript bitcode and
5529                    // not launch them if it's present. Don't bother checking on devices
5530                    // that don't have 64 bit support.
5531                    boolean needsRenderScriptOverride = false;
5532                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5533                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5534                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5535                        needsRenderScriptOverride = true;
5536                    }
5537
5538                    final int copyRet;
5539                    if (isAsec) {
5540                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5541                    } else {
5542                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5543                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5544                    }
5545
5546                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5547                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5548                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5549                    }
5550
5551                    if (copyRet >= 0) {
5552                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5553                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5554                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5555                    } else if (needsRenderScriptOverride) {
5556                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5557                    }
5558                }
5559            } catch (IOException ioe) {
5560                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5561            } finally {
5562                IoUtils.closeQuietly(handle);
5563            }
5564
5565            // Now that we've calculated the ABIs and determined if it's an internal app,
5566            // we will go ahead and populate the nativeLibraryPath.
5567            setNativeLibraryPaths(pkg);
5568
5569            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5570            final int[] userIds = sUserManager.getUserIds();
5571            synchronized (mInstallLock) {
5572                // Create a native library symlink only if we have native libraries
5573                // and if the native libraries are 32 bit libraries. We do not provide
5574                // this symlink for 64 bit libraries.
5575                if (pkg.applicationInfo.primaryCpuAbi != null &&
5576                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5577                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5578                    for (int userId : userIds) {
5579                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5580                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5581                                    "Failed linking native library dir (user=" + userId + ")");
5582                        }
5583                    }
5584                }
5585            }
5586        }
5587
5588        // This is a special case for the "system" package, where the ABI is
5589        // dictated by the zygote configuration (and init.rc). We should keep track
5590        // of this ABI so that we can deal with "normal" applications that run under
5591        // the same UID correctly.
5592        if (mPlatformPackage == pkg) {
5593            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5594                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5595        }
5596
5597        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5598        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5599        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5600        // Copy the derived override back to the parsed package, so that we can
5601        // update the package settings accordingly.
5602        pkg.cpuAbiOverride = cpuAbiOverride;
5603
5604        if (DEBUG_ABI_SELECTION) {
5605            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5606                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5607                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5608        }
5609
5610        // Push the derived path down into PackageSettings so we know what to
5611        // clean up at uninstall time.
5612        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5613
5614        if (DEBUG_ABI_SELECTION) {
5615            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5616                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5617                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5618        }
5619
5620        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5621            // We don't do this here during boot because we can do it all
5622            // at once after scanning all existing packages.
5623            //
5624            // We also do this *before* we perform dexopt on this package, so that
5625            // we can avoid redundant dexopts, and also to make sure we've got the
5626            // code and package path correct.
5627            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5628                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5629        }
5630
5631        if ((scanFlags & SCAN_NO_DEX) == 0) {
5632            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5633                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5634                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5635            }
5636        }
5637
5638        if (mFactoryTest && pkg.requestedPermissions.contains(
5639                android.Manifest.permission.FACTORY_TEST)) {
5640            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5641        }
5642
5643        ArrayList<PackageParser.Package> clientLibPkgs = null;
5644
5645        // writer
5646        synchronized (mPackages) {
5647            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5648                // Only system apps can add new shared libraries.
5649                if (pkg.libraryNames != null) {
5650                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5651                        String name = pkg.libraryNames.get(i);
5652                        boolean allowed = false;
5653                        if (isUpdatedSystemApp(pkg)) {
5654                            // New library entries can only be added through the
5655                            // system image.  This is important to get rid of a lot
5656                            // of nasty edge cases: for example if we allowed a non-
5657                            // system update of the app to add a library, then uninstalling
5658                            // the update would make the library go away, and assumptions
5659                            // we made such as through app install filtering would now
5660                            // have allowed apps on the device which aren't compatible
5661                            // with it.  Better to just have the restriction here, be
5662                            // conservative, and create many fewer cases that can negatively
5663                            // impact the user experience.
5664                            final PackageSetting sysPs = mSettings
5665                                    .getDisabledSystemPkgLPr(pkg.packageName);
5666                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5667                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5668                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5669                                        allowed = true;
5670                                        allowed = true;
5671                                        break;
5672                                    }
5673                                }
5674                            }
5675                        } else {
5676                            allowed = true;
5677                        }
5678                        if (allowed) {
5679                            if (!mSharedLibraries.containsKey(name)) {
5680                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5681                            } else if (!name.equals(pkg.packageName)) {
5682                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5683                                        + name + " already exists; skipping");
5684                            }
5685                        } else {
5686                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5687                                    + name + " that is not declared on system image; skipping");
5688                        }
5689                    }
5690                    if ((scanFlags&SCAN_BOOTING) == 0) {
5691                        // If we are not booting, we need to update any applications
5692                        // that are clients of our shared library.  If we are booting,
5693                        // this will all be done once the scan is complete.
5694                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5695                    }
5696                }
5697            }
5698        }
5699
5700        // We also need to dexopt any apps that are dependent on this library.  Note that
5701        // if these fail, we should abort the install since installing the library will
5702        // result in some apps being broken.
5703        if (clientLibPkgs != null) {
5704            if ((scanFlags & SCAN_NO_DEX) == 0) {
5705                for (int i = 0; i < clientLibPkgs.size(); i++) {
5706                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5707                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
5708                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5709                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5710                                "scanPackageLI failed to dexopt clientLibPkgs");
5711                    }
5712                }
5713            }
5714        }
5715
5716        // Request the ActivityManager to kill the process(only for existing packages)
5717        // so that we do not end up in a confused state while the user is still using the older
5718        // version of the application while the new one gets installed.
5719        if ((scanFlags & SCAN_REPLACING) != 0) {
5720            killApplication(pkg.applicationInfo.packageName,
5721                        pkg.applicationInfo.uid, "update pkg");
5722        }
5723
5724        // Also need to kill any apps that are dependent on the library.
5725        if (clientLibPkgs != null) {
5726            for (int i=0; i<clientLibPkgs.size(); i++) {
5727                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5728                killApplication(clientPkg.applicationInfo.packageName,
5729                        clientPkg.applicationInfo.uid, "update lib");
5730            }
5731        }
5732
5733        // writer
5734        synchronized (mPackages) {
5735            // We don't expect installation to fail beyond this point
5736
5737            // Add the new setting to mSettings
5738            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5739            // Add the new setting to mPackages
5740            mPackages.put(pkg.applicationInfo.packageName, pkg);
5741            // Make sure we don't accidentally delete its data.
5742            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5743            while (iter.hasNext()) {
5744                PackageCleanItem item = iter.next();
5745                if (pkgName.equals(item.packageName)) {
5746                    iter.remove();
5747                }
5748            }
5749
5750            // Take care of first install / last update times.
5751            if (currentTime != 0) {
5752                if (pkgSetting.firstInstallTime == 0) {
5753                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5754                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5755                    pkgSetting.lastUpdateTime = currentTime;
5756                }
5757            } else if (pkgSetting.firstInstallTime == 0) {
5758                // We need *something*.  Take time time stamp of the file.
5759                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5760            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5761                if (scanFileTime != pkgSetting.timeStamp) {
5762                    // A package on the system image has changed; consider this
5763                    // to be an update.
5764                    pkgSetting.lastUpdateTime = scanFileTime;
5765                }
5766            }
5767
5768            // Add the package's KeySets to the global KeySetManagerService
5769            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5770            try {
5771                // Old KeySetData no longer valid.
5772                ksms.removeAppKeySetDataLPw(pkg.packageName);
5773                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5774                if (pkg.mKeySetMapping != null) {
5775                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5776                            pkg.mKeySetMapping.entrySet()) {
5777                        if (entry.getValue() != null) {
5778                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5779                                                          entry.getValue(), entry.getKey());
5780                        }
5781                    }
5782                    if (pkg.mUpgradeKeySets != null) {
5783                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5784                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5785                        }
5786                    }
5787                }
5788            } catch (NullPointerException e) {
5789                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5790            } catch (IllegalArgumentException e) {
5791                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5792            }
5793
5794            int N = pkg.providers.size();
5795            StringBuilder r = null;
5796            int i;
5797            for (i=0; i<N; i++) {
5798                PackageParser.Provider p = pkg.providers.get(i);
5799                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5800                        p.info.processName, pkg.applicationInfo.uid);
5801                mProviders.addProvider(p);
5802                p.syncable = p.info.isSyncable;
5803                if (p.info.authority != null) {
5804                    String names[] = p.info.authority.split(";");
5805                    p.info.authority = null;
5806                    for (int j = 0; j < names.length; j++) {
5807                        if (j == 1 && p.syncable) {
5808                            // We only want the first authority for a provider to possibly be
5809                            // syncable, so if we already added this provider using a different
5810                            // authority clear the syncable flag. We copy the provider before
5811                            // changing it because the mProviders object contains a reference
5812                            // to a provider that we don't want to change.
5813                            // Only do this for the second authority since the resulting provider
5814                            // object can be the same for all future authorities for this provider.
5815                            p = new PackageParser.Provider(p);
5816                            p.syncable = false;
5817                        }
5818                        if (!mProvidersByAuthority.containsKey(names[j])) {
5819                            mProvidersByAuthority.put(names[j], p);
5820                            if (p.info.authority == null) {
5821                                p.info.authority = names[j];
5822                            } else {
5823                                p.info.authority = p.info.authority + ";" + names[j];
5824                            }
5825                            if (DEBUG_PACKAGE_SCANNING) {
5826                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5827                                    Log.d(TAG, "Registered content provider: " + names[j]
5828                                            + ", className = " + p.info.name + ", isSyncable = "
5829                                            + p.info.isSyncable);
5830                            }
5831                        } else {
5832                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5833                            Slog.w(TAG, "Skipping provider name " + names[j] +
5834                                    " (in package " + pkg.applicationInfo.packageName +
5835                                    "): name already used by "
5836                                    + ((other != null && other.getComponentName() != null)
5837                                            ? other.getComponentName().getPackageName() : "?"));
5838                        }
5839                    }
5840                }
5841                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5842                    if (r == null) {
5843                        r = new StringBuilder(256);
5844                    } else {
5845                        r.append(' ');
5846                    }
5847                    r.append(p.info.name);
5848                }
5849            }
5850            if (r != null) {
5851                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
5852            }
5853
5854            N = pkg.services.size();
5855            r = null;
5856            for (i=0; i<N; i++) {
5857                PackageParser.Service s = pkg.services.get(i);
5858                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
5859                        s.info.processName, pkg.applicationInfo.uid);
5860                mServices.addService(s);
5861                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5862                    if (r == null) {
5863                        r = new StringBuilder(256);
5864                    } else {
5865                        r.append(' ');
5866                    }
5867                    r.append(s.info.name);
5868                }
5869            }
5870            if (r != null) {
5871                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
5872            }
5873
5874            N = pkg.receivers.size();
5875            r = null;
5876            for (i=0; i<N; i++) {
5877                PackageParser.Activity a = pkg.receivers.get(i);
5878                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5879                        a.info.processName, pkg.applicationInfo.uid);
5880                mReceivers.addActivity(a, "receiver");
5881                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5882                    if (r == null) {
5883                        r = new StringBuilder(256);
5884                    } else {
5885                        r.append(' ');
5886                    }
5887                    r.append(a.info.name);
5888                }
5889            }
5890            if (r != null) {
5891                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
5892            }
5893
5894            N = pkg.activities.size();
5895            r = null;
5896            for (i=0; i<N; i++) {
5897                PackageParser.Activity a = pkg.activities.get(i);
5898                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
5899                        a.info.processName, pkg.applicationInfo.uid);
5900                mActivities.addActivity(a, "activity");
5901                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5902                    if (r == null) {
5903                        r = new StringBuilder(256);
5904                    } else {
5905                        r.append(' ');
5906                    }
5907                    r.append(a.info.name);
5908                }
5909            }
5910            if (r != null) {
5911                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
5912            }
5913
5914            N = pkg.permissionGroups.size();
5915            r = null;
5916            for (i=0; i<N; i++) {
5917                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
5918                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
5919                if (cur == null) {
5920                    mPermissionGroups.put(pg.info.name, pg);
5921                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5922                        if (r == null) {
5923                            r = new StringBuilder(256);
5924                        } else {
5925                            r.append(' ');
5926                        }
5927                        r.append(pg.info.name);
5928                    }
5929                } else {
5930                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
5931                            + pg.info.packageName + " ignored: original from "
5932                            + cur.info.packageName);
5933                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5934                        if (r == null) {
5935                            r = new StringBuilder(256);
5936                        } else {
5937                            r.append(' ');
5938                        }
5939                        r.append("DUP:");
5940                        r.append(pg.info.name);
5941                    }
5942                }
5943            }
5944            if (r != null) {
5945                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
5946            }
5947
5948            N = pkg.permissions.size();
5949            r = null;
5950            for (i=0; i<N; i++) {
5951                PackageParser.Permission p = pkg.permissions.get(i);
5952                HashMap<String, BasePermission> permissionMap =
5953                        p.tree ? mSettings.mPermissionTrees
5954                        : mSettings.mPermissions;
5955                p.group = mPermissionGroups.get(p.info.group);
5956                if (p.info.group == null || p.group != null) {
5957                    BasePermission bp = permissionMap.get(p.info.name);
5958
5959                    // Allow system apps to redefine non-system permissions
5960                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
5961                        final boolean currentOwnerIsSystem = (bp.perm != null
5962                                && isSystemApp(bp.perm.owner));
5963                        if (isSystemApp(p.owner)) {
5964                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
5965                                // It's a built-in permission and no owner, take ownership now
5966                                bp.packageSetting = pkgSetting;
5967                                bp.perm = p;
5968                                bp.uid = pkg.applicationInfo.uid;
5969                                bp.sourcePackage = p.info.packageName;
5970                            } else if (!currentOwnerIsSystem) {
5971                                String msg = "New decl " + p.owner + " of permission  "
5972                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
5973                                reportSettingsProblem(Log.WARN, msg);
5974                                bp = null;
5975                            }
5976                        }
5977                    }
5978
5979                    if (bp == null) {
5980                        bp = new BasePermission(p.info.name, p.info.packageName,
5981                                BasePermission.TYPE_NORMAL);
5982                        permissionMap.put(p.info.name, bp);
5983                    }
5984
5985                    if (bp.perm == null) {
5986                        if (bp.sourcePackage == null
5987                                || bp.sourcePackage.equals(p.info.packageName)) {
5988                            BasePermission tree = findPermissionTreeLP(p.info.name);
5989                            if (tree == null
5990                                    || tree.sourcePackage.equals(p.info.packageName)) {
5991                                bp.packageSetting = pkgSetting;
5992                                bp.perm = p;
5993                                bp.uid = pkg.applicationInfo.uid;
5994                                bp.sourcePackage = p.info.packageName;
5995                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
5996                                    if (r == null) {
5997                                        r = new StringBuilder(256);
5998                                    } else {
5999                                        r.append(' ');
6000                                    }
6001                                    r.append(p.info.name);
6002                                }
6003                            } else {
6004                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6005                                        + p.info.packageName + " ignored: base tree "
6006                                        + tree.name + " is from package "
6007                                        + tree.sourcePackage);
6008                            }
6009                        } else {
6010                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6011                                    + p.info.packageName + " ignored: original from "
6012                                    + bp.sourcePackage);
6013                        }
6014                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6015                        if (r == null) {
6016                            r = new StringBuilder(256);
6017                        } else {
6018                            r.append(' ');
6019                        }
6020                        r.append("DUP:");
6021                        r.append(p.info.name);
6022                    }
6023                    if (bp.perm == p) {
6024                        bp.protectionLevel = p.info.protectionLevel;
6025                    }
6026                } else {
6027                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6028                            + p.info.packageName + " ignored: no group "
6029                            + p.group);
6030                }
6031            }
6032            if (r != null) {
6033                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6034            }
6035
6036            N = pkg.instrumentation.size();
6037            r = null;
6038            for (i=0; i<N; i++) {
6039                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6040                a.info.packageName = pkg.applicationInfo.packageName;
6041                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6042                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6043                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6044                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6045                a.info.dataDir = pkg.applicationInfo.dataDir;
6046
6047                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6048                // need other information about the application, like the ABI and what not ?
6049                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6050                mInstrumentation.put(a.getComponentName(), a);
6051                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6052                    if (r == null) {
6053                        r = new StringBuilder(256);
6054                    } else {
6055                        r.append(' ');
6056                    }
6057                    r.append(a.info.name);
6058                }
6059            }
6060            if (r != null) {
6061                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6062            }
6063
6064            if (pkg.protectedBroadcasts != null) {
6065                N = pkg.protectedBroadcasts.size();
6066                for (i=0; i<N; i++) {
6067                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6068                }
6069            }
6070
6071            pkgSetting.setTimeStamp(scanFileTime);
6072
6073            // Create idmap files for pairs of (packages, overlay packages).
6074            // Note: "android", ie framework-res.apk, is handled by native layers.
6075            if (pkg.mOverlayTarget != null) {
6076                // This is an overlay package.
6077                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6078                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6079                        mOverlays.put(pkg.mOverlayTarget,
6080                                new HashMap<String, PackageParser.Package>());
6081                    }
6082                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6083                    map.put(pkg.packageName, pkg);
6084                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6085                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6086                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6087                                "scanPackageLI failed to createIdmap");
6088                    }
6089                }
6090            } else if (mOverlays.containsKey(pkg.packageName) &&
6091                    !pkg.packageName.equals("android")) {
6092                // This is a regular package, with one or more known overlay packages.
6093                createIdmapsForPackageLI(pkg);
6094            }
6095        }
6096
6097        return pkg;
6098    }
6099
6100    /**
6101     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6102     * i.e, so that all packages can be run inside a single process if required.
6103     *
6104     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6105     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6106     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6107     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6108     * updating a package that belongs to a shared user.
6109     *
6110     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6111     * adds unnecessary complexity.
6112     */
6113    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6114            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6115        String requiredInstructionSet = null;
6116        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6117            requiredInstructionSet = VMRuntime.getInstructionSet(
6118                     scannedPackage.applicationInfo.primaryCpuAbi);
6119        }
6120
6121        PackageSetting requirer = null;
6122        for (PackageSetting ps : packagesForUser) {
6123            // If packagesForUser contains scannedPackage, we skip it. This will happen
6124            // when scannedPackage is an update of an existing package. Without this check,
6125            // we will never be able to change the ABI of any package belonging to a shared
6126            // user, even if it's compatible with other packages.
6127            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6128                if (ps.primaryCpuAbiString == null) {
6129                    continue;
6130                }
6131
6132                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6133                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6134                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6135                    // this but there's not much we can do.
6136                    String errorMessage = "Instruction set mismatch, "
6137                            + ((requirer == null) ? "[caller]" : requirer)
6138                            + " requires " + requiredInstructionSet + " whereas " + ps
6139                            + " requires " + instructionSet;
6140                    Slog.w(TAG, errorMessage);
6141                }
6142
6143                if (requiredInstructionSet == null) {
6144                    requiredInstructionSet = instructionSet;
6145                    requirer = ps;
6146                }
6147            }
6148        }
6149
6150        if (requiredInstructionSet != null) {
6151            String adjustedAbi;
6152            if (requirer != null) {
6153                // requirer != null implies that either scannedPackage was null or that scannedPackage
6154                // did not require an ABI, in which case we have to adjust scannedPackage to match
6155                // the ABI of the set (which is the same as requirer's ABI)
6156                adjustedAbi = requirer.primaryCpuAbiString;
6157                if (scannedPackage != null) {
6158                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6159                }
6160            } else {
6161                // requirer == null implies that we're updating all ABIs in the set to
6162                // match scannedPackage.
6163                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6164            }
6165
6166            for (PackageSetting ps : packagesForUser) {
6167                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6168                    if (ps.primaryCpuAbiString != null) {
6169                        continue;
6170                    }
6171
6172                    ps.primaryCpuAbiString = adjustedAbi;
6173                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6174                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6175                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6176
6177                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6178                                deferDexOpt, true) == DEX_OPT_FAILED) {
6179                            ps.primaryCpuAbiString = null;
6180                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6181                            return;
6182                        } else {
6183                            mInstaller.rmdex(ps.codePathString,
6184                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6185                        }
6186                    }
6187                }
6188            }
6189        }
6190    }
6191
6192    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6193        synchronized (mPackages) {
6194            mResolverReplaced = true;
6195            // Set up information for custom user intent resolution activity.
6196            mResolveActivity.applicationInfo = pkg.applicationInfo;
6197            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6198            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6199            mResolveActivity.processName = null;
6200            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6201            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6202                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6203            mResolveActivity.theme = 0;
6204            mResolveActivity.exported = true;
6205            mResolveActivity.enabled = true;
6206            mResolveInfo.activityInfo = mResolveActivity;
6207            mResolveInfo.priority = 0;
6208            mResolveInfo.preferredOrder = 0;
6209            mResolveInfo.match = 0;
6210            mResolveComponentName = mCustomResolverComponentName;
6211            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6212                    mResolveComponentName);
6213        }
6214    }
6215
6216    private static String calculateBundledApkRoot(final String codePathString) {
6217        final File codePath = new File(codePathString);
6218        final File codeRoot;
6219        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6220            codeRoot = Environment.getRootDirectory();
6221        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6222            codeRoot = Environment.getOemDirectory();
6223        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6224            codeRoot = Environment.getVendorDirectory();
6225        } else {
6226            // Unrecognized code path; take its top real segment as the apk root:
6227            // e.g. /something/app/blah.apk => /something
6228            try {
6229                File f = codePath.getCanonicalFile();
6230                File parent = f.getParentFile();    // non-null because codePath is a file
6231                File tmp;
6232                while ((tmp = parent.getParentFile()) != null) {
6233                    f = parent;
6234                    parent = tmp;
6235                }
6236                codeRoot = f;
6237                Slog.w(TAG, "Unrecognized code path "
6238                        + codePath + " - using " + codeRoot);
6239            } catch (IOException e) {
6240                // Can't canonicalize the code path -- shenanigans?
6241                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6242                return Environment.getRootDirectory().getPath();
6243            }
6244        }
6245        return codeRoot.getPath();
6246    }
6247
6248    /**
6249     * Derive and set the location of native libraries for the given package,
6250     * which varies depending on where and how the package was installed.
6251     */
6252    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6253        final ApplicationInfo info = pkg.applicationInfo;
6254        final String codePath = pkg.codePath;
6255        final File codeFile = new File(codePath);
6256        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6257        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6258
6259        info.nativeLibraryRootDir = null;
6260        info.nativeLibraryRootRequiresIsa = false;
6261        info.nativeLibraryDir = null;
6262        info.secondaryNativeLibraryDir = null;
6263
6264        if (isApkFile(codeFile)) {
6265            // Monolithic install
6266            if (bundledApp) {
6267                // If "/system/lib64/apkname" exists, assume that is the per-package
6268                // native library directory to use; otherwise use "/system/lib/apkname".
6269                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6270                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6271                        getPrimaryInstructionSet(info));
6272
6273                // This is a bundled system app so choose the path based on the ABI.
6274                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6275                // is just the default path.
6276                final String apkName = deriveCodePathName(codePath);
6277                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6278                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6279                        apkName).getAbsolutePath();
6280
6281                if (info.secondaryCpuAbi != null) {
6282                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6283                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6284                            secondaryLibDir, apkName).getAbsolutePath();
6285                }
6286            } else if (asecApp) {
6287                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6288                        .getAbsolutePath();
6289            } else {
6290                final String apkName = deriveCodePathName(codePath);
6291                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6292                        .getAbsolutePath();
6293            }
6294
6295            info.nativeLibraryRootRequiresIsa = false;
6296            info.nativeLibraryDir = info.nativeLibraryRootDir;
6297        } else {
6298            // Cluster install
6299            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6300            info.nativeLibraryRootRequiresIsa = true;
6301
6302            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6303                    getPrimaryInstructionSet(info)).getAbsolutePath();
6304
6305            if (info.secondaryCpuAbi != null) {
6306                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6307                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6308            }
6309        }
6310    }
6311
6312    /**
6313     * Calculate the abis and roots for a bundled app. These can uniquely
6314     * be determined from the contents of the system partition, i.e whether
6315     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6316     * of this information, and instead assume that the system was built
6317     * sensibly.
6318     */
6319    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6320                                           PackageSetting pkgSetting) {
6321        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6322
6323        // If "/system/lib64/apkname" exists, assume that is the per-package
6324        // native library directory to use; otherwise use "/system/lib/apkname".
6325        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6326        setBundledAppAbi(pkg, apkRoot, apkName);
6327        // pkgSetting might be null during rescan following uninstall of updates
6328        // to a bundled app, so accommodate that possibility.  The settings in
6329        // that case will be established later from the parsed package.
6330        //
6331        // If the settings aren't null, sync them up with what we've just derived.
6332        // note that apkRoot isn't stored in the package settings.
6333        if (pkgSetting != null) {
6334            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6335            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6336        }
6337    }
6338
6339    /**
6340     * Deduces the ABI of a bundled app and sets the relevant fields on the
6341     * parsed pkg object.
6342     *
6343     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6344     *        under which system libraries are installed.
6345     * @param apkName the name of the installed package.
6346     */
6347    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6348        final File codeFile = new File(pkg.codePath);
6349
6350        final boolean has64BitLibs;
6351        final boolean has32BitLibs;
6352        if (isApkFile(codeFile)) {
6353            // Monolithic install
6354            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6355            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6356        } else {
6357            // Cluster install
6358            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6359            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6360                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6361                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6362                has64BitLibs = (new File(rootDir, isa)).exists();
6363            } else {
6364                has64BitLibs = false;
6365            }
6366            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6367                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6368                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6369                has32BitLibs = (new File(rootDir, isa)).exists();
6370            } else {
6371                has32BitLibs = false;
6372            }
6373        }
6374
6375        if (has64BitLibs && !has32BitLibs) {
6376            // The package has 64 bit libs, but not 32 bit libs. Its primary
6377            // ABI should be 64 bit. We can safely assume here that the bundled
6378            // native libraries correspond to the most preferred ABI in the list.
6379
6380            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6381            pkg.applicationInfo.secondaryCpuAbi = null;
6382        } else if (has32BitLibs && !has64BitLibs) {
6383            // The package has 32 bit libs but not 64 bit libs. Its primary
6384            // ABI should be 32 bit.
6385
6386            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6387            pkg.applicationInfo.secondaryCpuAbi = null;
6388        } else if (has32BitLibs && has64BitLibs) {
6389            // The application has both 64 and 32 bit bundled libraries. We check
6390            // here that the app declares multiArch support, and warn if it doesn't.
6391            //
6392            // We will be lenient here and record both ABIs. The primary will be the
6393            // ABI that's higher on the list, i.e, a device that's configured to prefer
6394            // 64 bit apps will see a 64 bit primary ABI,
6395
6396            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6397                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6398            }
6399
6400            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6401                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6402                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6403            } else {
6404                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6405                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6406            }
6407        } else {
6408            pkg.applicationInfo.primaryCpuAbi = null;
6409            pkg.applicationInfo.secondaryCpuAbi = null;
6410        }
6411    }
6412
6413    private void killApplication(String pkgName, int appId, String reason) {
6414        // Request the ActivityManager to kill the process(only for existing packages)
6415        // so that we do not end up in a confused state while the user is still using the older
6416        // version of the application while the new one gets installed.
6417        IActivityManager am = ActivityManagerNative.getDefault();
6418        if (am != null) {
6419            try {
6420                am.killApplicationWithAppId(pkgName, appId, reason);
6421            } catch (RemoteException e) {
6422            }
6423        }
6424    }
6425
6426    void removePackageLI(PackageSetting ps, boolean chatty) {
6427        if (DEBUG_INSTALL) {
6428            if (chatty)
6429                Log.d(TAG, "Removing package " + ps.name);
6430        }
6431
6432        // writer
6433        synchronized (mPackages) {
6434            mPackages.remove(ps.name);
6435            final PackageParser.Package pkg = ps.pkg;
6436            if (pkg != null) {
6437                cleanPackageDataStructuresLILPw(pkg, chatty);
6438            }
6439        }
6440    }
6441
6442    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6443        if (DEBUG_INSTALL) {
6444            if (chatty)
6445                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6446        }
6447
6448        // writer
6449        synchronized (mPackages) {
6450            mPackages.remove(pkg.applicationInfo.packageName);
6451            cleanPackageDataStructuresLILPw(pkg, chatty);
6452        }
6453    }
6454
6455    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6456        int N = pkg.providers.size();
6457        StringBuilder r = null;
6458        int i;
6459        for (i=0; i<N; i++) {
6460            PackageParser.Provider p = pkg.providers.get(i);
6461            mProviders.removeProvider(p);
6462            if (p.info.authority == null) {
6463
6464                /* There was another ContentProvider with this authority when
6465                 * this app was installed so this authority is null,
6466                 * Ignore it as we don't have to unregister the provider.
6467                 */
6468                continue;
6469            }
6470            String names[] = p.info.authority.split(";");
6471            for (int j = 0; j < names.length; j++) {
6472                if (mProvidersByAuthority.get(names[j]) == p) {
6473                    mProvidersByAuthority.remove(names[j]);
6474                    if (DEBUG_REMOVE) {
6475                        if (chatty)
6476                            Log.d(TAG, "Unregistered content provider: " + names[j]
6477                                    + ", className = " + p.info.name + ", isSyncable = "
6478                                    + p.info.isSyncable);
6479                    }
6480                }
6481            }
6482            if (DEBUG_REMOVE && chatty) {
6483                if (r == null) {
6484                    r = new StringBuilder(256);
6485                } else {
6486                    r.append(' ');
6487                }
6488                r.append(p.info.name);
6489            }
6490        }
6491        if (r != null) {
6492            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6493        }
6494
6495        N = pkg.services.size();
6496        r = null;
6497        for (i=0; i<N; i++) {
6498            PackageParser.Service s = pkg.services.get(i);
6499            mServices.removeService(s);
6500            if (chatty) {
6501                if (r == null) {
6502                    r = new StringBuilder(256);
6503                } else {
6504                    r.append(' ');
6505                }
6506                r.append(s.info.name);
6507            }
6508        }
6509        if (r != null) {
6510            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6511        }
6512
6513        N = pkg.receivers.size();
6514        r = null;
6515        for (i=0; i<N; i++) {
6516            PackageParser.Activity a = pkg.receivers.get(i);
6517            mReceivers.removeActivity(a, "receiver");
6518            if (DEBUG_REMOVE && chatty) {
6519                if (r == null) {
6520                    r = new StringBuilder(256);
6521                } else {
6522                    r.append(' ');
6523                }
6524                r.append(a.info.name);
6525            }
6526        }
6527        if (r != null) {
6528            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6529        }
6530
6531        N = pkg.activities.size();
6532        r = null;
6533        for (i=0; i<N; i++) {
6534            PackageParser.Activity a = pkg.activities.get(i);
6535            mActivities.removeActivity(a, "activity");
6536            if (DEBUG_REMOVE && chatty) {
6537                if (r == null) {
6538                    r = new StringBuilder(256);
6539                } else {
6540                    r.append(' ');
6541                }
6542                r.append(a.info.name);
6543            }
6544        }
6545        if (r != null) {
6546            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6547        }
6548
6549        N = pkg.permissions.size();
6550        r = null;
6551        for (i=0; i<N; i++) {
6552            PackageParser.Permission p = pkg.permissions.get(i);
6553            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6554            if (bp == null) {
6555                bp = mSettings.mPermissionTrees.get(p.info.name);
6556            }
6557            if (bp != null && bp.perm == p) {
6558                bp.perm = null;
6559                if (DEBUG_REMOVE && chatty) {
6560                    if (r == null) {
6561                        r = new StringBuilder(256);
6562                    } else {
6563                        r.append(' ');
6564                    }
6565                    r.append(p.info.name);
6566                }
6567            }
6568            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6569                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6570                if (appOpPerms != null) {
6571                    appOpPerms.remove(pkg.packageName);
6572                }
6573            }
6574        }
6575        if (r != null) {
6576            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6577        }
6578
6579        N = pkg.requestedPermissions.size();
6580        r = null;
6581        for (i=0; i<N; i++) {
6582            String perm = pkg.requestedPermissions.get(i);
6583            BasePermission bp = mSettings.mPermissions.get(perm);
6584            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6585                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6586                if (appOpPerms != null) {
6587                    appOpPerms.remove(pkg.packageName);
6588                    if (appOpPerms.isEmpty()) {
6589                        mAppOpPermissionPackages.remove(perm);
6590                    }
6591                }
6592            }
6593        }
6594        if (r != null) {
6595            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6596        }
6597
6598        N = pkg.instrumentation.size();
6599        r = null;
6600        for (i=0; i<N; i++) {
6601            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6602            mInstrumentation.remove(a.getComponentName());
6603            if (DEBUG_REMOVE && chatty) {
6604                if (r == null) {
6605                    r = new StringBuilder(256);
6606                } else {
6607                    r.append(' ');
6608                }
6609                r.append(a.info.name);
6610            }
6611        }
6612        if (r != null) {
6613            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6614        }
6615
6616        r = null;
6617        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6618            // Only system apps can hold shared libraries.
6619            if (pkg.libraryNames != null) {
6620                for (i=0; i<pkg.libraryNames.size(); i++) {
6621                    String name = pkg.libraryNames.get(i);
6622                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6623                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6624                        mSharedLibraries.remove(name);
6625                        if (DEBUG_REMOVE && chatty) {
6626                            if (r == null) {
6627                                r = new StringBuilder(256);
6628                            } else {
6629                                r.append(' ');
6630                            }
6631                            r.append(name);
6632                        }
6633                    }
6634                }
6635            }
6636        }
6637        if (r != null) {
6638            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6639        }
6640    }
6641
6642    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6643        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6644            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6645                return true;
6646            }
6647        }
6648        return false;
6649    }
6650
6651    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6652    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6653    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6654
6655    private void updatePermissionsLPw(String changingPkg,
6656            PackageParser.Package pkgInfo, int flags) {
6657        // Make sure there are no dangling permission trees.
6658        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6659        while (it.hasNext()) {
6660            final BasePermission bp = it.next();
6661            if (bp.packageSetting == null) {
6662                // We may not yet have parsed the package, so just see if
6663                // we still know about its settings.
6664                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6665            }
6666            if (bp.packageSetting == null) {
6667                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6668                        + " from package " + bp.sourcePackage);
6669                it.remove();
6670            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6671                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6672                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6673                            + " from package " + bp.sourcePackage);
6674                    flags |= UPDATE_PERMISSIONS_ALL;
6675                    it.remove();
6676                }
6677            }
6678        }
6679
6680        // Make sure all dynamic permissions have been assigned to a package,
6681        // and make sure there are no dangling permissions.
6682        it = mSettings.mPermissions.values().iterator();
6683        while (it.hasNext()) {
6684            final BasePermission bp = it.next();
6685            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6686                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6687                        + bp.name + " pkg=" + bp.sourcePackage
6688                        + " info=" + bp.pendingInfo);
6689                if (bp.packageSetting == null && bp.pendingInfo != null) {
6690                    final BasePermission tree = findPermissionTreeLP(bp.name);
6691                    if (tree != null && tree.perm != null) {
6692                        bp.packageSetting = tree.packageSetting;
6693                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6694                                new PermissionInfo(bp.pendingInfo));
6695                        bp.perm.info.packageName = tree.perm.info.packageName;
6696                        bp.perm.info.name = bp.name;
6697                        bp.uid = tree.uid;
6698                    }
6699                }
6700            }
6701            if (bp.packageSetting == null) {
6702                // We may not yet have parsed the package, so just see if
6703                // we still know about its settings.
6704                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6705            }
6706            if (bp.packageSetting == null) {
6707                Slog.w(TAG, "Removing dangling permission: " + bp.name
6708                        + " from package " + bp.sourcePackage);
6709                it.remove();
6710            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6711                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6712                    Slog.i(TAG, "Removing old permission: " + bp.name
6713                            + " from package " + bp.sourcePackage);
6714                    flags |= UPDATE_PERMISSIONS_ALL;
6715                    it.remove();
6716                }
6717            }
6718        }
6719
6720        // Now update the permissions for all packages, in particular
6721        // replace the granted permissions of the system packages.
6722        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6723            for (PackageParser.Package pkg : mPackages.values()) {
6724                if (pkg != pkgInfo) {
6725                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6726                            changingPkg);
6727                }
6728            }
6729        }
6730
6731        if (pkgInfo != null) {
6732            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6733        }
6734    }
6735
6736    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6737            String packageOfInterest) {
6738        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6739        if (ps == null) {
6740            return;
6741        }
6742        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6743        HashSet<String> origPermissions = gp.grantedPermissions;
6744        boolean changedPermission = false;
6745
6746        if (replace) {
6747            ps.permissionsFixed = false;
6748            if (gp == ps) {
6749                origPermissions = new HashSet<String>(gp.grantedPermissions);
6750                gp.grantedPermissions.clear();
6751                gp.gids = mGlobalGids;
6752            }
6753        }
6754
6755        if (gp.gids == null) {
6756            gp.gids = mGlobalGids;
6757        }
6758
6759        final int N = pkg.requestedPermissions.size();
6760        for (int i=0; i<N; i++) {
6761            final String name = pkg.requestedPermissions.get(i);
6762            final boolean required = pkg.requestedPermissionsRequired.get(i);
6763            final BasePermission bp = mSettings.mPermissions.get(name);
6764            if (DEBUG_INSTALL) {
6765                if (gp != ps) {
6766                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6767                }
6768            }
6769
6770            if (bp == null || bp.packageSetting == null) {
6771                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6772                    Slog.w(TAG, "Unknown permission " + name
6773                            + " in package " + pkg.packageName);
6774                }
6775                continue;
6776            }
6777
6778            final String perm = bp.name;
6779            boolean allowed;
6780            boolean allowedSig = false;
6781            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6782                // Keep track of app op permissions.
6783                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6784                if (pkgs == null) {
6785                    pkgs = new ArraySet<>();
6786                    mAppOpPermissionPackages.put(bp.name, pkgs);
6787                }
6788                pkgs.add(pkg.packageName);
6789            }
6790            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6791            if (level == PermissionInfo.PROTECTION_NORMAL
6792                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6793                // We grant a normal or dangerous permission if any of the following
6794                // are true:
6795                // 1) The permission is required
6796                // 2) The permission is optional, but was granted in the past
6797                // 3) The permission is optional, but was requested by an
6798                //    app in /system (not /data)
6799                //
6800                // Otherwise, reject the permission.
6801                allowed = (required || origPermissions.contains(perm)
6802                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6803            } else if (bp.packageSetting == null) {
6804                // This permission is invalid; skip it.
6805                allowed = false;
6806            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6807                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6808                if (allowed) {
6809                    allowedSig = true;
6810                }
6811            } else {
6812                allowed = false;
6813            }
6814            if (DEBUG_INSTALL) {
6815                if (gp != ps) {
6816                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6817                }
6818            }
6819            if (allowed) {
6820                if (!isSystemApp(ps) && ps.permissionsFixed) {
6821                    // If this is an existing, non-system package, then
6822                    // we can't add any new permissions to it.
6823                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
6824                        // Except...  if this is a permission that was added
6825                        // to the platform (note: need to only do this when
6826                        // updating the platform).
6827                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
6828                    }
6829                }
6830                if (allowed) {
6831                    if (!gp.grantedPermissions.contains(perm)) {
6832                        changedPermission = true;
6833                        gp.grantedPermissions.add(perm);
6834                        gp.gids = appendInts(gp.gids, bp.gids);
6835                    } else if (!ps.haveGids) {
6836                        gp.gids = appendInts(gp.gids, bp.gids);
6837                    }
6838                } else {
6839                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6840                        Slog.w(TAG, "Not granting permission " + perm
6841                                + " to package " + pkg.packageName
6842                                + " because it was previously installed without");
6843                    }
6844                }
6845            } else {
6846                if (gp.grantedPermissions.remove(perm)) {
6847                    changedPermission = true;
6848                    gp.gids = removeInts(gp.gids, bp.gids);
6849                    Slog.i(TAG, "Un-granting permission " + perm
6850                            + " from package " + pkg.packageName
6851                            + " (protectionLevel=" + bp.protectionLevel
6852                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6853                            + ")");
6854                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
6855                    // Don't print warning for app op permissions, since it is fine for them
6856                    // not to be granted, there is a UI for the user to decide.
6857                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6858                        Slog.w(TAG, "Not granting permission " + perm
6859                                + " to package " + pkg.packageName
6860                                + " (protectionLevel=" + bp.protectionLevel
6861                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
6862                                + ")");
6863                    }
6864                }
6865            }
6866        }
6867
6868        if ((changedPermission || replace) && !ps.permissionsFixed &&
6869                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
6870            // This is the first that we have heard about this package, so the
6871            // permissions we have now selected are fixed until explicitly
6872            // changed.
6873            ps.permissionsFixed = true;
6874        }
6875        ps.haveGids = true;
6876    }
6877
6878    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
6879        boolean allowed = false;
6880        final int NP = PackageParser.NEW_PERMISSIONS.length;
6881        for (int ip=0; ip<NP; ip++) {
6882            final PackageParser.NewPermissionInfo npi
6883                    = PackageParser.NEW_PERMISSIONS[ip];
6884            if (npi.name.equals(perm)
6885                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
6886                allowed = true;
6887                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
6888                        + pkg.packageName);
6889                break;
6890            }
6891        }
6892        return allowed;
6893    }
6894
6895    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
6896                                          BasePermission bp, HashSet<String> origPermissions) {
6897        boolean allowed;
6898        allowed = (compareSignatures(
6899                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
6900                        == PackageManager.SIGNATURE_MATCH)
6901                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
6902                        == PackageManager.SIGNATURE_MATCH);
6903        if (!allowed && (bp.protectionLevel
6904                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
6905            if (isSystemApp(pkg)) {
6906                // For updated system applications, a system permission
6907                // is granted only if it had been defined by the original application.
6908                if (isUpdatedSystemApp(pkg)) {
6909                    final PackageSetting sysPs = mSettings
6910                            .getDisabledSystemPkgLPr(pkg.packageName);
6911                    final GrantedPermissions origGp = sysPs.sharedUser != null
6912                            ? sysPs.sharedUser : sysPs;
6913
6914                    if (origGp.grantedPermissions.contains(perm)) {
6915                        // If the original was granted this permission, we take
6916                        // that grant decision as read and propagate it to the
6917                        // update.
6918                        allowed = true;
6919                    } else {
6920                        // The system apk may have been updated with an older
6921                        // version of the one on the data partition, but which
6922                        // granted a new system permission that it didn't have
6923                        // before.  In this case we do want to allow the app to
6924                        // now get the new permission if the ancestral apk is
6925                        // privileged to get it.
6926                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
6927                            for (int j=0;
6928                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
6929                                if (perm.equals(
6930                                        sysPs.pkg.requestedPermissions.get(j))) {
6931                                    allowed = true;
6932                                    break;
6933                                }
6934                            }
6935                        }
6936                    }
6937                } else {
6938                    allowed = isPrivilegedApp(pkg);
6939                }
6940            }
6941        }
6942        if (!allowed && (bp.protectionLevel
6943                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
6944            // For development permissions, a development permission
6945            // is granted only if it was already granted.
6946            allowed = origPermissions.contains(perm);
6947        }
6948        return allowed;
6949    }
6950
6951    final class ActivityIntentResolver
6952            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
6953        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
6954                boolean defaultOnly, int userId) {
6955            if (!sUserManager.exists(userId)) return null;
6956            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
6957            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
6958        }
6959
6960        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
6961                int userId) {
6962            if (!sUserManager.exists(userId)) return null;
6963            mFlags = flags;
6964            return super.queryIntent(intent, resolvedType,
6965                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
6966        }
6967
6968        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
6969                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
6970            if (!sUserManager.exists(userId)) return null;
6971            if (packageActivities == null) {
6972                return null;
6973            }
6974            mFlags = flags;
6975            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
6976            final int N = packageActivities.size();
6977            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
6978                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
6979
6980            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
6981            for (int i = 0; i < N; ++i) {
6982                intentFilters = packageActivities.get(i).intents;
6983                if (intentFilters != null && intentFilters.size() > 0) {
6984                    PackageParser.ActivityIntentInfo[] array =
6985                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
6986                    intentFilters.toArray(array);
6987                    listCut.add(array);
6988                }
6989            }
6990            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
6991        }
6992
6993        public final void addActivity(PackageParser.Activity a, String type) {
6994            final boolean systemApp = isSystemApp(a.info.applicationInfo);
6995            mActivities.put(a.getComponentName(), a);
6996            if (DEBUG_SHOW_INFO)
6997                Log.v(
6998                TAG, "  " + type + " " +
6999                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7000            if (DEBUG_SHOW_INFO)
7001                Log.v(TAG, "    Class=" + a.info.name);
7002            final int NI = a.intents.size();
7003            for (int j=0; j<NI; j++) {
7004                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7005                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7006                    intent.setPriority(0);
7007                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7008                            + a.className + " with priority > 0, forcing to 0");
7009                }
7010                if (DEBUG_SHOW_INFO) {
7011                    Log.v(TAG, "    IntentFilter:");
7012                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7013                }
7014                if (!intent.debugCheck()) {
7015                    Log.w(TAG, "==> For Activity " + a.info.name);
7016                }
7017                addFilter(intent);
7018            }
7019        }
7020
7021        public final void removeActivity(PackageParser.Activity a, String type) {
7022            mActivities.remove(a.getComponentName());
7023            if (DEBUG_SHOW_INFO) {
7024                Log.v(TAG, "  " + type + " "
7025                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7026                                : a.info.name) + ":");
7027                Log.v(TAG, "    Class=" + a.info.name);
7028            }
7029            final int NI = a.intents.size();
7030            for (int j=0; j<NI; j++) {
7031                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7032                if (DEBUG_SHOW_INFO) {
7033                    Log.v(TAG, "    IntentFilter:");
7034                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7035                }
7036                removeFilter(intent);
7037            }
7038        }
7039
7040        @Override
7041        protected boolean allowFilterResult(
7042                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7043            ActivityInfo filterAi = filter.activity.info;
7044            for (int i=dest.size()-1; i>=0; i--) {
7045                ActivityInfo destAi = dest.get(i).activityInfo;
7046                if (destAi.name == filterAi.name
7047                        && destAi.packageName == filterAi.packageName) {
7048                    return false;
7049                }
7050            }
7051            return true;
7052        }
7053
7054        @Override
7055        protected ActivityIntentInfo[] newArray(int size) {
7056            return new ActivityIntentInfo[size];
7057        }
7058
7059        @Override
7060        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7061            if (!sUserManager.exists(userId)) return true;
7062            PackageParser.Package p = filter.activity.owner;
7063            if (p != null) {
7064                PackageSetting ps = (PackageSetting)p.mExtras;
7065                if (ps != null) {
7066                    // System apps are never considered stopped for purposes of
7067                    // filtering, because there may be no way for the user to
7068                    // actually re-launch them.
7069                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7070                            && ps.getStopped(userId);
7071                }
7072            }
7073            return false;
7074        }
7075
7076        @Override
7077        protected boolean isPackageForFilter(String packageName,
7078                PackageParser.ActivityIntentInfo info) {
7079            return packageName.equals(info.activity.owner.packageName);
7080        }
7081
7082        @Override
7083        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7084                int match, int userId) {
7085            if (!sUserManager.exists(userId)) return null;
7086            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7087                return null;
7088            }
7089            final PackageParser.Activity activity = info.activity;
7090            if (mSafeMode && (activity.info.applicationInfo.flags
7091                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7092                return null;
7093            }
7094            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7095            if (ps == null) {
7096                return null;
7097            }
7098            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7099                    ps.readUserState(userId), userId);
7100            if (ai == null) {
7101                return null;
7102            }
7103            final ResolveInfo res = new ResolveInfo();
7104            res.activityInfo = ai;
7105            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7106                res.filter = info;
7107            }
7108            res.priority = info.getPriority();
7109            res.preferredOrder = activity.owner.mPreferredOrder;
7110            //System.out.println("Result: " + res.activityInfo.className +
7111            //                   " = " + res.priority);
7112            res.match = match;
7113            res.isDefault = info.hasDefault;
7114            res.labelRes = info.labelRes;
7115            res.nonLocalizedLabel = info.nonLocalizedLabel;
7116            if (userNeedsBadging(userId)) {
7117                res.noResourceId = true;
7118            } else {
7119                res.icon = info.icon;
7120            }
7121            res.system = isSystemApp(res.activityInfo.applicationInfo);
7122            return res;
7123        }
7124
7125        @Override
7126        protected void sortResults(List<ResolveInfo> results) {
7127            Collections.sort(results, mResolvePrioritySorter);
7128        }
7129
7130        @Override
7131        protected void dumpFilter(PrintWriter out, String prefix,
7132                PackageParser.ActivityIntentInfo filter) {
7133            out.print(prefix); out.print(
7134                    Integer.toHexString(System.identityHashCode(filter.activity)));
7135                    out.print(' ');
7136                    filter.activity.printComponentShortName(out);
7137                    out.print(" filter ");
7138                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7139        }
7140
7141//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7142//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7143//            final List<ResolveInfo> retList = Lists.newArrayList();
7144//            while (i.hasNext()) {
7145//                final ResolveInfo resolveInfo = i.next();
7146//                if (isEnabledLP(resolveInfo.activityInfo)) {
7147//                    retList.add(resolveInfo);
7148//                }
7149//            }
7150//            return retList;
7151//        }
7152
7153        // Keys are String (activity class name), values are Activity.
7154        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7155                = new HashMap<ComponentName, PackageParser.Activity>();
7156        private int mFlags;
7157    }
7158
7159    private final class ServiceIntentResolver
7160            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7161        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7162                boolean defaultOnly, int userId) {
7163            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7164            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7165        }
7166
7167        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7168                int userId) {
7169            if (!sUserManager.exists(userId)) return null;
7170            mFlags = flags;
7171            return super.queryIntent(intent, resolvedType,
7172                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7173        }
7174
7175        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7176                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7177            if (!sUserManager.exists(userId)) return null;
7178            if (packageServices == null) {
7179                return null;
7180            }
7181            mFlags = flags;
7182            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7183            final int N = packageServices.size();
7184            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7185                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7186
7187            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7188            for (int i = 0; i < N; ++i) {
7189                intentFilters = packageServices.get(i).intents;
7190                if (intentFilters != null && intentFilters.size() > 0) {
7191                    PackageParser.ServiceIntentInfo[] array =
7192                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7193                    intentFilters.toArray(array);
7194                    listCut.add(array);
7195                }
7196            }
7197            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7198        }
7199
7200        public final void addService(PackageParser.Service s) {
7201            mServices.put(s.getComponentName(), s);
7202            if (DEBUG_SHOW_INFO) {
7203                Log.v(TAG, "  "
7204                        + (s.info.nonLocalizedLabel != null
7205                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7206                Log.v(TAG, "    Class=" + s.info.name);
7207            }
7208            final int NI = s.intents.size();
7209            int j;
7210            for (j=0; j<NI; j++) {
7211                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7212                if (DEBUG_SHOW_INFO) {
7213                    Log.v(TAG, "    IntentFilter:");
7214                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7215                }
7216                if (!intent.debugCheck()) {
7217                    Log.w(TAG, "==> For Service " + s.info.name);
7218                }
7219                addFilter(intent);
7220            }
7221        }
7222
7223        public final void removeService(PackageParser.Service s) {
7224            mServices.remove(s.getComponentName());
7225            if (DEBUG_SHOW_INFO) {
7226                Log.v(TAG, "  " + (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                removeFilter(intent);
7239            }
7240        }
7241
7242        @Override
7243        protected boolean allowFilterResult(
7244                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7245            ServiceInfo filterSi = filter.service.info;
7246            for (int i=dest.size()-1; i>=0; i--) {
7247                ServiceInfo destAi = dest.get(i).serviceInfo;
7248                if (destAi.name == filterSi.name
7249                        && destAi.packageName == filterSi.packageName) {
7250                    return false;
7251                }
7252            }
7253            return true;
7254        }
7255
7256        @Override
7257        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7258            return new PackageParser.ServiceIntentInfo[size];
7259        }
7260
7261        @Override
7262        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7263            if (!sUserManager.exists(userId)) return true;
7264            PackageParser.Package p = filter.service.owner;
7265            if (p != null) {
7266                PackageSetting ps = (PackageSetting)p.mExtras;
7267                if (ps != null) {
7268                    // System apps are never considered stopped for purposes of
7269                    // filtering, because there may be no way for the user to
7270                    // actually re-launch them.
7271                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7272                            && ps.getStopped(userId);
7273                }
7274            }
7275            return false;
7276        }
7277
7278        @Override
7279        protected boolean isPackageForFilter(String packageName,
7280                PackageParser.ServiceIntentInfo info) {
7281            return packageName.equals(info.service.owner.packageName);
7282        }
7283
7284        @Override
7285        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7286                int match, int userId) {
7287            if (!sUserManager.exists(userId)) return null;
7288            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7289            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7290                return null;
7291            }
7292            final PackageParser.Service service = info.service;
7293            if (mSafeMode && (service.info.applicationInfo.flags
7294                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7295                return null;
7296            }
7297            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7298            if (ps == null) {
7299                return null;
7300            }
7301            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7302                    ps.readUserState(userId), userId);
7303            if (si == null) {
7304                return null;
7305            }
7306            final ResolveInfo res = new ResolveInfo();
7307            res.serviceInfo = si;
7308            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7309                res.filter = filter;
7310            }
7311            res.priority = info.getPriority();
7312            res.preferredOrder = service.owner.mPreferredOrder;
7313            //System.out.println("Result: " + res.activityInfo.className +
7314            //                   " = " + res.priority);
7315            res.match = match;
7316            res.isDefault = info.hasDefault;
7317            res.labelRes = info.labelRes;
7318            res.nonLocalizedLabel = info.nonLocalizedLabel;
7319            res.icon = info.icon;
7320            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7321            return res;
7322        }
7323
7324        @Override
7325        protected void sortResults(List<ResolveInfo> results) {
7326            Collections.sort(results, mResolvePrioritySorter);
7327        }
7328
7329        @Override
7330        protected void dumpFilter(PrintWriter out, String prefix,
7331                PackageParser.ServiceIntentInfo filter) {
7332            out.print(prefix); out.print(
7333                    Integer.toHexString(System.identityHashCode(filter.service)));
7334                    out.print(' ');
7335                    filter.service.printComponentShortName(out);
7336                    out.print(" filter ");
7337                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7338        }
7339
7340//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7341//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7342//            final List<ResolveInfo> retList = Lists.newArrayList();
7343//            while (i.hasNext()) {
7344//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7345//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7346//                    retList.add(resolveInfo);
7347//                }
7348//            }
7349//            return retList;
7350//        }
7351
7352        // Keys are String (activity class name), values are Activity.
7353        private final HashMap<ComponentName, PackageParser.Service> mServices
7354                = new HashMap<ComponentName, PackageParser.Service>();
7355        private int mFlags;
7356    };
7357
7358    private final class ProviderIntentResolver
7359            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7360        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7361                boolean defaultOnly, int userId) {
7362            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7363            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7364        }
7365
7366        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7367                int userId) {
7368            if (!sUserManager.exists(userId))
7369                return null;
7370            mFlags = flags;
7371            return super.queryIntent(intent, resolvedType,
7372                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7373        }
7374
7375        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7376                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7377            if (!sUserManager.exists(userId))
7378                return null;
7379            if (packageProviders == null) {
7380                return null;
7381            }
7382            mFlags = flags;
7383            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7384            final int N = packageProviders.size();
7385            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7386                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7387
7388            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7389            for (int i = 0; i < N; ++i) {
7390                intentFilters = packageProviders.get(i).intents;
7391                if (intentFilters != null && intentFilters.size() > 0) {
7392                    PackageParser.ProviderIntentInfo[] array =
7393                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7394                    intentFilters.toArray(array);
7395                    listCut.add(array);
7396                }
7397            }
7398            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7399        }
7400
7401        public final void addProvider(PackageParser.Provider p) {
7402            if (mProviders.containsKey(p.getComponentName())) {
7403                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7404                return;
7405            }
7406
7407            mProviders.put(p.getComponentName(), p);
7408            if (DEBUG_SHOW_INFO) {
7409                Log.v(TAG, "  "
7410                        + (p.info.nonLocalizedLabel != null
7411                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7412                Log.v(TAG, "    Class=" + p.info.name);
7413            }
7414            final int NI = p.intents.size();
7415            int j;
7416            for (j = 0; j < NI; j++) {
7417                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7418                if (DEBUG_SHOW_INFO) {
7419                    Log.v(TAG, "    IntentFilter:");
7420                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7421                }
7422                if (!intent.debugCheck()) {
7423                    Log.w(TAG, "==> For Provider " + p.info.name);
7424                }
7425                addFilter(intent);
7426            }
7427        }
7428
7429        public final void removeProvider(PackageParser.Provider p) {
7430            mProviders.remove(p.getComponentName());
7431            if (DEBUG_SHOW_INFO) {
7432                Log.v(TAG, "  " + (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                removeFilter(intent);
7445            }
7446        }
7447
7448        @Override
7449        protected boolean allowFilterResult(
7450                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7451            ProviderInfo filterPi = filter.provider.info;
7452            for (int i = dest.size() - 1; i >= 0; i--) {
7453                ProviderInfo destPi = dest.get(i).providerInfo;
7454                if (destPi.name == filterPi.name
7455                        && destPi.packageName == filterPi.packageName) {
7456                    return false;
7457                }
7458            }
7459            return true;
7460        }
7461
7462        @Override
7463        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7464            return new PackageParser.ProviderIntentInfo[size];
7465        }
7466
7467        @Override
7468        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7469            if (!sUserManager.exists(userId))
7470                return true;
7471            PackageParser.Package p = filter.provider.owner;
7472            if (p != null) {
7473                PackageSetting ps = (PackageSetting) p.mExtras;
7474                if (ps != null) {
7475                    // System apps are never considered stopped for purposes of
7476                    // filtering, because there may be no way for the user to
7477                    // actually re-launch them.
7478                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7479                            && ps.getStopped(userId);
7480                }
7481            }
7482            return false;
7483        }
7484
7485        @Override
7486        protected boolean isPackageForFilter(String packageName,
7487                PackageParser.ProviderIntentInfo info) {
7488            return packageName.equals(info.provider.owner.packageName);
7489        }
7490
7491        @Override
7492        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7493                int match, int userId) {
7494            if (!sUserManager.exists(userId))
7495                return null;
7496            final PackageParser.ProviderIntentInfo info = filter;
7497            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7498                return null;
7499            }
7500            final PackageParser.Provider provider = info.provider;
7501            if (mSafeMode && (provider.info.applicationInfo.flags
7502                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7503                return null;
7504            }
7505            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7506            if (ps == null) {
7507                return null;
7508            }
7509            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7510                    ps.readUserState(userId), userId);
7511            if (pi == null) {
7512                return null;
7513            }
7514            final ResolveInfo res = new ResolveInfo();
7515            res.providerInfo = pi;
7516            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7517                res.filter = filter;
7518            }
7519            res.priority = info.getPriority();
7520            res.preferredOrder = provider.owner.mPreferredOrder;
7521            res.match = match;
7522            res.isDefault = info.hasDefault;
7523            res.labelRes = info.labelRes;
7524            res.nonLocalizedLabel = info.nonLocalizedLabel;
7525            res.icon = info.icon;
7526            res.system = isSystemApp(res.providerInfo.applicationInfo);
7527            return res;
7528        }
7529
7530        @Override
7531        protected void sortResults(List<ResolveInfo> results) {
7532            Collections.sort(results, mResolvePrioritySorter);
7533        }
7534
7535        @Override
7536        protected void dumpFilter(PrintWriter out, String prefix,
7537                PackageParser.ProviderIntentInfo filter) {
7538            out.print(prefix);
7539            out.print(
7540                    Integer.toHexString(System.identityHashCode(filter.provider)));
7541            out.print(' ');
7542            filter.provider.printComponentShortName(out);
7543            out.print(" filter ");
7544            out.println(Integer.toHexString(System.identityHashCode(filter)));
7545        }
7546
7547        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7548                = new HashMap<ComponentName, PackageParser.Provider>();
7549        private int mFlags;
7550    };
7551
7552    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7553            new Comparator<ResolveInfo>() {
7554        public int compare(ResolveInfo r1, ResolveInfo r2) {
7555            int v1 = r1.priority;
7556            int v2 = r2.priority;
7557            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7558            if (v1 != v2) {
7559                return (v1 > v2) ? -1 : 1;
7560            }
7561            v1 = r1.preferredOrder;
7562            v2 = r2.preferredOrder;
7563            if (v1 != v2) {
7564                return (v1 > v2) ? -1 : 1;
7565            }
7566            if (r1.isDefault != r2.isDefault) {
7567                return r1.isDefault ? -1 : 1;
7568            }
7569            v1 = r1.match;
7570            v2 = r2.match;
7571            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7572            if (v1 != v2) {
7573                return (v1 > v2) ? -1 : 1;
7574            }
7575            if (r1.system != r2.system) {
7576                return r1.system ? -1 : 1;
7577            }
7578            return 0;
7579        }
7580    };
7581
7582    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7583            new Comparator<ProviderInfo>() {
7584        public int compare(ProviderInfo p1, ProviderInfo p2) {
7585            final int v1 = p1.initOrder;
7586            final int v2 = p2.initOrder;
7587            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7588        }
7589    };
7590
7591    static final void sendPackageBroadcast(String action, String pkg,
7592            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7593            int[] userIds) {
7594        IActivityManager am = ActivityManagerNative.getDefault();
7595        if (am != null) {
7596            try {
7597                if (userIds == null) {
7598                    userIds = am.getRunningUserIds();
7599                }
7600                for (int id : userIds) {
7601                    final Intent intent = new Intent(action,
7602                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7603                    if (extras != null) {
7604                        intent.putExtras(extras);
7605                    }
7606                    if (targetPkg != null) {
7607                        intent.setPackage(targetPkg);
7608                    }
7609                    // Modify the UID when posting to other users
7610                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7611                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7612                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7613                        intent.putExtra(Intent.EXTRA_UID, uid);
7614                    }
7615                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7616                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7617                    if (DEBUG_BROADCASTS) {
7618                        RuntimeException here = new RuntimeException("here");
7619                        here.fillInStackTrace();
7620                        Slog.d(TAG, "Sending to user " + id + ": "
7621                                + intent.toShortString(false, true, false, false)
7622                                + " " + intent.getExtras(), here);
7623                    }
7624                    am.broadcastIntent(null, intent, null, finishedReceiver,
7625                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7626                            finishedReceiver != null, false, id);
7627                }
7628            } catch (RemoteException ex) {
7629            }
7630        }
7631    }
7632
7633    /**
7634     * Check if the external storage media is available. This is true if there
7635     * is a mounted external storage medium or if the external storage is
7636     * emulated.
7637     */
7638    private boolean isExternalMediaAvailable() {
7639        return mMediaMounted || Environment.isExternalStorageEmulated();
7640    }
7641
7642    @Override
7643    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7644        // writer
7645        synchronized (mPackages) {
7646            if (!isExternalMediaAvailable()) {
7647                // If the external storage is no longer mounted at this point,
7648                // the caller may not have been able to delete all of this
7649                // packages files and can not delete any more.  Bail.
7650                return null;
7651            }
7652            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7653            if (lastPackage != null) {
7654                pkgs.remove(lastPackage);
7655            }
7656            if (pkgs.size() > 0) {
7657                return pkgs.get(0);
7658            }
7659        }
7660        return null;
7661    }
7662
7663    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7664        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7665                userId, andCode ? 1 : 0, packageName);
7666        if (mSystemReady) {
7667            msg.sendToTarget();
7668        } else {
7669            if (mPostSystemReadyMessages == null) {
7670                mPostSystemReadyMessages = new ArrayList<>();
7671            }
7672            mPostSystemReadyMessages.add(msg);
7673        }
7674    }
7675
7676    void startCleaningPackages() {
7677        // reader
7678        synchronized (mPackages) {
7679            if (!isExternalMediaAvailable()) {
7680                return;
7681            }
7682            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7683                return;
7684            }
7685        }
7686        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7687        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7688        IActivityManager am = ActivityManagerNative.getDefault();
7689        if (am != null) {
7690            try {
7691                am.startService(null, intent, null, UserHandle.USER_OWNER);
7692            } catch (RemoteException e) {
7693            }
7694        }
7695    }
7696
7697    @Override
7698    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7699            int installFlags, String installerPackageName, VerificationParams verificationParams,
7700            String packageAbiOverride) {
7701        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7702                packageAbiOverride, UserHandle.getCallingUserId());
7703    }
7704
7705    @Override
7706    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7707            int installFlags, String installerPackageName, VerificationParams verificationParams,
7708            String packageAbiOverride, int userId) {
7709        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
7710
7711        final int callingUid = Binder.getCallingUid();
7712        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
7713
7714        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7715            try {
7716                if (observer != null) {
7717                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7718                }
7719            } catch (RemoteException re) {
7720            }
7721            return;
7722        }
7723
7724        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
7725            installFlags |= PackageManager.INSTALL_FROM_ADB;
7726
7727        } else {
7728            // Caller holds INSTALL_PACKAGES permission, so we're less strict
7729            // about installerPackageName.
7730
7731            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
7732            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
7733        }
7734
7735        UserHandle user;
7736        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7737            user = UserHandle.ALL;
7738        } else {
7739            user = new UserHandle(userId);
7740        }
7741
7742        verificationParams.setInstallerUid(callingUid);
7743
7744        final File originFile = new File(originPath);
7745        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7746
7747        final Message msg = mHandler.obtainMessage(INIT_COPY);
7748        msg.obj = new InstallParams(origin, observer, installFlags,
7749                installerPackageName, verificationParams, user, packageAbiOverride);
7750        mHandler.sendMessage(msg);
7751    }
7752
7753    void installStage(String packageName, File stagedDir, String stagedCid,
7754            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7755            String installerPackageName, int installerUid, UserHandle user) {
7756        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7757                params.referrerUri, installerUid, null);
7758
7759        final OriginInfo origin;
7760        if (stagedDir != null) {
7761            origin = OriginInfo.fromStagedFile(stagedDir);
7762        } else {
7763            origin = OriginInfo.fromStagedContainer(stagedCid);
7764        }
7765
7766        final Message msg = mHandler.obtainMessage(INIT_COPY);
7767        msg.obj = new InstallParams(origin, observer, params.installFlags,
7768                installerPackageName, verifParams, user, params.abiOverride);
7769        mHandler.sendMessage(msg);
7770    }
7771
7772    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7773        Bundle extras = new Bundle(1);
7774        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7775
7776        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7777                packageName, extras, null, null, new int[] {userId});
7778        try {
7779            IActivityManager am = ActivityManagerNative.getDefault();
7780            final boolean isSystem =
7781                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7782            if (isSystem && am.isUserRunning(userId, false)) {
7783                // The just-installed/enabled app is bundled on the system, so presumed
7784                // to be able to run automatically without needing an explicit launch.
7785                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7786                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7787                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7788                        .setPackage(packageName);
7789                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7790                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7791            }
7792        } catch (RemoteException e) {
7793            // shouldn't happen
7794            Slog.w(TAG, "Unable to bootstrap installed package", e);
7795        }
7796    }
7797
7798    @Override
7799    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7800            int userId) {
7801        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7802        PackageSetting pkgSetting;
7803        final int uid = Binder.getCallingUid();
7804        enforceCrossUserPermission(uid, userId, true, true,
7805                "setApplicationHiddenSetting for user " + userId);
7806
7807        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7808            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7809            return false;
7810        }
7811
7812        long callingId = Binder.clearCallingIdentity();
7813        try {
7814            boolean sendAdded = false;
7815            boolean sendRemoved = false;
7816            // writer
7817            synchronized (mPackages) {
7818                pkgSetting = mSettings.mPackages.get(packageName);
7819                if (pkgSetting == null) {
7820                    return false;
7821                }
7822                if (pkgSetting.getHidden(userId) != hidden) {
7823                    pkgSetting.setHidden(hidden, userId);
7824                    mSettings.writePackageRestrictionsLPr(userId);
7825                    if (hidden) {
7826                        sendRemoved = true;
7827                    } else {
7828                        sendAdded = true;
7829                    }
7830                }
7831            }
7832            if (sendAdded) {
7833                sendPackageAddedForUser(packageName, pkgSetting, userId);
7834                return true;
7835            }
7836            if (sendRemoved) {
7837                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
7838                        "hiding pkg");
7839                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
7840            }
7841        } finally {
7842            Binder.restoreCallingIdentity(callingId);
7843        }
7844        return false;
7845    }
7846
7847    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
7848            int userId) {
7849        final PackageRemovedInfo info = new PackageRemovedInfo();
7850        info.removedPackage = packageName;
7851        info.removedUsers = new int[] {userId};
7852        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
7853        info.sendBroadcast(false, false, false);
7854    }
7855
7856    /**
7857     * Returns true if application is not found or there was an error. Otherwise it returns
7858     * the hidden state of the package for the given user.
7859     */
7860    @Override
7861    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
7862        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7863        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
7864                false, "getApplicationHidden for user " + userId);
7865        PackageSetting pkgSetting;
7866        long callingId = Binder.clearCallingIdentity();
7867        try {
7868            // writer
7869            synchronized (mPackages) {
7870                pkgSetting = mSettings.mPackages.get(packageName);
7871                if (pkgSetting == null) {
7872                    return true;
7873                }
7874                return pkgSetting.getHidden(userId);
7875            }
7876        } finally {
7877            Binder.restoreCallingIdentity(callingId);
7878        }
7879    }
7880
7881    /**
7882     * @hide
7883     */
7884    @Override
7885    public int installExistingPackageAsUser(String packageName, int userId) {
7886        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
7887                null);
7888        PackageSetting pkgSetting;
7889        final int uid = Binder.getCallingUid();
7890        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
7891                + userId);
7892        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7893            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
7894        }
7895
7896        long callingId = Binder.clearCallingIdentity();
7897        try {
7898            boolean sendAdded = false;
7899            Bundle extras = new Bundle(1);
7900
7901            // writer
7902            synchronized (mPackages) {
7903                pkgSetting = mSettings.mPackages.get(packageName);
7904                if (pkgSetting == null) {
7905                    return PackageManager.INSTALL_FAILED_INVALID_URI;
7906                }
7907                if (!pkgSetting.getInstalled(userId)) {
7908                    pkgSetting.setInstalled(true, userId);
7909                    pkgSetting.setHidden(false, userId);
7910                    mSettings.writePackageRestrictionsLPr(userId);
7911                    sendAdded = true;
7912                }
7913            }
7914
7915            if (sendAdded) {
7916                sendPackageAddedForUser(packageName, pkgSetting, userId);
7917            }
7918        } finally {
7919            Binder.restoreCallingIdentity(callingId);
7920        }
7921
7922        return PackageManager.INSTALL_SUCCEEDED;
7923    }
7924
7925    boolean isUserRestricted(int userId, String restrictionKey) {
7926        Bundle restrictions = sUserManager.getUserRestrictions(userId);
7927        if (restrictions.getBoolean(restrictionKey, false)) {
7928            Log.w(TAG, "User is restricted: " + restrictionKey);
7929            return true;
7930        }
7931        return false;
7932    }
7933
7934    @Override
7935    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
7936        mContext.enforceCallingOrSelfPermission(
7937                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7938                "Only package verification agents can verify applications");
7939
7940        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7941        final PackageVerificationResponse response = new PackageVerificationResponse(
7942                verificationCode, Binder.getCallingUid());
7943        msg.arg1 = id;
7944        msg.obj = response;
7945        mHandler.sendMessage(msg);
7946    }
7947
7948    @Override
7949    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
7950            long millisecondsToDelay) {
7951        mContext.enforceCallingOrSelfPermission(
7952                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
7953                "Only package verification agents can extend verification timeouts");
7954
7955        final PackageVerificationState state = mPendingVerification.get(id);
7956        final PackageVerificationResponse response = new PackageVerificationResponse(
7957                verificationCodeAtTimeout, Binder.getCallingUid());
7958
7959        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
7960            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
7961        }
7962        if (millisecondsToDelay < 0) {
7963            millisecondsToDelay = 0;
7964        }
7965        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
7966                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
7967            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
7968        }
7969
7970        if ((state != null) && !state.timeoutExtended()) {
7971            state.extendTimeout();
7972
7973            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
7974            msg.arg1 = id;
7975            msg.obj = response;
7976            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
7977        }
7978    }
7979
7980    private void broadcastPackageVerified(int verificationId, Uri packageUri,
7981            int verificationCode, UserHandle user) {
7982        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
7983        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
7984        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
7985        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
7986        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
7987
7988        mContext.sendBroadcastAsUser(intent, user,
7989                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
7990    }
7991
7992    private ComponentName matchComponentForVerifier(String packageName,
7993            List<ResolveInfo> receivers) {
7994        ActivityInfo targetReceiver = null;
7995
7996        final int NR = receivers.size();
7997        for (int i = 0; i < NR; i++) {
7998            final ResolveInfo info = receivers.get(i);
7999            if (info.activityInfo == null) {
8000                continue;
8001            }
8002
8003            if (packageName.equals(info.activityInfo.packageName)) {
8004                targetReceiver = info.activityInfo;
8005                break;
8006            }
8007        }
8008
8009        if (targetReceiver == null) {
8010            return null;
8011        }
8012
8013        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8014    }
8015
8016    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8017            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8018        if (pkgInfo.verifiers.length == 0) {
8019            return null;
8020        }
8021
8022        final int N = pkgInfo.verifiers.length;
8023        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8024        for (int i = 0; i < N; i++) {
8025            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8026
8027            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8028                    receivers);
8029            if (comp == null) {
8030                continue;
8031            }
8032
8033            final int verifierUid = getUidForVerifier(verifierInfo);
8034            if (verifierUid == -1) {
8035                continue;
8036            }
8037
8038            if (DEBUG_VERIFY) {
8039                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8040                        + " with the correct signature");
8041            }
8042            sufficientVerifiers.add(comp);
8043            verificationState.addSufficientVerifier(verifierUid);
8044        }
8045
8046        return sufficientVerifiers;
8047    }
8048
8049    private int getUidForVerifier(VerifierInfo verifierInfo) {
8050        synchronized (mPackages) {
8051            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8052            if (pkg == null) {
8053                return -1;
8054            } else if (pkg.mSignatures.length != 1) {
8055                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8056                        + " has more than one signature; ignoring");
8057                return -1;
8058            }
8059
8060            /*
8061             * If the public key of the package's signature does not match
8062             * our expected public key, then this is a different package and
8063             * we should skip.
8064             */
8065
8066            final byte[] expectedPublicKey;
8067            try {
8068                final Signature verifierSig = pkg.mSignatures[0];
8069                final PublicKey publicKey = verifierSig.getPublicKey();
8070                expectedPublicKey = publicKey.getEncoded();
8071            } catch (CertificateException e) {
8072                return -1;
8073            }
8074
8075            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8076
8077            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8078                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8079                        + " does not have the expected public key; ignoring");
8080                return -1;
8081            }
8082
8083            return pkg.applicationInfo.uid;
8084        }
8085    }
8086
8087    @Override
8088    public void finishPackageInstall(int token) {
8089        enforceSystemOrRoot("Only the system is allowed to finish installs");
8090
8091        if (DEBUG_INSTALL) {
8092            Slog.v(TAG, "BM finishing package install for " + token);
8093        }
8094
8095        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8096        mHandler.sendMessage(msg);
8097    }
8098
8099    /**
8100     * Get the verification agent timeout.
8101     *
8102     * @return verification timeout in milliseconds
8103     */
8104    private long getVerificationTimeout() {
8105        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8106                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8107                DEFAULT_VERIFICATION_TIMEOUT);
8108    }
8109
8110    /**
8111     * Get the default verification agent response code.
8112     *
8113     * @return default verification response code
8114     */
8115    private int getDefaultVerificationResponse() {
8116        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8117                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8118                DEFAULT_VERIFICATION_RESPONSE);
8119    }
8120
8121    /**
8122     * Check whether or not package verification has been enabled.
8123     *
8124     * @return true if verification should be performed
8125     */
8126    private boolean isVerificationEnabled(int userId, int installFlags) {
8127        if (!DEFAULT_VERIFY_ENABLE) {
8128            return false;
8129        }
8130
8131        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8132
8133        // Check if installing from ADB
8134        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8135            // Do not run verification in a test harness environment
8136            if (ActivityManager.isRunningInTestHarness()) {
8137                return false;
8138            }
8139            if (ensureVerifyAppsEnabled) {
8140                return true;
8141            }
8142            // Check if the developer does not want package verification for ADB installs
8143            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8144                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8145                return false;
8146            }
8147        }
8148
8149        if (ensureVerifyAppsEnabled) {
8150            return true;
8151        }
8152
8153        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8154                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8155    }
8156
8157    /**
8158     * Get the "allow unknown sources" setting.
8159     *
8160     * @return the current "allow unknown sources" setting
8161     */
8162    private int getUnknownSourcesSettings() {
8163        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8164                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8165                -1);
8166    }
8167
8168    @Override
8169    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8170        final int uid = Binder.getCallingUid();
8171        // writer
8172        synchronized (mPackages) {
8173            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8174            if (targetPackageSetting == null) {
8175                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8176            }
8177
8178            PackageSetting installerPackageSetting;
8179            if (installerPackageName != null) {
8180                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8181                if (installerPackageSetting == null) {
8182                    throw new IllegalArgumentException("Unknown installer package: "
8183                            + installerPackageName);
8184                }
8185            } else {
8186                installerPackageSetting = null;
8187            }
8188
8189            Signature[] callerSignature;
8190            Object obj = mSettings.getUserIdLPr(uid);
8191            if (obj != null) {
8192                if (obj instanceof SharedUserSetting) {
8193                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8194                } else if (obj instanceof PackageSetting) {
8195                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8196                } else {
8197                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8198                }
8199            } else {
8200                throw new SecurityException("Unknown calling uid " + uid);
8201            }
8202
8203            // Verify: can't set installerPackageName to a package that is
8204            // not signed with the same cert as the caller.
8205            if (installerPackageSetting != null) {
8206                if (compareSignatures(callerSignature,
8207                        installerPackageSetting.signatures.mSignatures)
8208                        != PackageManager.SIGNATURE_MATCH) {
8209                    throw new SecurityException(
8210                            "Caller does not have same cert as new installer package "
8211                            + installerPackageName);
8212                }
8213            }
8214
8215            // Verify: if target already has an installer package, it must
8216            // be signed with the same cert as the caller.
8217            if (targetPackageSetting.installerPackageName != null) {
8218                PackageSetting setting = mSettings.mPackages.get(
8219                        targetPackageSetting.installerPackageName);
8220                // If the currently set package isn't valid, then it's always
8221                // okay to change it.
8222                if (setting != null) {
8223                    if (compareSignatures(callerSignature,
8224                            setting.signatures.mSignatures)
8225                            != PackageManager.SIGNATURE_MATCH) {
8226                        throw new SecurityException(
8227                                "Caller does not have same cert as old installer package "
8228                                + targetPackageSetting.installerPackageName);
8229                    }
8230                }
8231            }
8232
8233            // Okay!
8234            targetPackageSetting.installerPackageName = installerPackageName;
8235            scheduleWriteSettingsLocked();
8236        }
8237    }
8238
8239    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8240        // Queue up an async operation since the package installation may take a little while.
8241        mHandler.post(new Runnable() {
8242            public void run() {
8243                mHandler.removeCallbacks(this);
8244                 // Result object to be returned
8245                PackageInstalledInfo res = new PackageInstalledInfo();
8246                res.returnCode = currentStatus;
8247                res.uid = -1;
8248                res.pkg = null;
8249                res.removedInfo = new PackageRemovedInfo();
8250                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8251                    args.doPreInstall(res.returnCode);
8252                    synchronized (mInstallLock) {
8253                        installPackageLI(args, res);
8254                    }
8255                    args.doPostInstall(res.returnCode, res.uid);
8256                }
8257
8258                // A restore should be performed at this point if (a) the install
8259                // succeeded, (b) the operation is not an update, and (c) the new
8260                // package has not opted out of backup participation.
8261                final boolean update = res.removedInfo.removedPackage != null;
8262                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8263                boolean doRestore = !update
8264                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8265
8266                // Set up the post-install work request bookkeeping.  This will be used
8267                // and cleaned up by the post-install event handling regardless of whether
8268                // there's a restore pass performed.  Token values are >= 1.
8269                int token;
8270                if (mNextInstallToken < 0) mNextInstallToken = 1;
8271                token = mNextInstallToken++;
8272
8273                PostInstallData data = new PostInstallData(args, res);
8274                mRunningInstalls.put(token, data);
8275                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8276
8277                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8278                    // Pass responsibility to the Backup Manager.  It will perform a
8279                    // restore if appropriate, then pass responsibility back to the
8280                    // Package Manager to run the post-install observer callbacks
8281                    // and broadcasts.
8282                    IBackupManager bm = IBackupManager.Stub.asInterface(
8283                            ServiceManager.getService(Context.BACKUP_SERVICE));
8284                    if (bm != null) {
8285                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8286                                + " to BM for possible restore");
8287                        try {
8288                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8289                        } catch (RemoteException e) {
8290                            // can't happen; the backup manager is local
8291                        } catch (Exception e) {
8292                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8293                            doRestore = false;
8294                        }
8295                    } else {
8296                        Slog.e(TAG, "Backup Manager not found!");
8297                        doRestore = false;
8298                    }
8299                }
8300
8301                if (!doRestore) {
8302                    // No restore possible, or the Backup Manager was mysteriously not
8303                    // available -- just fire the post-install work request directly.
8304                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8305                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8306                    mHandler.sendMessage(msg);
8307                }
8308            }
8309        });
8310    }
8311
8312    private abstract class HandlerParams {
8313        private static final int MAX_RETRIES = 4;
8314
8315        /**
8316         * Number of times startCopy() has been attempted and had a non-fatal
8317         * error.
8318         */
8319        private int mRetries = 0;
8320
8321        /** User handle for the user requesting the information or installation. */
8322        private final UserHandle mUser;
8323
8324        HandlerParams(UserHandle user) {
8325            mUser = user;
8326        }
8327
8328        UserHandle getUser() {
8329            return mUser;
8330        }
8331
8332        final boolean startCopy() {
8333            boolean res;
8334            try {
8335                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8336
8337                if (++mRetries > MAX_RETRIES) {
8338                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8339                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8340                    handleServiceError();
8341                    return false;
8342                } else {
8343                    handleStartCopy();
8344                    res = true;
8345                }
8346            } catch (RemoteException e) {
8347                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8348                mHandler.sendEmptyMessage(MCS_RECONNECT);
8349                res = false;
8350            }
8351            handleReturnCode();
8352            return res;
8353        }
8354
8355        final void serviceError() {
8356            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8357            handleServiceError();
8358            handleReturnCode();
8359        }
8360
8361        abstract void handleStartCopy() throws RemoteException;
8362        abstract void handleServiceError();
8363        abstract void handleReturnCode();
8364    }
8365
8366    class MeasureParams extends HandlerParams {
8367        private final PackageStats mStats;
8368        private boolean mSuccess;
8369
8370        private final IPackageStatsObserver mObserver;
8371
8372        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8373            super(new UserHandle(stats.userHandle));
8374            mObserver = observer;
8375            mStats = stats;
8376        }
8377
8378        @Override
8379        public String toString() {
8380            return "MeasureParams{"
8381                + Integer.toHexString(System.identityHashCode(this))
8382                + " " + mStats.packageName + "}";
8383        }
8384
8385        @Override
8386        void handleStartCopy() throws RemoteException {
8387            synchronized (mInstallLock) {
8388                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8389            }
8390
8391            if (mSuccess) {
8392                final boolean mounted;
8393                if (Environment.isExternalStorageEmulated()) {
8394                    mounted = true;
8395                } else {
8396                    final String status = Environment.getExternalStorageState();
8397                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8398                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8399                }
8400
8401                if (mounted) {
8402                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8403
8404                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8405                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8406
8407                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8408                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8409
8410                    // Always subtract cache size, since it's a subdirectory
8411                    mStats.externalDataSize -= mStats.externalCacheSize;
8412
8413                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8414                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8415
8416                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8417                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8418                }
8419            }
8420        }
8421
8422        @Override
8423        void handleReturnCode() {
8424            if (mObserver != null) {
8425                try {
8426                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8427                } catch (RemoteException e) {
8428                    Slog.i(TAG, "Observer no longer exists.");
8429                }
8430            }
8431        }
8432
8433        @Override
8434        void handleServiceError() {
8435            Slog.e(TAG, "Could not measure application " + mStats.packageName
8436                            + " external storage");
8437        }
8438    }
8439
8440    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8441            throws RemoteException {
8442        long result = 0;
8443        for (File path : paths) {
8444            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8445        }
8446        return result;
8447    }
8448
8449    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8450        for (File path : paths) {
8451            try {
8452                mcs.clearDirectory(path.getAbsolutePath());
8453            } catch (RemoteException e) {
8454            }
8455        }
8456    }
8457
8458    static class OriginInfo {
8459        /**
8460         * Location where install is coming from, before it has been
8461         * copied/renamed into place. This could be a single monolithic APK
8462         * file, or a cluster directory. This location may be untrusted.
8463         */
8464        final File file;
8465        final String cid;
8466
8467        /**
8468         * Flag indicating that {@link #file} or {@link #cid} has already been
8469         * staged, meaning downstream users don't need to defensively copy the
8470         * contents.
8471         */
8472        final boolean staged;
8473
8474        /**
8475         * Flag indicating that {@link #file} or {@link #cid} is an already
8476         * installed app that is being moved.
8477         */
8478        final boolean existing;
8479
8480        final String resolvedPath;
8481        final File resolvedFile;
8482
8483        static OriginInfo fromNothing() {
8484            return new OriginInfo(null, null, false, false);
8485        }
8486
8487        static OriginInfo fromUntrustedFile(File file) {
8488            return new OriginInfo(file, null, false, false);
8489        }
8490
8491        static OriginInfo fromExistingFile(File file) {
8492            return new OriginInfo(file, null, false, true);
8493        }
8494
8495        static OriginInfo fromStagedFile(File file) {
8496            return new OriginInfo(file, null, true, false);
8497        }
8498
8499        static OriginInfo fromStagedContainer(String cid) {
8500            return new OriginInfo(null, cid, true, false);
8501        }
8502
8503        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8504            this.file = file;
8505            this.cid = cid;
8506            this.staged = staged;
8507            this.existing = existing;
8508
8509            if (cid != null) {
8510                resolvedPath = PackageHelper.getSdDir(cid);
8511                resolvedFile = new File(resolvedPath);
8512            } else if (file != null) {
8513                resolvedPath = file.getAbsolutePath();
8514                resolvedFile = file;
8515            } else {
8516                resolvedPath = null;
8517                resolvedFile = null;
8518            }
8519        }
8520    }
8521
8522    class InstallParams extends HandlerParams {
8523        final OriginInfo origin;
8524        final IPackageInstallObserver2 observer;
8525        int installFlags;
8526        final String installerPackageName;
8527        final VerificationParams verificationParams;
8528        private InstallArgs mArgs;
8529        private int mRet;
8530        final String packageAbiOverride;
8531
8532        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8533                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8534                String packageAbiOverride) {
8535            super(user);
8536            this.origin = origin;
8537            this.observer = observer;
8538            this.installFlags = installFlags;
8539            this.installerPackageName = installerPackageName;
8540            this.verificationParams = verificationParams;
8541            this.packageAbiOverride = packageAbiOverride;
8542        }
8543
8544        @Override
8545        public String toString() {
8546            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8547                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8548        }
8549
8550        public ManifestDigest getManifestDigest() {
8551            if (verificationParams == null) {
8552                return null;
8553            }
8554            return verificationParams.getManifestDigest();
8555        }
8556
8557        private int installLocationPolicy(PackageInfoLite pkgLite) {
8558            String packageName = pkgLite.packageName;
8559            int installLocation = pkgLite.installLocation;
8560            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8561            // reader
8562            synchronized (mPackages) {
8563                PackageParser.Package pkg = mPackages.get(packageName);
8564                if (pkg != null) {
8565                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8566                        // Check for downgrading.
8567                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8568                            if (pkgLite.versionCode < pkg.mVersionCode) {
8569                                Slog.w(TAG, "Can't install update of " + packageName
8570                                        + " update version " + pkgLite.versionCode
8571                                        + " is older than installed version "
8572                                        + pkg.mVersionCode);
8573                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8574                            }
8575                        }
8576                        // Check for updated system application.
8577                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8578                            if (onSd) {
8579                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8580                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8581                            }
8582                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8583                        } else {
8584                            if (onSd) {
8585                                // Install flag overrides everything.
8586                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8587                            }
8588                            // If current upgrade specifies particular preference
8589                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8590                                // Application explicitly specified internal.
8591                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8592                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8593                                // App explictly prefers external. Let policy decide
8594                            } else {
8595                                // Prefer previous location
8596                                if (isExternal(pkg)) {
8597                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8598                                }
8599                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8600                            }
8601                        }
8602                    } else {
8603                        // Invalid install. Return error code
8604                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8605                    }
8606                }
8607            }
8608            // All the special cases have been taken care of.
8609            // Return result based on recommended install location.
8610            if (onSd) {
8611                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8612            }
8613            return pkgLite.recommendedInstallLocation;
8614        }
8615
8616        /*
8617         * Invoke remote method to get package information and install
8618         * location values. Override install location based on default
8619         * policy if needed and then create install arguments based
8620         * on the install location.
8621         */
8622        public void handleStartCopy() throws RemoteException {
8623            int ret = PackageManager.INSTALL_SUCCEEDED;
8624
8625            // If we're already staged, we've firmly committed to an install location
8626            if (origin.staged) {
8627                if (origin.file != null) {
8628                    installFlags |= PackageManager.INSTALL_INTERNAL;
8629                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8630                } else if (origin.cid != null) {
8631                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8632                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8633                } else {
8634                    throw new IllegalStateException("Invalid stage location");
8635                }
8636            }
8637
8638            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8639            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8640
8641            PackageInfoLite pkgLite = null;
8642
8643            if (onInt && onSd) {
8644                // Check if both bits are set.
8645                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8646                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8647            } else {
8648                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8649                        packageAbiOverride);
8650
8651                /*
8652                 * If we have too little free space, try to free cache
8653                 * before giving up.
8654                 */
8655                if (!origin.staged && pkgLite.recommendedInstallLocation
8656                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8657                    // TODO: focus freeing disk space on the target device
8658                    final StorageManager storage = StorageManager.from(mContext);
8659                    final long lowThreshold = storage.getStorageLowBytes(
8660                            Environment.getDataDirectory());
8661
8662                    final long sizeBytes = mContainerService.calculateInstalledSize(
8663                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8664
8665                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8666                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8667                                installFlags, packageAbiOverride);
8668                    }
8669
8670                    /*
8671                     * The cache free must have deleted the file we
8672                     * downloaded to install.
8673                     *
8674                     * TODO: fix the "freeCache" call to not delete
8675                     *       the file we care about.
8676                     */
8677                    if (pkgLite.recommendedInstallLocation
8678                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8679                        pkgLite.recommendedInstallLocation
8680                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8681                    }
8682                }
8683            }
8684
8685            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8686                int loc = pkgLite.recommendedInstallLocation;
8687                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8688                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8689                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8690                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8691                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8692                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8693                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8694                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8695                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8696                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8697                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8698                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8699                } else {
8700                    // Override with defaults if needed.
8701                    loc = installLocationPolicy(pkgLite);
8702                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8703                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8704                    } else if (!onSd && !onInt) {
8705                        // Override install location with flags
8706                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8707                            // Set the flag to install on external media.
8708                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8709                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8710                        } else {
8711                            // Make sure the flag for installing on external
8712                            // media is unset
8713                            installFlags |= PackageManager.INSTALL_INTERNAL;
8714                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8715                        }
8716                    }
8717                }
8718            }
8719
8720            final InstallArgs args = createInstallArgs(this);
8721            mArgs = args;
8722
8723            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8724                 /*
8725                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8726                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8727                 */
8728                int userIdentifier = getUser().getIdentifier();
8729                if (userIdentifier == UserHandle.USER_ALL
8730                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8731                    userIdentifier = UserHandle.USER_OWNER;
8732                }
8733
8734                /*
8735                 * Determine if we have any installed package verifiers. If we
8736                 * do, then we'll defer to them to verify the packages.
8737                 */
8738                final int requiredUid = mRequiredVerifierPackage == null ? -1
8739                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8740                if (!origin.existing && requiredUid != -1
8741                        && isVerificationEnabled(userIdentifier, installFlags)) {
8742                    final Intent verification = new Intent(
8743                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8744                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8745                            PACKAGE_MIME_TYPE);
8746                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8747
8748                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8749                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8750                            0 /* TODO: Which userId? */);
8751
8752                    if (DEBUG_VERIFY) {
8753                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8754                                + verification.toString() + " with " + pkgLite.verifiers.length
8755                                + " optional verifiers");
8756                    }
8757
8758                    final int verificationId = mPendingVerificationToken++;
8759
8760                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8761
8762                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8763                            installerPackageName);
8764
8765                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8766                            installFlags);
8767
8768                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8769                            pkgLite.packageName);
8770
8771                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8772                            pkgLite.versionCode);
8773
8774                    if (verificationParams != null) {
8775                        if (verificationParams.getVerificationURI() != null) {
8776                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8777                                 verificationParams.getVerificationURI());
8778                        }
8779                        if (verificationParams.getOriginatingURI() != null) {
8780                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8781                                  verificationParams.getOriginatingURI());
8782                        }
8783                        if (verificationParams.getReferrer() != null) {
8784                            verification.putExtra(Intent.EXTRA_REFERRER,
8785                                  verificationParams.getReferrer());
8786                        }
8787                        if (verificationParams.getOriginatingUid() >= 0) {
8788                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8789                                  verificationParams.getOriginatingUid());
8790                        }
8791                        if (verificationParams.getInstallerUid() >= 0) {
8792                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8793                                  verificationParams.getInstallerUid());
8794                        }
8795                    }
8796
8797                    final PackageVerificationState verificationState = new PackageVerificationState(
8798                            requiredUid, args);
8799
8800                    mPendingVerification.append(verificationId, verificationState);
8801
8802                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8803                            receivers, verificationState);
8804
8805                    /*
8806                     * If any sufficient verifiers were listed in the package
8807                     * manifest, attempt to ask them.
8808                     */
8809                    if (sufficientVerifiers != null) {
8810                        final int N = sufficientVerifiers.size();
8811                        if (N == 0) {
8812                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8813                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8814                        } else {
8815                            for (int i = 0; i < N; i++) {
8816                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8817
8818                                final Intent sufficientIntent = new Intent(verification);
8819                                sufficientIntent.setComponent(verifierComponent);
8820
8821                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
8822                            }
8823                        }
8824                    }
8825
8826                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
8827                            mRequiredVerifierPackage, receivers);
8828                    if (ret == PackageManager.INSTALL_SUCCEEDED
8829                            && mRequiredVerifierPackage != null) {
8830                        /*
8831                         * Send the intent to the required verification agent,
8832                         * but only start the verification timeout after the
8833                         * target BroadcastReceivers have run.
8834                         */
8835                        verification.setComponent(requiredVerifierComponent);
8836                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
8837                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8838                                new BroadcastReceiver() {
8839                                    @Override
8840                                    public void onReceive(Context context, Intent intent) {
8841                                        final Message msg = mHandler
8842                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
8843                                        msg.arg1 = verificationId;
8844                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
8845                                    }
8846                                }, null, 0, null, null);
8847
8848                        /*
8849                         * We don't want the copy to proceed until verification
8850                         * succeeds, so null out this field.
8851                         */
8852                        mArgs = null;
8853                    }
8854                } else {
8855                    /*
8856                     * No package verification is enabled, so immediately start
8857                     * the remote call to initiate copy using temporary file.
8858                     */
8859                    ret = args.copyApk(mContainerService, true);
8860                }
8861            }
8862
8863            mRet = ret;
8864        }
8865
8866        @Override
8867        void handleReturnCode() {
8868            // If mArgs is null, then MCS couldn't be reached. When it
8869            // reconnects, it will try again to install. At that point, this
8870            // will succeed.
8871            if (mArgs != null) {
8872                processPendingInstall(mArgs, mRet);
8873            }
8874        }
8875
8876        @Override
8877        void handleServiceError() {
8878            mArgs = createInstallArgs(this);
8879            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
8880        }
8881
8882        public boolean isForwardLocked() {
8883            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8884        }
8885    }
8886
8887    /**
8888     * Used during creation of InstallArgs
8889     *
8890     * @param installFlags package installation flags
8891     * @return true if should be installed on external storage
8892     */
8893    private static boolean installOnSd(int installFlags) {
8894        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
8895            return false;
8896        }
8897        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
8898            return true;
8899        }
8900        return false;
8901    }
8902
8903    /**
8904     * Used during creation of InstallArgs
8905     *
8906     * @param installFlags package installation flags
8907     * @return true if should be installed as forward locked
8908     */
8909    private static boolean installForwardLocked(int installFlags) {
8910        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
8911    }
8912
8913    private InstallArgs createInstallArgs(InstallParams params) {
8914        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
8915            return new AsecInstallArgs(params);
8916        } else {
8917            return new FileInstallArgs(params);
8918        }
8919    }
8920
8921    /**
8922     * Create args that describe an existing installed package. Typically used
8923     * when cleaning up old installs, or used as a move source.
8924     */
8925    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
8926            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
8927        final boolean isInAsec;
8928        if (installOnSd(installFlags)) {
8929            /* Apps on SD card are always in ASEC containers. */
8930            isInAsec = true;
8931        } else if (installForwardLocked(installFlags)
8932                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
8933            /*
8934             * Forward-locked apps are only in ASEC containers if they're the
8935             * new style
8936             */
8937            isInAsec = true;
8938        } else {
8939            isInAsec = false;
8940        }
8941
8942        if (isInAsec) {
8943            return new AsecInstallArgs(codePath, instructionSets,
8944                    installOnSd(installFlags), installForwardLocked(installFlags));
8945        } else {
8946            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
8947                    instructionSets);
8948        }
8949    }
8950
8951    static abstract class InstallArgs {
8952        /** @see InstallParams#origin */
8953        final OriginInfo origin;
8954
8955        final IPackageInstallObserver2 observer;
8956        // Always refers to PackageManager flags only
8957        final int installFlags;
8958        final String installerPackageName;
8959        final ManifestDigest manifestDigest;
8960        final UserHandle user;
8961        final String abiOverride;
8962
8963        // The list of instruction sets supported by this app. This is currently
8964        // only used during the rmdex() phase to clean up resources. We can get rid of this
8965        // if we move dex files under the common app path.
8966        /* nullable */ String[] instructionSets;
8967
8968        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8969                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
8970                String[] instructionSets, String abiOverride) {
8971            this.origin = origin;
8972            this.installFlags = installFlags;
8973            this.observer = observer;
8974            this.installerPackageName = installerPackageName;
8975            this.manifestDigest = manifestDigest;
8976            this.user = user;
8977            this.instructionSets = instructionSets;
8978            this.abiOverride = abiOverride;
8979        }
8980
8981        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
8982        abstract int doPreInstall(int status);
8983
8984        /**
8985         * Rename package into final resting place. All paths on the given
8986         * scanned package should be updated to reflect the rename.
8987         */
8988        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
8989        abstract int doPostInstall(int status, int uid);
8990
8991        /** @see PackageSettingBase#codePathString */
8992        abstract String getCodePath();
8993        /** @see PackageSettingBase#resourcePathString */
8994        abstract String getResourcePath();
8995        abstract String getLegacyNativeLibraryPath();
8996
8997        // Need installer lock especially for dex file removal.
8998        abstract void cleanUpResourcesLI();
8999        abstract boolean doPostDeleteLI(boolean delete);
9000        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9001
9002        /**
9003         * Called before the source arguments are copied. This is used mostly
9004         * for MoveParams when it needs to read the source file to put it in the
9005         * destination.
9006         */
9007        int doPreCopy() {
9008            return PackageManager.INSTALL_SUCCEEDED;
9009        }
9010
9011        /**
9012         * Called after the source arguments are copied. This is used mostly for
9013         * MoveParams when it needs to read the source file to put it in the
9014         * destination.
9015         *
9016         * @return
9017         */
9018        int doPostCopy(int uid) {
9019            return PackageManager.INSTALL_SUCCEEDED;
9020        }
9021
9022        protected boolean isFwdLocked() {
9023            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9024        }
9025
9026        protected boolean isExternal() {
9027            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9028        }
9029
9030        UserHandle getUser() {
9031            return user;
9032        }
9033    }
9034
9035    /**
9036     * Logic to handle installation of non-ASEC applications, including copying
9037     * and renaming logic.
9038     */
9039    class FileInstallArgs extends InstallArgs {
9040        private File codeFile;
9041        private File resourceFile;
9042        private File legacyNativeLibraryPath;
9043
9044        // Example topology:
9045        // /data/app/com.example/base.apk
9046        // /data/app/com.example/split_foo.apk
9047        // /data/app/com.example/lib/arm/libfoo.so
9048        // /data/app/com.example/lib/arm64/libfoo.so
9049        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9050
9051        /** New install */
9052        FileInstallArgs(InstallParams params) {
9053            super(params.origin, params.observer, params.installFlags,
9054                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9055                    null /* instruction sets */, params.packageAbiOverride);
9056            if (isFwdLocked()) {
9057                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9058            }
9059        }
9060
9061        /** Existing install */
9062        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9063                String[] instructionSets) {
9064            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9065            this.codeFile = (codePath != null) ? new File(codePath) : null;
9066            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9067            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9068                    new File(legacyNativeLibraryPath) : null;
9069        }
9070
9071        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9072            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9073                    isFwdLocked(), abiOverride);
9074
9075            final StorageManager storage = StorageManager.from(mContext);
9076            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9077        }
9078
9079        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9080            if (origin.staged) {
9081                Slog.d(TAG, origin.file + " already staged; skipping copy");
9082                codeFile = origin.file;
9083                resourceFile = origin.file;
9084                return PackageManager.INSTALL_SUCCEEDED;
9085            }
9086
9087            try {
9088                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9089                codeFile = tempDir;
9090                resourceFile = tempDir;
9091            } catch (IOException e) {
9092                Slog.w(TAG, "Failed to create copy file: " + e);
9093                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9094            }
9095
9096            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9097                @Override
9098                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9099                    if (!FileUtils.isValidExtFilename(name)) {
9100                        throw new IllegalArgumentException("Invalid filename: " + name);
9101                    }
9102                    try {
9103                        final File file = new File(codeFile, name);
9104                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9105                                O_RDWR | O_CREAT, 0644);
9106                        Os.chmod(file.getAbsolutePath(), 0644);
9107                        return new ParcelFileDescriptor(fd);
9108                    } catch (ErrnoException e) {
9109                        throw new RemoteException("Failed to open: " + e.getMessage());
9110                    }
9111                }
9112            };
9113
9114            int ret = PackageManager.INSTALL_SUCCEEDED;
9115            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9116            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9117                Slog.e(TAG, "Failed to copy package");
9118                return ret;
9119            }
9120
9121            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9122            NativeLibraryHelper.Handle handle = null;
9123            try {
9124                handle = NativeLibraryHelper.Handle.create(codeFile);
9125                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9126                        abiOverride);
9127            } catch (IOException e) {
9128                Slog.e(TAG, "Copying native libraries failed", e);
9129                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9130            } finally {
9131                IoUtils.closeQuietly(handle);
9132            }
9133
9134            return ret;
9135        }
9136
9137        int doPreInstall(int status) {
9138            if (status != PackageManager.INSTALL_SUCCEEDED) {
9139                cleanUp();
9140            }
9141            return status;
9142        }
9143
9144        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9145            if (status != PackageManager.INSTALL_SUCCEEDED) {
9146                cleanUp();
9147                return false;
9148            } else {
9149                final File beforeCodeFile = codeFile;
9150                final File afterCodeFile = getNextCodePath(pkg.packageName);
9151
9152                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9153                try {
9154                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9155                } catch (ErrnoException e) {
9156                    Slog.d(TAG, "Failed to rename", e);
9157                    return false;
9158                }
9159
9160                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9161                    Slog.d(TAG, "Failed to restorecon");
9162                    return false;
9163                }
9164
9165                // Reflect the rename internally
9166                codeFile = afterCodeFile;
9167                resourceFile = afterCodeFile;
9168
9169                // Reflect the rename in scanned details
9170                pkg.codePath = afterCodeFile.getAbsolutePath();
9171                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9172                        pkg.baseCodePath);
9173                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9174                        pkg.splitCodePaths);
9175
9176                // Reflect the rename in app info
9177                pkg.applicationInfo.setCodePath(pkg.codePath);
9178                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9179                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9180                pkg.applicationInfo.setResourcePath(pkg.codePath);
9181                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9182                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9183
9184                return true;
9185            }
9186        }
9187
9188        int doPostInstall(int status, int uid) {
9189            if (status != PackageManager.INSTALL_SUCCEEDED) {
9190                cleanUp();
9191            }
9192            return status;
9193        }
9194
9195        @Override
9196        String getCodePath() {
9197            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9198        }
9199
9200        @Override
9201        String getResourcePath() {
9202            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9203        }
9204
9205        @Override
9206        String getLegacyNativeLibraryPath() {
9207            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9208        }
9209
9210        private boolean cleanUp() {
9211            if (codeFile == null || !codeFile.exists()) {
9212                return false;
9213            }
9214
9215            if (codeFile.isDirectory()) {
9216                FileUtils.deleteContents(codeFile);
9217            }
9218            codeFile.delete();
9219
9220            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9221                resourceFile.delete();
9222            }
9223
9224            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9225                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9226                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9227                }
9228                legacyNativeLibraryPath.delete();
9229            }
9230
9231            return true;
9232        }
9233
9234        void cleanUpResourcesLI() {
9235            // Try enumerating all code paths before deleting
9236            List<String> allCodePaths = Collections.EMPTY_LIST;
9237            if (codeFile != null && codeFile.exists()) {
9238                try {
9239                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9240                    allCodePaths = pkg.getAllCodePaths();
9241                } catch (PackageParserException e) {
9242                    // Ignored; we tried our best
9243                }
9244            }
9245
9246            cleanUp();
9247
9248            if (!allCodePaths.isEmpty()) {
9249                if (instructionSets == null) {
9250                    throw new IllegalStateException("instructionSet == null");
9251                }
9252                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9253                for (String codePath : allCodePaths) {
9254                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9255                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9256                        if (retCode < 0) {
9257                            Slog.w(TAG, "Couldn't remove dex file for package: "
9258                                    + " at location " + codePath + ", retcode=" + retCode);
9259                            // we don't consider this to be a failure of the core package deletion
9260                        }
9261                    }
9262                }
9263            }
9264        }
9265
9266        boolean doPostDeleteLI(boolean delete) {
9267            // XXX err, shouldn't we respect the delete flag?
9268            cleanUpResourcesLI();
9269            return true;
9270        }
9271    }
9272
9273    private boolean isAsecExternal(String cid) {
9274        final String asecPath = PackageHelper.getSdFilesystem(cid);
9275        return !asecPath.startsWith(mAsecInternalPath);
9276    }
9277
9278    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9279            PackageManagerException {
9280        if (copyRet < 0) {
9281            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9282                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9283                throw new PackageManagerException(copyRet, message);
9284            }
9285        }
9286    }
9287
9288    /**
9289     * Extract the MountService "container ID" from the full code path of an
9290     * .apk.
9291     */
9292    static String cidFromCodePath(String fullCodePath) {
9293        int eidx = fullCodePath.lastIndexOf("/");
9294        String subStr1 = fullCodePath.substring(0, eidx);
9295        int sidx = subStr1.lastIndexOf("/");
9296        return subStr1.substring(sidx+1, eidx);
9297    }
9298
9299    /**
9300     * Logic to handle installation of ASEC applications, including copying and
9301     * renaming logic.
9302     */
9303    class AsecInstallArgs extends InstallArgs {
9304        static final String RES_FILE_NAME = "pkg.apk";
9305        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9306
9307        String cid;
9308        String packagePath;
9309        String resourcePath;
9310        String legacyNativeLibraryDir;
9311
9312        /** New install */
9313        AsecInstallArgs(InstallParams params) {
9314            super(params.origin, params.observer, params.installFlags,
9315                    params.installerPackageName, params.getManifestDigest(),
9316                    params.getUser(), null /* instruction sets */,
9317                    params.packageAbiOverride);
9318        }
9319
9320        /** Existing install */
9321        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9322                        boolean isExternal, boolean isForwardLocked) {
9323            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9324                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9325                    instructionSets, null);
9326            // Hackily pretend we're still looking at a full code path
9327            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9328                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9329            }
9330
9331            // Extract cid from fullCodePath
9332            int eidx = fullCodePath.lastIndexOf("/");
9333            String subStr1 = fullCodePath.substring(0, eidx);
9334            int sidx = subStr1.lastIndexOf("/");
9335            cid = subStr1.substring(sidx+1, eidx);
9336            setMountPath(subStr1);
9337        }
9338
9339        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9340            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9341                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9342                    instructionSets, null);
9343            this.cid = cid;
9344            setMountPath(PackageHelper.getSdDir(cid));
9345        }
9346
9347        void createCopyFile() {
9348            cid = mInstallerService.allocateExternalStageCidLegacy();
9349        }
9350
9351        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9352            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9353                    abiOverride);
9354
9355            final File target;
9356            if (isExternal()) {
9357                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9358            } else {
9359                target = Environment.getDataDirectory();
9360            }
9361
9362            final StorageManager storage = StorageManager.from(mContext);
9363            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9364        }
9365
9366        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9367            if (origin.staged) {
9368                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9369                cid = origin.cid;
9370                setMountPath(PackageHelper.getSdDir(cid));
9371                return PackageManager.INSTALL_SUCCEEDED;
9372            }
9373
9374            if (temp) {
9375                createCopyFile();
9376            } else {
9377                /*
9378                 * Pre-emptively destroy the container since it's destroyed if
9379                 * copying fails due to it existing anyway.
9380                 */
9381                PackageHelper.destroySdDir(cid);
9382            }
9383
9384            final String newMountPath = imcs.copyPackageToContainer(
9385                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9386                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9387
9388            if (newMountPath != null) {
9389                setMountPath(newMountPath);
9390                return PackageManager.INSTALL_SUCCEEDED;
9391            } else {
9392                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9393            }
9394        }
9395
9396        @Override
9397        String getCodePath() {
9398            return packagePath;
9399        }
9400
9401        @Override
9402        String getResourcePath() {
9403            return resourcePath;
9404        }
9405
9406        @Override
9407        String getLegacyNativeLibraryPath() {
9408            return legacyNativeLibraryDir;
9409        }
9410
9411        int doPreInstall(int status) {
9412            if (status != PackageManager.INSTALL_SUCCEEDED) {
9413                // Destroy container
9414                PackageHelper.destroySdDir(cid);
9415            } else {
9416                boolean mounted = PackageHelper.isContainerMounted(cid);
9417                if (!mounted) {
9418                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9419                            Process.SYSTEM_UID);
9420                    if (newMountPath != null) {
9421                        setMountPath(newMountPath);
9422                    } else {
9423                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9424                    }
9425                }
9426            }
9427            return status;
9428        }
9429
9430        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9431            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9432            String newMountPath = null;
9433            if (PackageHelper.isContainerMounted(cid)) {
9434                // Unmount the container
9435                if (!PackageHelper.unMountSdDir(cid)) {
9436                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9437                    return false;
9438                }
9439            }
9440            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9441                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9442                        " which might be stale. Will try to clean up.");
9443                // Clean up the stale container and proceed to recreate.
9444                if (!PackageHelper.destroySdDir(newCacheId)) {
9445                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9446                    return false;
9447                }
9448                // Successfully cleaned up stale container. Try to rename again.
9449                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9450                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9451                            + " inspite of cleaning it up.");
9452                    return false;
9453                }
9454            }
9455            if (!PackageHelper.isContainerMounted(newCacheId)) {
9456                Slog.w(TAG, "Mounting container " + newCacheId);
9457                newMountPath = PackageHelper.mountSdDir(newCacheId,
9458                        getEncryptKey(), Process.SYSTEM_UID);
9459            } else {
9460                newMountPath = PackageHelper.getSdDir(newCacheId);
9461            }
9462            if (newMountPath == null) {
9463                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9464                return false;
9465            }
9466            Log.i(TAG, "Succesfully renamed " + cid +
9467                    " to " + newCacheId +
9468                    " at new path: " + newMountPath);
9469            cid = newCacheId;
9470
9471            final File beforeCodeFile = new File(packagePath);
9472            setMountPath(newMountPath);
9473            final File afterCodeFile = new File(packagePath);
9474
9475            // Reflect the rename in scanned details
9476            pkg.codePath = afterCodeFile.getAbsolutePath();
9477            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9478                    pkg.baseCodePath);
9479            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9480                    pkg.splitCodePaths);
9481
9482            // Reflect the rename in app info
9483            pkg.applicationInfo.setCodePath(pkg.codePath);
9484            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9485            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9486            pkg.applicationInfo.setResourcePath(pkg.codePath);
9487            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9488            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9489
9490            return true;
9491        }
9492
9493        private void setMountPath(String mountPath) {
9494            final File mountFile = new File(mountPath);
9495
9496            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9497            if (monolithicFile.exists()) {
9498                packagePath = monolithicFile.getAbsolutePath();
9499                if (isFwdLocked()) {
9500                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9501                } else {
9502                    resourcePath = packagePath;
9503                }
9504            } else {
9505                packagePath = mountFile.getAbsolutePath();
9506                resourcePath = packagePath;
9507            }
9508
9509            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9510        }
9511
9512        int doPostInstall(int status, int uid) {
9513            if (status != PackageManager.INSTALL_SUCCEEDED) {
9514                cleanUp();
9515            } else {
9516                final int groupOwner;
9517                final String protectedFile;
9518                if (isFwdLocked()) {
9519                    groupOwner = UserHandle.getSharedAppGid(uid);
9520                    protectedFile = RES_FILE_NAME;
9521                } else {
9522                    groupOwner = -1;
9523                    protectedFile = null;
9524                }
9525
9526                if (uid < Process.FIRST_APPLICATION_UID
9527                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9528                    Slog.e(TAG, "Failed to finalize " + cid);
9529                    PackageHelper.destroySdDir(cid);
9530                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9531                }
9532
9533                boolean mounted = PackageHelper.isContainerMounted(cid);
9534                if (!mounted) {
9535                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9536                }
9537            }
9538            return status;
9539        }
9540
9541        private void cleanUp() {
9542            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9543
9544            // Destroy secure container
9545            PackageHelper.destroySdDir(cid);
9546        }
9547
9548        private List<String> getAllCodePaths() {
9549            final File codeFile = new File(getCodePath());
9550            if (codeFile != null && codeFile.exists()) {
9551                try {
9552                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9553                    return pkg.getAllCodePaths();
9554                } catch (PackageParserException e) {
9555                    // Ignored; we tried our best
9556                }
9557            }
9558            return Collections.EMPTY_LIST;
9559        }
9560
9561        void cleanUpResourcesLI() {
9562            // Enumerate all code paths before deleting
9563            cleanUpResourcesLI(getAllCodePaths());
9564        }
9565
9566        private void cleanUpResourcesLI(List<String> allCodePaths) {
9567            cleanUp();
9568
9569            if (!allCodePaths.isEmpty()) {
9570                if (instructionSets == null) {
9571                    throw new IllegalStateException("instructionSet == null");
9572                }
9573                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9574                for (String codePath : allCodePaths) {
9575                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9576                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9577                        if (retCode < 0) {
9578                            Slog.w(TAG, "Couldn't remove dex file for package: "
9579                                    + " at location " + codePath + ", retcode=" + retCode);
9580                            // we don't consider this to be a failure of the core package deletion
9581                        }
9582                    }
9583                }
9584            }
9585        }
9586
9587        boolean matchContainer(String app) {
9588            if (cid.startsWith(app)) {
9589                return true;
9590            }
9591            return false;
9592        }
9593
9594        String getPackageName() {
9595            return getAsecPackageName(cid);
9596        }
9597
9598        boolean doPostDeleteLI(boolean delete) {
9599            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9600            final List<String> allCodePaths = getAllCodePaths();
9601            boolean mounted = PackageHelper.isContainerMounted(cid);
9602            if (mounted) {
9603                // Unmount first
9604                if (PackageHelper.unMountSdDir(cid)) {
9605                    mounted = false;
9606                }
9607            }
9608            if (!mounted && delete) {
9609                cleanUpResourcesLI(allCodePaths);
9610            }
9611            return !mounted;
9612        }
9613
9614        @Override
9615        int doPreCopy() {
9616            if (isFwdLocked()) {
9617                if (!PackageHelper.fixSdPermissions(cid,
9618                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9619                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9620                }
9621            }
9622
9623            return PackageManager.INSTALL_SUCCEEDED;
9624        }
9625
9626        @Override
9627        int doPostCopy(int uid) {
9628            if (isFwdLocked()) {
9629                if (uid < Process.FIRST_APPLICATION_UID
9630                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9631                                RES_FILE_NAME)) {
9632                    Slog.e(TAG, "Failed to finalize " + cid);
9633                    PackageHelper.destroySdDir(cid);
9634                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9635                }
9636            }
9637
9638            return PackageManager.INSTALL_SUCCEEDED;
9639        }
9640    }
9641
9642    static String getAsecPackageName(String packageCid) {
9643        int idx = packageCid.lastIndexOf("-");
9644        if (idx == -1) {
9645            return packageCid;
9646        }
9647        return packageCid.substring(0, idx);
9648    }
9649
9650    // Utility method used to create code paths based on package name and available index.
9651    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9652        String idxStr = "";
9653        int idx = 1;
9654        // Fall back to default value of idx=1 if prefix is not
9655        // part of oldCodePath
9656        if (oldCodePath != null) {
9657            String subStr = oldCodePath;
9658            // Drop the suffix right away
9659            if (suffix != null && subStr.endsWith(suffix)) {
9660                subStr = subStr.substring(0, subStr.length() - suffix.length());
9661            }
9662            // If oldCodePath already contains prefix find out the
9663            // ending index to either increment or decrement.
9664            int sidx = subStr.lastIndexOf(prefix);
9665            if (sidx != -1) {
9666                subStr = subStr.substring(sidx + prefix.length());
9667                if (subStr != null) {
9668                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9669                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9670                    }
9671                    try {
9672                        idx = Integer.parseInt(subStr);
9673                        if (idx <= 1) {
9674                            idx++;
9675                        } else {
9676                            idx--;
9677                        }
9678                    } catch(NumberFormatException e) {
9679                    }
9680                }
9681            }
9682        }
9683        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9684        return prefix + idxStr;
9685    }
9686
9687    private File getNextCodePath(String packageName) {
9688        int suffix = 1;
9689        File result;
9690        do {
9691            result = new File(mAppInstallDir, packageName + "-" + suffix);
9692            suffix++;
9693        } while (result.exists());
9694        return result;
9695    }
9696
9697    // Utility method used to ignore ADD/REMOVE events
9698    // by directory observer.
9699    private static boolean ignoreCodePath(String fullPathStr) {
9700        String apkName = deriveCodePathName(fullPathStr);
9701        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9702        if (idx != -1 && ((idx+1) < apkName.length())) {
9703            // Make sure the package ends with a numeral
9704            String version = apkName.substring(idx+1);
9705            try {
9706                Integer.parseInt(version);
9707                return true;
9708            } catch (NumberFormatException e) {}
9709        }
9710        return false;
9711    }
9712
9713    // Utility method that returns the relative package path with respect
9714    // to the installation directory. Like say for /data/data/com.test-1.apk
9715    // string com.test-1 is returned.
9716    static String deriveCodePathName(String codePath) {
9717        if (codePath == null) {
9718            return null;
9719        }
9720        final File codeFile = new File(codePath);
9721        final String name = codeFile.getName();
9722        if (codeFile.isDirectory()) {
9723            return name;
9724        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9725            final int lastDot = name.lastIndexOf('.');
9726            return name.substring(0, lastDot);
9727        } else {
9728            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9729            return null;
9730        }
9731    }
9732
9733    class PackageInstalledInfo {
9734        String name;
9735        int uid;
9736        // The set of users that originally had this package installed.
9737        int[] origUsers;
9738        // The set of users that now have this package installed.
9739        int[] newUsers;
9740        PackageParser.Package pkg;
9741        int returnCode;
9742        String returnMsg;
9743        PackageRemovedInfo removedInfo;
9744
9745        public void setError(int code, String msg) {
9746            returnCode = code;
9747            returnMsg = msg;
9748            Slog.w(TAG, msg);
9749        }
9750
9751        public void setError(String msg, PackageParserException e) {
9752            returnCode = e.error;
9753            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9754            Slog.w(TAG, msg, e);
9755        }
9756
9757        public void setError(String msg, PackageManagerException e) {
9758            returnCode = e.error;
9759            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9760            Slog.w(TAG, msg, e);
9761        }
9762
9763        // In some error cases we want to convey more info back to the observer
9764        String origPackage;
9765        String origPermission;
9766    }
9767
9768    /*
9769     * Install a non-existing package.
9770     */
9771    private void installNewPackageLI(PackageParser.Package pkg,
9772            int parseFlags, int scanFlags, UserHandle user,
9773            String installerPackageName, PackageInstalledInfo res) {
9774        // Remember this for later, in case we need to rollback this install
9775        String pkgName = pkg.packageName;
9776
9777        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9778        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9779        synchronized(mPackages) {
9780            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9781                // A package with the same name is already installed, though
9782                // it has been renamed to an older name.  The package we
9783                // are trying to install should be installed as an update to
9784                // the existing one, but that has not been requested, so bail.
9785                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9786                        + " without first uninstalling package running as "
9787                        + mSettings.mRenamedPackages.get(pkgName));
9788                return;
9789            }
9790            if (mPackages.containsKey(pkgName)) {
9791                // Don't allow installation over an existing package with the same name.
9792                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9793                        + " without first uninstalling.");
9794                return;
9795            }
9796        }
9797
9798        try {
9799            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9800                    System.currentTimeMillis(), user);
9801
9802            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9803            // delete the partially installed application. the data directory will have to be
9804            // restored if it was already existing
9805            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9806                // remove package from internal structures.  Note that we want deletePackageX to
9807                // delete the package data and cache directories that it created in
9808                // scanPackageLocked, unless those directories existed before we even tried to
9809                // install.
9810                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9811                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9812                                res.removedInfo, true);
9813            }
9814
9815        } catch (PackageManagerException e) {
9816            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9817        }
9818    }
9819
9820    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9821        // Upgrade keysets are being used.  Determine if new package has a superset of the
9822        // required keys.
9823        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
9824        KeySetManagerService ksms = mSettings.mKeySetManagerService;
9825        for (int i = 0; i < upgradeKeySets.length; i++) {
9826            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
9827            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
9828                return true;
9829            }
9830        }
9831        return false;
9832    }
9833
9834    private void replacePackageLI(PackageParser.Package pkg,
9835            int parseFlags, int scanFlags, UserHandle user,
9836            String installerPackageName, PackageInstalledInfo res) {
9837        PackageParser.Package oldPackage;
9838        String pkgName = pkg.packageName;
9839        int[] allUsers;
9840        boolean[] perUserInstalled;
9841
9842        // First find the old package info and check signatures
9843        synchronized(mPackages) {
9844            oldPackage = mPackages.get(pkgName);
9845            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
9846            PackageSetting ps = mSettings.mPackages.get(pkgName);
9847            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
9848                // default to original signature matching
9849                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
9850                    != PackageManager.SIGNATURE_MATCH) {
9851                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9852                            "New package has a different signature: " + pkgName);
9853                    return;
9854                }
9855            } else {
9856                if(!checkUpgradeKeySetLP(ps, pkg)) {
9857                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
9858                            "New package not signed by keys specified by upgrade-keysets: "
9859                            + pkgName);
9860                    return;
9861                }
9862            }
9863
9864            // In case of rollback, remember per-user/profile install state
9865            allUsers = sUserManager.getUserIds();
9866            perUserInstalled = new boolean[allUsers.length];
9867            for (int i = 0; i < allUsers.length; i++) {
9868                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
9869            }
9870        }
9871
9872        boolean sysPkg = (isSystemApp(oldPackage));
9873        if (sysPkg) {
9874            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9875                    user, allUsers, perUserInstalled, installerPackageName, res);
9876        } else {
9877            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
9878                    user, allUsers, perUserInstalled, installerPackageName, res);
9879        }
9880    }
9881
9882    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
9883            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9884            int[] allUsers, boolean[] perUserInstalled,
9885            String installerPackageName, PackageInstalledInfo res) {
9886        String pkgName = deletedPackage.packageName;
9887        boolean deletedPkg = true;
9888        boolean updatedSettings = false;
9889
9890        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
9891                + deletedPackage);
9892        long origUpdateTime;
9893        if (pkg.mExtras != null) {
9894            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
9895        } else {
9896            origUpdateTime = 0;
9897        }
9898
9899        // First delete the existing package while retaining the data directory
9900        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
9901                res.removedInfo, true)) {
9902            // If the existing package wasn't successfully deleted
9903            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
9904            deletedPkg = false;
9905        } else {
9906            // Successfully deleted the old package; proceed with replace.
9907
9908            // If deleted package lived in a container, give users a chance to
9909            // relinquish resources before killing.
9910            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
9911                if (DEBUG_INSTALL) {
9912                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
9913                }
9914                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
9915                final ArrayList<String> pkgList = new ArrayList<String>(1);
9916                pkgList.add(deletedPackage.applicationInfo.packageName);
9917                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
9918            }
9919
9920            deleteCodeCacheDirsLI(pkgName);
9921            try {
9922                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
9923                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
9924                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
9925                updatedSettings = true;
9926            } catch (PackageManagerException e) {
9927                res.setError("Package couldn't be installed in " + pkg.codePath, e);
9928            }
9929        }
9930
9931        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9932            // remove package from internal structures.  Note that we want deletePackageX to
9933            // delete the package data and cache directories that it created in
9934            // scanPackageLocked, unless those directories existed before we even tried to
9935            // install.
9936            if(updatedSettings) {
9937                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
9938                deletePackageLI(
9939                        pkgName, null, true, allUsers, perUserInstalled,
9940                        PackageManager.DELETE_KEEP_DATA,
9941                                res.removedInfo, true);
9942            }
9943            // Since we failed to install the new package we need to restore the old
9944            // package that we deleted.
9945            if (deletedPkg) {
9946                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
9947                File restoreFile = new File(deletedPackage.codePath);
9948                // Parse old package
9949                boolean oldOnSd = isExternal(deletedPackage);
9950                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
9951                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
9952                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
9953                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
9954                try {
9955                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
9956                } catch (PackageManagerException e) {
9957                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
9958                            + e.getMessage());
9959                    return;
9960                }
9961                // Restore of old package succeeded. Update permissions.
9962                // writer
9963                synchronized (mPackages) {
9964                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
9965                            UPDATE_PERMISSIONS_ALL);
9966                    // can downgrade to reader
9967                    mSettings.writeLPr();
9968                }
9969                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
9970            }
9971        }
9972    }
9973
9974    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
9975            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
9976            int[] allUsers, boolean[] perUserInstalled,
9977            String installerPackageName, PackageInstalledInfo res) {
9978        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
9979                + ", old=" + deletedPackage);
9980        boolean updatedSettings = false;
9981        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
9982        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
9983            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
9984        }
9985        String packageName = deletedPackage.packageName;
9986        if (packageName == null) {
9987            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
9988                    "Attempt to delete null packageName.");
9989            return;
9990        }
9991        PackageParser.Package oldPkg;
9992        PackageSetting oldPkgSetting;
9993        // reader
9994        synchronized (mPackages) {
9995            oldPkg = mPackages.get(packageName);
9996            oldPkgSetting = mSettings.mPackages.get(packageName);
9997            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
9998                    (oldPkgSetting == null)) {
9999                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10000                        "Couldn't find package:" + packageName + " information");
10001                return;
10002            }
10003        }
10004
10005        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10006
10007        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10008        res.removedInfo.removedPackage = packageName;
10009        // Remove existing system package
10010        removePackageLI(oldPkgSetting, true);
10011        // writer
10012        synchronized (mPackages) {
10013            if (!mSettings.disableSystemPackageLPw(packageName) && deletedPackage != null) {
10014                // We didn't need to disable the .apk as a current system package,
10015                // which means we are replacing another update that is already
10016                // installed.  We need to make sure to delete the older one's .apk.
10017                res.removedInfo.args = createInstallArgsForExisting(0,
10018                        deletedPackage.applicationInfo.getCodePath(),
10019                        deletedPackage.applicationInfo.getResourcePath(),
10020                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10021                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10022            } else {
10023                res.removedInfo.args = null;
10024            }
10025        }
10026
10027        // Successfully disabled the old package. Now proceed with re-installation
10028        deleteCodeCacheDirsLI(packageName);
10029
10030        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10031        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10032
10033        PackageParser.Package newPackage = null;
10034        try {
10035            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10036            if (newPackage.mExtras != null) {
10037                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10038                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10039                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10040
10041                // is the update attempting to change shared user? that isn't going to work...
10042                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10043                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10044                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10045                            + " to " + newPkgSetting.sharedUser);
10046                    updatedSettings = true;
10047                }
10048            }
10049
10050            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10051                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10052                updatedSettings = true;
10053            }
10054
10055        } catch (PackageManagerException e) {
10056            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10057        }
10058
10059        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10060            // Re installation failed. Restore old information
10061            // Remove new pkg information
10062            if (newPackage != null) {
10063                removeInstalledPackageLI(newPackage, true);
10064            }
10065            // Add back the old system package
10066            try {
10067                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10068            } catch (PackageManagerException e) {
10069                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10070            }
10071            // Restore the old system information in Settings
10072            synchronized(mPackages) {
10073                if (updatedSettings) {
10074                    mSettings.enableSystemPackageLPw(packageName);
10075                    mSettings.setInstallerPackageName(packageName,
10076                            oldPkgSetting.installerPackageName);
10077                }
10078                mSettings.writeLPr();
10079            }
10080        }
10081    }
10082
10083    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10084            int[] allUsers, boolean[] perUserInstalled,
10085            PackageInstalledInfo res) {
10086        String pkgName = newPackage.packageName;
10087        synchronized (mPackages) {
10088            //write settings. the installStatus will be incomplete at this stage.
10089            //note that the new package setting would have already been
10090            //added to mPackages. It hasn't been persisted yet.
10091            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10092            mSettings.writeLPr();
10093        }
10094
10095        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10096
10097        synchronized (mPackages) {
10098            updatePermissionsLPw(newPackage.packageName, newPackage,
10099                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10100                            ? UPDATE_PERMISSIONS_ALL : 0));
10101            // For system-bundled packages, we assume that installing an upgraded version
10102            // of the package implies that the user actually wants to run that new code,
10103            // so we enable the package.
10104            if (isSystemApp(newPackage)) {
10105                // NB: implicit assumption that system package upgrades apply to all users
10106                if (DEBUG_INSTALL) {
10107                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10108                }
10109                PackageSetting ps = mSettings.mPackages.get(pkgName);
10110                if (ps != null) {
10111                    if (res.origUsers != null) {
10112                        for (int userHandle : res.origUsers) {
10113                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10114                                    userHandle, installerPackageName);
10115                        }
10116                    }
10117                    // Also convey the prior install/uninstall state
10118                    if (allUsers != null && perUserInstalled != null) {
10119                        for (int i = 0; i < allUsers.length; i++) {
10120                            if (DEBUG_INSTALL) {
10121                                Slog.d(TAG, "    user " + allUsers[i]
10122                                        + " => " + perUserInstalled[i]);
10123                            }
10124                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10125                        }
10126                        // these install state changes will be persisted in the
10127                        // upcoming call to mSettings.writeLPr().
10128                    }
10129                }
10130            }
10131            res.name = pkgName;
10132            res.uid = newPackage.applicationInfo.uid;
10133            res.pkg = newPackage;
10134            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10135            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10136            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10137            //to update install status
10138            mSettings.writeLPr();
10139        }
10140    }
10141
10142    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10143        final int installFlags = args.installFlags;
10144        String installerPackageName = args.installerPackageName;
10145        File tmpPackageFile = new File(args.getCodePath());
10146        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10147        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10148        boolean replace = false;
10149        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10150        // Result object to be returned
10151        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10152
10153        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10154        // Retrieve PackageSettings and parse package
10155        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10156                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10157                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10158        PackageParser pp = new PackageParser();
10159        pp.setSeparateProcesses(mSeparateProcesses);
10160        pp.setDisplayMetrics(mMetrics);
10161
10162        final PackageParser.Package pkg;
10163        try {
10164            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10165        } catch (PackageParserException e) {
10166            res.setError("Failed parse during installPackageLI", e);
10167            return;
10168        }
10169
10170        // Mark that we have an install time CPU ABI override.
10171        pkg.cpuAbiOverride = args.abiOverride;
10172
10173        String pkgName = res.name = pkg.packageName;
10174        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10175            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10176                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10177                return;
10178            }
10179        }
10180
10181        try {
10182            pp.collectCertificates(pkg, parseFlags);
10183            pp.collectManifestDigest(pkg);
10184        } catch (PackageParserException e) {
10185            res.setError("Failed collect during installPackageLI", e);
10186            return;
10187        }
10188
10189        /* If the installer passed in a manifest digest, compare it now. */
10190        if (args.manifestDigest != null) {
10191            if (DEBUG_INSTALL) {
10192                final String parsedManifest = pkg.manifestDigest == null ? "null"
10193                        : pkg.manifestDigest.toString();
10194                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10195                        + parsedManifest);
10196            }
10197
10198            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10199                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10200                return;
10201            }
10202        } else if (DEBUG_INSTALL) {
10203            final String parsedManifest = pkg.manifestDigest == null
10204                    ? "null" : pkg.manifestDigest.toString();
10205            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10206        }
10207
10208        // Get rid of all references to package scan path via parser.
10209        pp = null;
10210        String oldCodePath = null;
10211        boolean systemApp = false;
10212        synchronized (mPackages) {
10213            // Check whether the newly-scanned package wants to define an already-defined perm
10214            int N = pkg.permissions.size();
10215            for (int i = N-1; i >= 0; i--) {
10216                PackageParser.Permission perm = pkg.permissions.get(i);
10217                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10218                if (bp != null) {
10219                    // If the defining package is signed with our cert, it's okay.  This
10220                    // also includes the "updating the same package" case, of course.
10221                    // "updating same package" could also involve key-rotation.
10222                    final boolean sigsOk;
10223                    if (!bp.sourcePackage.equals(pkg.packageName)
10224                            || !(bp.packageSetting instanceof PackageSetting)
10225                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10226                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10227                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10228                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10229                    } else {
10230                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10231                    }
10232                    if (!sigsOk) {
10233                        // If the owning package is the system itself, we log but allow
10234                        // install to proceed; we fail the install on all other permission
10235                        // redefinitions.
10236                        if (!bp.sourcePackage.equals("android")) {
10237                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10238                                    + pkg.packageName + " attempting to redeclare permission "
10239                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10240                            res.origPermission = perm.info.name;
10241                            res.origPackage = bp.sourcePackage;
10242                            return;
10243                        } else {
10244                            Slog.w(TAG, "Package " + pkg.packageName
10245                                    + " attempting to redeclare system permission "
10246                                    + perm.info.name + "; ignoring new declaration");
10247                            pkg.permissions.remove(i);
10248                        }
10249                    }
10250                }
10251            }
10252
10253            // Check if installing already existing package
10254            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10255                String oldName = mSettings.mRenamedPackages.get(pkgName);
10256                if (pkg.mOriginalPackages != null
10257                        && pkg.mOriginalPackages.contains(oldName)
10258                        && mPackages.containsKey(oldName)) {
10259                    // This package is derived from an original package,
10260                    // and this device has been updating from that original
10261                    // name.  We must continue using the original name, so
10262                    // rename the new package here.
10263                    pkg.setPackageName(oldName);
10264                    pkgName = pkg.packageName;
10265                    replace = true;
10266                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10267                            + oldName + " pkgName=" + pkgName);
10268                } else if (mPackages.containsKey(pkgName)) {
10269                    // This package, under its official name, already exists
10270                    // on the device; we should replace it.
10271                    replace = true;
10272                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10273                }
10274            }
10275            PackageSetting ps = mSettings.mPackages.get(pkgName);
10276            if (ps != null) {
10277                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10278                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10279                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10280                    systemApp = (ps.pkg.applicationInfo.flags &
10281                            ApplicationInfo.FLAG_SYSTEM) != 0;
10282                }
10283                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10284            }
10285        }
10286
10287        if (systemApp && onSd) {
10288            // Disable updates to system apps on sdcard
10289            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10290                    "Cannot install updates to system apps on sdcard");
10291            return;
10292        }
10293
10294        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10295            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10296            return;
10297        }
10298
10299        if (replace) {
10300            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10301                    installerPackageName, res);
10302        } else {
10303            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10304                    args.user, installerPackageName, res);
10305        }
10306        synchronized (mPackages) {
10307            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10308            if (ps != null) {
10309                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10310            }
10311        }
10312    }
10313
10314    private static boolean isForwardLocked(PackageParser.Package pkg) {
10315        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10316    }
10317
10318    private static boolean isForwardLocked(ApplicationInfo info) {
10319        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10320    }
10321
10322    private boolean isForwardLocked(PackageSetting ps) {
10323        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10324    }
10325
10326    private static boolean isMultiArch(PackageSetting ps) {
10327        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10328    }
10329
10330    private static boolean isMultiArch(ApplicationInfo info) {
10331        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10332    }
10333
10334    private static boolean isExternal(PackageParser.Package pkg) {
10335        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10336    }
10337
10338    private static boolean isExternal(PackageSetting ps) {
10339        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10340    }
10341
10342    private static boolean isExternal(ApplicationInfo info) {
10343        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10344    }
10345
10346    private static boolean isSystemApp(PackageParser.Package pkg) {
10347        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10348    }
10349
10350    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10351        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10352    }
10353
10354    private static boolean isSystemApp(ApplicationInfo info) {
10355        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10356    }
10357
10358    private static boolean isSystemApp(PackageSetting ps) {
10359        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10360    }
10361
10362    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10363        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10364    }
10365
10366    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10367        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10368    }
10369
10370    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10371        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10372    }
10373
10374    private int packageFlagsToInstallFlags(PackageSetting ps) {
10375        int installFlags = 0;
10376        if (isExternal(ps)) {
10377            installFlags |= PackageManager.INSTALL_EXTERNAL;
10378        }
10379        if (isForwardLocked(ps)) {
10380            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10381        }
10382        return installFlags;
10383    }
10384
10385    private void deleteTempPackageFiles() {
10386        final FilenameFilter filter = new FilenameFilter() {
10387            public boolean accept(File dir, String name) {
10388                return name.startsWith("vmdl") && name.endsWith(".tmp");
10389            }
10390        };
10391        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10392            file.delete();
10393        }
10394    }
10395
10396    @Override
10397    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10398            int flags) {
10399        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10400                flags);
10401    }
10402
10403    @Override
10404    public void deletePackage(final String packageName,
10405            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10406        mContext.enforceCallingOrSelfPermission(
10407                android.Manifest.permission.DELETE_PACKAGES, null);
10408        final int uid = Binder.getCallingUid();
10409        if (UserHandle.getUserId(uid) != userId) {
10410            mContext.enforceCallingPermission(
10411                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10412                    "deletePackage for user " + userId);
10413        }
10414        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10415            try {
10416                observer.onPackageDeleted(packageName,
10417                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10418            } catch (RemoteException re) {
10419            }
10420            return;
10421        }
10422
10423        boolean uninstallBlocked = false;
10424        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10425            int[] users = sUserManager.getUserIds();
10426            for (int i = 0; i < users.length; ++i) {
10427                if (getBlockUninstallForUser(packageName, users[i])) {
10428                    uninstallBlocked = true;
10429                    break;
10430                }
10431            }
10432        } else {
10433            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10434        }
10435        if (uninstallBlocked) {
10436            try {
10437                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10438                        null);
10439            } catch (RemoteException re) {
10440            }
10441            return;
10442        }
10443
10444        if (DEBUG_REMOVE) {
10445            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10446        }
10447        // Queue up an async operation since the package deletion may take a little while.
10448        mHandler.post(new Runnable() {
10449            public void run() {
10450                mHandler.removeCallbacks(this);
10451                final int returnCode = deletePackageX(packageName, userId, flags);
10452                if (observer != null) {
10453                    try {
10454                        observer.onPackageDeleted(packageName, returnCode, null);
10455                    } catch (RemoteException e) {
10456                        Log.i(TAG, "Observer no longer exists.");
10457                    } //end catch
10458                } //end if
10459            } //end run
10460        });
10461    }
10462
10463    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10464        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10465                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10466        try {
10467            if (dpm != null) {
10468                if (dpm.isDeviceOwner(packageName)) {
10469                    return true;
10470                }
10471                int[] users;
10472                if (userId == UserHandle.USER_ALL) {
10473                    users = sUserManager.getUserIds();
10474                } else {
10475                    users = new int[]{userId};
10476                }
10477                for (int i = 0; i < users.length; ++i) {
10478                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10479                        return true;
10480                    }
10481                }
10482            }
10483        } catch (RemoteException e) {
10484        }
10485        return false;
10486    }
10487
10488    /**
10489     *  This method is an internal method that could be get invoked either
10490     *  to delete an installed package or to clean up a failed installation.
10491     *  After deleting an installed package, a broadcast is sent to notify any
10492     *  listeners that the package has been installed. For cleaning up a failed
10493     *  installation, the broadcast is not necessary since the package's
10494     *  installation wouldn't have sent the initial broadcast either
10495     *  The key steps in deleting a package are
10496     *  deleting the package information in internal structures like mPackages,
10497     *  deleting the packages base directories through installd
10498     *  updating mSettings to reflect current status
10499     *  persisting settings for later use
10500     *  sending a broadcast if necessary
10501     */
10502    private int deletePackageX(String packageName, int userId, int flags) {
10503        final PackageRemovedInfo info = new PackageRemovedInfo();
10504        final boolean res;
10505
10506        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10507                ? UserHandle.ALL : new UserHandle(userId);
10508
10509        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10510            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10511            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10512        }
10513
10514        boolean removedForAllUsers = false;
10515        boolean systemUpdate = false;
10516
10517        // for the uninstall-updates case and restricted profiles, remember the per-
10518        // userhandle installed state
10519        int[] allUsers;
10520        boolean[] perUserInstalled;
10521        synchronized (mPackages) {
10522            PackageSetting ps = mSettings.mPackages.get(packageName);
10523            allUsers = sUserManager.getUserIds();
10524            perUserInstalled = new boolean[allUsers.length];
10525            for (int i = 0; i < allUsers.length; i++) {
10526                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10527            }
10528        }
10529
10530        synchronized (mInstallLock) {
10531            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10532            res = deletePackageLI(packageName, removeForUser,
10533                    true, allUsers, perUserInstalled,
10534                    flags | REMOVE_CHATTY, info, true);
10535            systemUpdate = info.isRemovedPackageSystemUpdate;
10536            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10537                removedForAllUsers = true;
10538            }
10539            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10540                    + " removedForAllUsers=" + removedForAllUsers);
10541        }
10542
10543        if (res) {
10544            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10545
10546            // If the removed package was a system update, the old system package
10547            // was re-enabled; we need to broadcast this information
10548            if (systemUpdate) {
10549                Bundle extras = new Bundle(1);
10550                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10551                        ? info.removedAppId : info.uid);
10552                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10553
10554                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10555                        extras, null, null, null);
10556                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10557                        extras, null, null, null);
10558                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10559                        null, packageName, null, null);
10560            }
10561        }
10562        // Force a gc here.
10563        Runtime.getRuntime().gc();
10564        // Delete the resources here after sending the broadcast to let
10565        // other processes clean up before deleting resources.
10566        if (info.args != null) {
10567            synchronized (mInstallLock) {
10568                info.args.doPostDeleteLI(true);
10569            }
10570        }
10571
10572        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10573    }
10574
10575    static class PackageRemovedInfo {
10576        String removedPackage;
10577        int uid = -1;
10578        int removedAppId = -1;
10579        int[] removedUsers = null;
10580        boolean isRemovedPackageSystemUpdate = false;
10581        // Clean up resources deleted packages.
10582        InstallArgs args = null;
10583
10584        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10585            Bundle extras = new Bundle(1);
10586            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10587            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10588            if (replacing) {
10589                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10590            }
10591            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10592            if (removedPackage != null) {
10593                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10594                        extras, null, null, removedUsers);
10595                if (fullRemove && !replacing) {
10596                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10597                            extras, null, null, removedUsers);
10598                }
10599            }
10600            if (removedAppId >= 0) {
10601                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10602                        removedUsers);
10603            }
10604        }
10605    }
10606
10607    /*
10608     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10609     * flag is not set, the data directory is removed as well.
10610     * make sure this flag is set for partially installed apps. If not its meaningless to
10611     * delete a partially installed application.
10612     */
10613    private void removePackageDataLI(PackageSetting ps,
10614            int[] allUserHandles, boolean[] perUserInstalled,
10615            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10616        String packageName = ps.name;
10617        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10618        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10619        // Retrieve object to delete permissions for shared user later on
10620        final PackageSetting deletedPs;
10621        // reader
10622        synchronized (mPackages) {
10623            deletedPs = mSettings.mPackages.get(packageName);
10624            if (outInfo != null) {
10625                outInfo.removedPackage = packageName;
10626                outInfo.removedUsers = deletedPs != null
10627                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10628                        : null;
10629            }
10630        }
10631        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10632            removeDataDirsLI(packageName);
10633            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10634        }
10635        // writer
10636        synchronized (mPackages) {
10637            if (deletedPs != null) {
10638                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10639                    if (outInfo != null) {
10640                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10641                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10642                    }
10643                    if (deletedPs != null) {
10644                        updatePermissionsLPw(deletedPs.name, null, 0);
10645                        if (deletedPs.sharedUser != null) {
10646                            // remove permissions associated with package
10647                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10648                        }
10649                    }
10650                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10651                }
10652                // make sure to preserve per-user disabled state if this removal was just
10653                // a downgrade of a system app to the factory package
10654                if (allUserHandles != null && perUserInstalled != null) {
10655                    if (DEBUG_REMOVE) {
10656                        Slog.d(TAG, "Propagating install state across downgrade");
10657                    }
10658                    for (int i = 0; i < allUserHandles.length; i++) {
10659                        if (DEBUG_REMOVE) {
10660                            Slog.d(TAG, "    user " + allUserHandles[i]
10661                                    + " => " + perUserInstalled[i]);
10662                        }
10663                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10664                    }
10665                }
10666            }
10667            // can downgrade to reader
10668            if (writeSettings) {
10669                // Save settings now
10670                mSettings.writeLPr();
10671            }
10672        }
10673        if (outInfo != null) {
10674            // A user ID was deleted here. Go through all users and remove it
10675            // from KeyStore.
10676            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10677        }
10678    }
10679
10680    static boolean locationIsPrivileged(File path) {
10681        try {
10682            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10683                    .getCanonicalPath();
10684            return path.getCanonicalPath().startsWith(privilegedAppDir);
10685        } catch (IOException e) {
10686            Slog.e(TAG, "Unable to access code path " + path);
10687        }
10688        return false;
10689    }
10690
10691    /*
10692     * Tries to delete system package.
10693     */
10694    private boolean deleteSystemPackageLI(PackageSetting newPs,
10695            int[] allUserHandles, boolean[] perUserInstalled,
10696            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10697        final boolean applyUserRestrictions
10698                = (allUserHandles != null) && (perUserInstalled != null);
10699        PackageSetting disabledPs = null;
10700        // Confirm if the system package has been updated
10701        // An updated system app can be deleted. This will also have to restore
10702        // the system pkg from system partition
10703        // reader
10704        synchronized (mPackages) {
10705            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10706        }
10707        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10708                + " disabledPs=" + disabledPs);
10709        if (disabledPs == null) {
10710            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10711            return false;
10712        } else if (DEBUG_REMOVE) {
10713            Slog.d(TAG, "Deleting system pkg from data partition");
10714        }
10715        if (DEBUG_REMOVE) {
10716            if (applyUserRestrictions) {
10717                Slog.d(TAG, "Remembering install states:");
10718                for (int i = 0; i < allUserHandles.length; i++) {
10719                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10720                }
10721            }
10722        }
10723        // Delete the updated package
10724        outInfo.isRemovedPackageSystemUpdate = true;
10725        if (disabledPs.versionCode < newPs.versionCode) {
10726            // Delete data for downgrades
10727            flags &= ~PackageManager.DELETE_KEEP_DATA;
10728        } else {
10729            // Preserve data by setting flag
10730            flags |= PackageManager.DELETE_KEEP_DATA;
10731        }
10732        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10733                allUserHandles, perUserInstalled, outInfo, writeSettings);
10734        if (!ret) {
10735            return false;
10736        }
10737        // writer
10738        synchronized (mPackages) {
10739            // Reinstate the old system package
10740            mSettings.enableSystemPackageLPw(newPs.name);
10741            // Remove any native libraries from the upgraded package.
10742            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10743        }
10744        // Install the system package
10745        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10746        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10747        if (locationIsPrivileged(disabledPs.codePath)) {
10748            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10749        }
10750
10751        final PackageParser.Package newPkg;
10752        try {
10753            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10754        } catch (PackageManagerException e) {
10755            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10756            return false;
10757        }
10758
10759        // writer
10760        synchronized (mPackages) {
10761            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10762            updatePermissionsLPw(newPkg.packageName, newPkg,
10763                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10764            if (applyUserRestrictions) {
10765                if (DEBUG_REMOVE) {
10766                    Slog.d(TAG, "Propagating install state across reinstall");
10767                }
10768                for (int i = 0; i < allUserHandles.length; i++) {
10769                    if (DEBUG_REMOVE) {
10770                        Slog.d(TAG, "    user " + allUserHandles[i]
10771                                + " => " + perUserInstalled[i]);
10772                    }
10773                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10774                }
10775                // Regardless of writeSettings we need to ensure that this restriction
10776                // state propagation is persisted
10777                mSettings.writeAllUsersPackageRestrictionsLPr();
10778            }
10779            // can downgrade to reader here
10780            if (writeSettings) {
10781                mSettings.writeLPr();
10782            }
10783        }
10784        return true;
10785    }
10786
10787    private boolean deleteInstalledPackageLI(PackageSetting ps,
10788            boolean deleteCodeAndResources, int flags,
10789            int[] allUserHandles, boolean[] perUserInstalled,
10790            PackageRemovedInfo outInfo, boolean writeSettings) {
10791        if (outInfo != null) {
10792            outInfo.uid = ps.appId;
10793        }
10794
10795        // Delete package data from internal structures and also remove data if flag is set
10796        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10797
10798        // Delete application code and resources
10799        if (deleteCodeAndResources && (outInfo != null)) {
10800            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10801                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10802                    getAppDexInstructionSets(ps));
10803            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10804        }
10805        return true;
10806    }
10807
10808    @Override
10809    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10810            int userId) {
10811        mContext.enforceCallingOrSelfPermission(
10812                android.Manifest.permission.DELETE_PACKAGES, null);
10813        synchronized (mPackages) {
10814            PackageSetting ps = mSettings.mPackages.get(packageName);
10815            if (ps == null) {
10816                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10817                return false;
10818            }
10819            if (!ps.getInstalled(userId)) {
10820                // Can't block uninstall for an app that is not installed or enabled.
10821                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
10822                return false;
10823            }
10824            ps.setBlockUninstall(blockUninstall, userId);
10825            mSettings.writePackageRestrictionsLPr(userId);
10826        }
10827        return true;
10828    }
10829
10830    @Override
10831    public boolean getBlockUninstallForUser(String packageName, int userId) {
10832        synchronized (mPackages) {
10833            PackageSetting ps = mSettings.mPackages.get(packageName);
10834            if (ps == null) {
10835                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
10836                return false;
10837            }
10838            return ps.getBlockUninstall(userId);
10839        }
10840    }
10841
10842    /*
10843     * This method handles package deletion in general
10844     */
10845    private boolean deletePackageLI(String packageName, UserHandle user,
10846            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
10847            int flags, PackageRemovedInfo outInfo,
10848            boolean writeSettings) {
10849        if (packageName == null) {
10850            Slog.w(TAG, "Attempt to delete null packageName.");
10851            return false;
10852        }
10853        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
10854        PackageSetting ps;
10855        boolean dataOnly = false;
10856        int removeUser = -1;
10857        int appId = -1;
10858        synchronized (mPackages) {
10859            ps = mSettings.mPackages.get(packageName);
10860            if (ps == null) {
10861                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
10862                return false;
10863            }
10864            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
10865                    && user.getIdentifier() != UserHandle.USER_ALL) {
10866                // The caller is asking that the package only be deleted for a single
10867                // user.  To do this, we just mark its uninstalled state and delete
10868                // its data.  If this is a system app, we only allow this to happen if
10869                // they have set the special DELETE_SYSTEM_APP which requests different
10870                // semantics than normal for uninstalling system apps.
10871                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
10872                ps.setUserState(user.getIdentifier(),
10873                        COMPONENT_ENABLED_STATE_DEFAULT,
10874                        false, //installed
10875                        true,  //stopped
10876                        true,  //notLaunched
10877                        false, //hidden
10878                        null, null, null,
10879                        false // blockUninstall
10880                        );
10881                if (!isSystemApp(ps)) {
10882                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
10883                        // Other user still have this package installed, so all
10884                        // we need to do is clear this user's data and save that
10885                        // it is uninstalled.
10886                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
10887                        removeUser = user.getIdentifier();
10888                        appId = ps.appId;
10889                        mSettings.writePackageRestrictionsLPr(removeUser);
10890                    } else {
10891                        // We need to set it back to 'installed' so the uninstall
10892                        // broadcasts will be sent correctly.
10893                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
10894                        ps.setInstalled(true, user.getIdentifier());
10895                    }
10896                } else {
10897                    // This is a system app, so we assume that the
10898                    // other users still have this package installed, so all
10899                    // we need to do is clear this user's data and save that
10900                    // it is uninstalled.
10901                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
10902                    removeUser = user.getIdentifier();
10903                    appId = ps.appId;
10904                    mSettings.writePackageRestrictionsLPr(removeUser);
10905                }
10906            }
10907        }
10908
10909        if (removeUser >= 0) {
10910            // From above, we determined that we are deleting this only
10911            // for a single user.  Continue the work here.
10912            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
10913            if (outInfo != null) {
10914                outInfo.removedPackage = packageName;
10915                outInfo.removedAppId = appId;
10916                outInfo.removedUsers = new int[] {removeUser};
10917            }
10918            mInstaller.clearUserData(packageName, removeUser);
10919            removeKeystoreDataIfNeeded(removeUser, appId);
10920            schedulePackageCleaning(packageName, removeUser, false);
10921            return true;
10922        }
10923
10924        if (dataOnly) {
10925            // Delete application data first
10926            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
10927            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
10928            return true;
10929        }
10930
10931        boolean ret = false;
10932        if (isSystemApp(ps)) {
10933            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
10934            // When an updated system application is deleted we delete the existing resources as well and
10935            // fall back to existing code in system partition
10936            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
10937                    flags, outInfo, writeSettings);
10938        } else {
10939            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
10940            // Kill application pre-emptively especially for apps on sd.
10941            killApplication(packageName, ps.appId, "uninstall pkg");
10942            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
10943                    allUserHandles, perUserInstalled,
10944                    outInfo, writeSettings);
10945        }
10946
10947        return ret;
10948    }
10949
10950    private final class ClearStorageConnection implements ServiceConnection {
10951        IMediaContainerService mContainerService;
10952
10953        @Override
10954        public void onServiceConnected(ComponentName name, IBinder service) {
10955            synchronized (this) {
10956                mContainerService = IMediaContainerService.Stub.asInterface(service);
10957                notifyAll();
10958            }
10959        }
10960
10961        @Override
10962        public void onServiceDisconnected(ComponentName name) {
10963        }
10964    }
10965
10966    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
10967        final boolean mounted;
10968        if (Environment.isExternalStorageEmulated()) {
10969            mounted = true;
10970        } else {
10971            final String status = Environment.getExternalStorageState();
10972
10973            mounted = status.equals(Environment.MEDIA_MOUNTED)
10974                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
10975        }
10976
10977        if (!mounted) {
10978            return;
10979        }
10980
10981        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
10982        int[] users;
10983        if (userId == UserHandle.USER_ALL) {
10984            users = sUserManager.getUserIds();
10985        } else {
10986            users = new int[] { userId };
10987        }
10988        final ClearStorageConnection conn = new ClearStorageConnection();
10989        if (mContext.bindServiceAsUser(
10990                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
10991            try {
10992                for (int curUser : users) {
10993                    long timeout = SystemClock.uptimeMillis() + 5000;
10994                    synchronized (conn) {
10995                        long now = SystemClock.uptimeMillis();
10996                        while (conn.mContainerService == null && now < timeout) {
10997                            try {
10998                                conn.wait(timeout - now);
10999                            } catch (InterruptedException e) {
11000                            }
11001                        }
11002                    }
11003                    if (conn.mContainerService == null) {
11004                        return;
11005                    }
11006
11007                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11008                    clearDirectory(conn.mContainerService,
11009                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11010                    if (allData) {
11011                        clearDirectory(conn.mContainerService,
11012                                userEnv.buildExternalStorageAppDataDirs(packageName));
11013                        clearDirectory(conn.mContainerService,
11014                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11015                    }
11016                }
11017            } finally {
11018                mContext.unbindService(conn);
11019            }
11020        }
11021    }
11022
11023    @Override
11024    public void clearApplicationUserData(final String packageName,
11025            final IPackageDataObserver observer, final int userId) {
11026        mContext.enforceCallingOrSelfPermission(
11027                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11028        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11029        // Queue up an async operation since the package deletion may take a little while.
11030        mHandler.post(new Runnable() {
11031            public void run() {
11032                mHandler.removeCallbacks(this);
11033                final boolean succeeded;
11034                synchronized (mInstallLock) {
11035                    succeeded = clearApplicationUserDataLI(packageName, userId);
11036                }
11037                clearExternalStorageDataSync(packageName, userId, true);
11038                if (succeeded) {
11039                    // invoke DeviceStorageMonitor's update method to clear any notifications
11040                    DeviceStorageMonitorInternal
11041                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11042                    if (dsm != null) {
11043                        dsm.checkMemory();
11044                    }
11045                }
11046                if(observer != null) {
11047                    try {
11048                        observer.onRemoveCompleted(packageName, succeeded);
11049                    } catch (RemoteException e) {
11050                        Log.i(TAG, "Observer no longer exists.");
11051                    }
11052                } //end if observer
11053            } //end run
11054        });
11055    }
11056
11057    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11058        if (packageName == null) {
11059            Slog.w(TAG, "Attempt to delete null packageName.");
11060            return false;
11061        }
11062
11063        // Try finding details about the requested package
11064        PackageParser.Package pkg;
11065        synchronized (mPackages) {
11066            pkg = mPackages.get(packageName);
11067            if (pkg == null) {
11068                final PackageSetting ps = mSettings.mPackages.get(packageName);
11069                if (ps != null) {
11070                    pkg = ps.pkg;
11071                }
11072            }
11073        }
11074
11075        if (pkg == null) {
11076            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11077        }
11078
11079        // Always delete data directories for package, even if we found no other
11080        // record of app. This helps users recover from UID mismatches without
11081        // resorting to a full data wipe.
11082        int retCode = mInstaller.clearUserData(packageName, userId);
11083        if (retCode < 0) {
11084            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11085            return false;
11086        }
11087
11088        if (pkg == null) {
11089            return false;
11090        }
11091
11092        if (pkg != null && pkg.applicationInfo != null) {
11093            final int appId = pkg.applicationInfo.uid;
11094            removeKeystoreDataIfNeeded(userId, appId);
11095        }
11096
11097        // Create a native library symlink only if we have native libraries
11098        // and if the native libraries are 32 bit libraries. We do not provide
11099        // this symlink for 64 bit libraries.
11100        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11101                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11102            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11103            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11104                Slog.w(TAG, "Failed linking native library dir");
11105                return false;
11106            }
11107        }
11108
11109        return true;
11110    }
11111
11112    /**
11113     * Remove entries from the keystore daemon. Will only remove it if the
11114     * {@code appId} is valid.
11115     */
11116    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11117        if (appId < 0) {
11118            return;
11119        }
11120
11121        final KeyStore keyStore = KeyStore.getInstance();
11122        if (keyStore != null) {
11123            if (userId == UserHandle.USER_ALL) {
11124                for (final int individual : sUserManager.getUserIds()) {
11125                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11126                }
11127            } else {
11128                keyStore.clearUid(UserHandle.getUid(userId, appId));
11129            }
11130        } else {
11131            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11132        }
11133    }
11134
11135    @Override
11136    public void deleteApplicationCacheFiles(final String packageName,
11137            final IPackageDataObserver observer) {
11138        mContext.enforceCallingOrSelfPermission(
11139                android.Manifest.permission.DELETE_CACHE_FILES, null);
11140        // Queue up an async operation since the package deletion may take a little while.
11141        final int userId = UserHandle.getCallingUserId();
11142        mHandler.post(new Runnable() {
11143            public void run() {
11144                mHandler.removeCallbacks(this);
11145                final boolean succeded;
11146                synchronized (mInstallLock) {
11147                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11148                }
11149                clearExternalStorageDataSync(packageName, userId, false);
11150                if(observer != null) {
11151                    try {
11152                        observer.onRemoveCompleted(packageName, succeded);
11153                    } catch (RemoteException e) {
11154                        Log.i(TAG, "Observer no longer exists.");
11155                    }
11156                } //end if observer
11157            } //end run
11158        });
11159    }
11160
11161    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11162        if (packageName == null) {
11163            Slog.w(TAG, "Attempt to delete null packageName.");
11164            return false;
11165        }
11166        PackageParser.Package p;
11167        synchronized (mPackages) {
11168            p = mPackages.get(packageName);
11169        }
11170        if (p == null) {
11171            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11172            return false;
11173        }
11174        final ApplicationInfo applicationInfo = p.applicationInfo;
11175        if (applicationInfo == null) {
11176            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11177            return false;
11178        }
11179        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11180        if (retCode < 0) {
11181            Slog.w(TAG, "Couldn't remove cache files for package: "
11182                       + packageName + " u" + userId);
11183            return false;
11184        }
11185        return true;
11186    }
11187
11188    @Override
11189    public void getPackageSizeInfo(final String packageName, int userHandle,
11190            final IPackageStatsObserver observer) {
11191        mContext.enforceCallingOrSelfPermission(
11192                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11193        if (packageName == null) {
11194            throw new IllegalArgumentException("Attempt to get size of null packageName");
11195        }
11196
11197        PackageStats stats = new PackageStats(packageName, userHandle);
11198
11199        /*
11200         * Queue up an async operation since the package measurement may take a
11201         * little while.
11202         */
11203        Message msg = mHandler.obtainMessage(INIT_COPY);
11204        msg.obj = new MeasureParams(stats, observer);
11205        mHandler.sendMessage(msg);
11206    }
11207
11208    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11209            PackageStats pStats) {
11210        if (packageName == null) {
11211            Slog.w(TAG, "Attempt to get size of null packageName.");
11212            return false;
11213        }
11214        PackageParser.Package p;
11215        boolean dataOnly = false;
11216        String libDirRoot = null;
11217        String asecPath = null;
11218        PackageSetting ps = null;
11219        synchronized (mPackages) {
11220            p = mPackages.get(packageName);
11221            ps = mSettings.mPackages.get(packageName);
11222            if(p == null) {
11223                dataOnly = true;
11224                if((ps == null) || (ps.pkg == null)) {
11225                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11226                    return false;
11227                }
11228                p = ps.pkg;
11229            }
11230            if (ps != null) {
11231                libDirRoot = ps.legacyNativeLibraryPathString;
11232            }
11233            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11234                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11235                if (secureContainerId != null) {
11236                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11237                }
11238            }
11239        }
11240        String publicSrcDir = null;
11241        if(!dataOnly) {
11242            final ApplicationInfo applicationInfo = p.applicationInfo;
11243            if (applicationInfo == null) {
11244                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11245                return false;
11246            }
11247            if (isForwardLocked(p)) {
11248                publicSrcDir = applicationInfo.getBaseResourcePath();
11249            }
11250        }
11251        // TODO: extend to measure size of split APKs
11252        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11253        // not just the first level.
11254        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11255        // just the primary.
11256        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11257        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11258                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11259        if (res < 0) {
11260            return false;
11261        }
11262
11263        // Fix-up for forward-locked applications in ASEC containers.
11264        if (!isExternal(p)) {
11265            pStats.codeSize += pStats.externalCodeSize;
11266            pStats.externalCodeSize = 0L;
11267        }
11268
11269        return true;
11270    }
11271
11272
11273    @Override
11274    public void addPackageToPreferred(String packageName) {
11275        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11276    }
11277
11278    @Override
11279    public void removePackageFromPreferred(String packageName) {
11280        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11281    }
11282
11283    @Override
11284    public List<PackageInfo> getPreferredPackages(int flags) {
11285        return new ArrayList<PackageInfo>();
11286    }
11287
11288    private int getUidTargetSdkVersionLockedLPr(int uid) {
11289        Object obj = mSettings.getUserIdLPr(uid);
11290        if (obj instanceof SharedUserSetting) {
11291            final SharedUserSetting sus = (SharedUserSetting) obj;
11292            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11293            final Iterator<PackageSetting> it = sus.packages.iterator();
11294            while (it.hasNext()) {
11295                final PackageSetting ps = it.next();
11296                if (ps.pkg != null) {
11297                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11298                    if (v < vers) vers = v;
11299                }
11300            }
11301            return vers;
11302        } else if (obj instanceof PackageSetting) {
11303            final PackageSetting ps = (PackageSetting) obj;
11304            if (ps.pkg != null) {
11305                return ps.pkg.applicationInfo.targetSdkVersion;
11306            }
11307        }
11308        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11309    }
11310
11311    @Override
11312    public void addPreferredActivity(IntentFilter filter, int match,
11313            ComponentName[] set, ComponentName activity, int userId) {
11314        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11315                "Adding preferred");
11316    }
11317
11318    private void addPreferredActivityInternal(IntentFilter filter, int match,
11319            ComponentName[] set, ComponentName activity, boolean always, int userId,
11320            String opname) {
11321        // writer
11322        int callingUid = Binder.getCallingUid();
11323        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11324        if (filter.countActions() == 0) {
11325            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11326            return;
11327        }
11328        synchronized (mPackages) {
11329            if (mContext.checkCallingOrSelfPermission(
11330                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11331                    != PackageManager.PERMISSION_GRANTED) {
11332                if (getUidTargetSdkVersionLockedLPr(callingUid)
11333                        < Build.VERSION_CODES.FROYO) {
11334                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11335                            + callingUid);
11336                    return;
11337                }
11338                mContext.enforceCallingOrSelfPermission(
11339                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11340            }
11341
11342            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11343            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11344                    + userId + ":");
11345            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11346            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11347            mSettings.writePackageRestrictionsLPr(userId);
11348        }
11349    }
11350
11351    @Override
11352    public void replacePreferredActivity(IntentFilter filter, int match,
11353            ComponentName[] set, ComponentName activity, int userId) {
11354        if (filter.countActions() != 1) {
11355            throw new IllegalArgumentException(
11356                    "replacePreferredActivity expects filter to have only 1 action.");
11357        }
11358        if (filter.countDataAuthorities() != 0
11359                || filter.countDataPaths() != 0
11360                || filter.countDataSchemes() > 1
11361                || filter.countDataTypes() != 0) {
11362            throw new IllegalArgumentException(
11363                    "replacePreferredActivity expects filter to have no data authorities, " +
11364                    "paths, or types; and at most one scheme.");
11365        }
11366
11367        final int callingUid = Binder.getCallingUid();
11368        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11369        synchronized (mPackages) {
11370            if (mContext.checkCallingOrSelfPermission(
11371                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11372                    != PackageManager.PERMISSION_GRANTED) {
11373                if (getUidTargetSdkVersionLockedLPr(callingUid)
11374                        < Build.VERSION_CODES.FROYO) {
11375                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11376                            + Binder.getCallingUid());
11377                    return;
11378                }
11379                mContext.enforceCallingOrSelfPermission(
11380                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11381            }
11382
11383            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11384            if (pir != null) {
11385                // Get all of the existing entries that exactly match this filter.
11386                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11387                if (existing != null && existing.size() == 1) {
11388                    PreferredActivity cur = existing.get(0);
11389                    if (DEBUG_PREFERRED) {
11390                        Slog.i(TAG, "Checking replace of preferred:");
11391                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11392                        if (!cur.mPref.mAlways) {
11393                            Slog.i(TAG, "  -- CUR; not mAlways!");
11394                        } else {
11395                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11396                            Slog.i(TAG, "  -- CUR: mSet="
11397                                    + Arrays.toString(cur.mPref.mSetComponents));
11398                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11399                            Slog.i(TAG, "  -- NEW: mMatch="
11400                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11401                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11402                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11403                        }
11404                    }
11405                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11406                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11407                            && cur.mPref.sameSet(set)) {
11408                        // Setting the preferred activity to what it happens to be already
11409                        if (DEBUG_PREFERRED) {
11410                            Slog.i(TAG, "Replacing with same preferred activity "
11411                                    + cur.mPref.mShortComponent + " for user "
11412                                    + userId + ":");
11413                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11414                        }
11415                        return;
11416                    }
11417                }
11418
11419                if (existing != null) {
11420                    if (DEBUG_PREFERRED) {
11421                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11422                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11423                    }
11424                    for (int i = 0; i < existing.size(); i++) {
11425                        PreferredActivity pa = existing.get(i);
11426                        if (DEBUG_PREFERRED) {
11427                            Slog.i(TAG, "Removing existing preferred activity "
11428                                    + pa.mPref.mComponent + ":");
11429                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11430                        }
11431                        pir.removeFilter(pa);
11432                    }
11433                }
11434            }
11435            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11436                    "Replacing preferred");
11437        }
11438    }
11439
11440    @Override
11441    public void clearPackagePreferredActivities(String packageName) {
11442        final int uid = Binder.getCallingUid();
11443        // writer
11444        synchronized (mPackages) {
11445            PackageParser.Package pkg = mPackages.get(packageName);
11446            if (pkg == null || pkg.applicationInfo.uid != uid) {
11447                if (mContext.checkCallingOrSelfPermission(
11448                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11449                        != PackageManager.PERMISSION_GRANTED) {
11450                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11451                            < Build.VERSION_CODES.FROYO) {
11452                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11453                                + Binder.getCallingUid());
11454                        return;
11455                    }
11456                    mContext.enforceCallingOrSelfPermission(
11457                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11458                }
11459            }
11460
11461            int user = UserHandle.getCallingUserId();
11462            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11463                mSettings.writePackageRestrictionsLPr(user);
11464                scheduleWriteSettingsLocked();
11465            }
11466        }
11467    }
11468
11469    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11470    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11471        ArrayList<PreferredActivity> removed = null;
11472        boolean changed = false;
11473        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11474            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11475            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11476            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11477                continue;
11478            }
11479            Iterator<PreferredActivity> it = pir.filterIterator();
11480            while (it.hasNext()) {
11481                PreferredActivity pa = it.next();
11482                // Mark entry for removal only if it matches the package name
11483                // and the entry is of type "always".
11484                if (packageName == null ||
11485                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11486                                && pa.mPref.mAlways)) {
11487                    if (removed == null) {
11488                        removed = new ArrayList<PreferredActivity>();
11489                    }
11490                    removed.add(pa);
11491                }
11492            }
11493            if (removed != null) {
11494                for (int j=0; j<removed.size(); j++) {
11495                    PreferredActivity pa = removed.get(j);
11496                    pir.removeFilter(pa);
11497                }
11498                changed = true;
11499            }
11500        }
11501        return changed;
11502    }
11503
11504    @Override
11505    public void resetPreferredActivities(int userId) {
11506        /* TODO: Actually use userId. Why is it being passed in? */
11507        mContext.enforceCallingOrSelfPermission(
11508                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11509        // writer
11510        synchronized (mPackages) {
11511            int user = UserHandle.getCallingUserId();
11512            clearPackagePreferredActivitiesLPw(null, user);
11513            mSettings.readDefaultPreferredAppsLPw(this, user);
11514            mSettings.writePackageRestrictionsLPr(user);
11515            scheduleWriteSettingsLocked();
11516        }
11517    }
11518
11519    @Override
11520    public int getPreferredActivities(List<IntentFilter> outFilters,
11521            List<ComponentName> outActivities, String packageName) {
11522
11523        int num = 0;
11524        final int userId = UserHandle.getCallingUserId();
11525        // reader
11526        synchronized (mPackages) {
11527            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11528            if (pir != null) {
11529                final Iterator<PreferredActivity> it = pir.filterIterator();
11530                while (it.hasNext()) {
11531                    final PreferredActivity pa = it.next();
11532                    if (packageName == null
11533                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11534                                    && pa.mPref.mAlways)) {
11535                        if (outFilters != null) {
11536                            outFilters.add(new IntentFilter(pa));
11537                        }
11538                        if (outActivities != null) {
11539                            outActivities.add(pa.mPref.mComponent);
11540                        }
11541                    }
11542                }
11543            }
11544        }
11545
11546        return num;
11547    }
11548
11549    @Override
11550    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11551            int userId) {
11552        int callingUid = Binder.getCallingUid();
11553        if (callingUid != Process.SYSTEM_UID) {
11554            throw new SecurityException(
11555                    "addPersistentPreferredActivity can only be run by the system");
11556        }
11557        if (filter.countActions() == 0) {
11558            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11559            return;
11560        }
11561        synchronized (mPackages) {
11562            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11563                    " :");
11564            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11565            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11566                    new PersistentPreferredActivity(filter, activity));
11567            mSettings.writePackageRestrictionsLPr(userId);
11568        }
11569    }
11570
11571    @Override
11572    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11573        int callingUid = Binder.getCallingUid();
11574        if (callingUid != Process.SYSTEM_UID) {
11575            throw new SecurityException(
11576                    "clearPackagePersistentPreferredActivities can only be run by the system");
11577        }
11578        ArrayList<PersistentPreferredActivity> removed = null;
11579        boolean changed = false;
11580        synchronized (mPackages) {
11581            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11582                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11583                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11584                        .valueAt(i);
11585                if (userId != thisUserId) {
11586                    continue;
11587                }
11588                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11589                while (it.hasNext()) {
11590                    PersistentPreferredActivity ppa = it.next();
11591                    // Mark entry for removal only if it matches the package name.
11592                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11593                        if (removed == null) {
11594                            removed = new ArrayList<PersistentPreferredActivity>();
11595                        }
11596                        removed.add(ppa);
11597                    }
11598                }
11599                if (removed != null) {
11600                    for (int j=0; j<removed.size(); j++) {
11601                        PersistentPreferredActivity ppa = removed.get(j);
11602                        ppir.removeFilter(ppa);
11603                    }
11604                    changed = true;
11605                }
11606            }
11607
11608            if (changed) {
11609                mSettings.writePackageRestrictionsLPr(userId);
11610            }
11611        }
11612    }
11613
11614    @Override
11615    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11616            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11617        mContext.enforceCallingOrSelfPermission(
11618                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11619        int callingUid = Binder.getCallingUid();
11620        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11621        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11622        if (intentFilter.countActions() == 0) {
11623            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11624            return;
11625        }
11626        synchronized (mPackages) {
11627            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11628                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11629            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11630            mSettings.writePackageRestrictionsLPr(sourceUserId);
11631        }
11632    }
11633
11634    @Override
11635    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11636            int ownerUserId) {
11637        mContext.enforceCallingOrSelfPermission(
11638                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11639        int callingUid = Binder.getCallingUid();
11640        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11641        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11642        int callingUserId = UserHandle.getUserId(callingUid);
11643        synchronized (mPackages) {
11644            CrossProfileIntentResolver resolver =
11645                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11646            HashSet<CrossProfileIntentFilter> set =
11647                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11648            for (CrossProfileIntentFilter filter : set) {
11649                if (filter.getOwnerPackage().equals(ownerPackage)
11650                        && filter.getOwnerUserId() == callingUserId) {
11651                    resolver.removeFilter(filter);
11652                }
11653            }
11654            mSettings.writePackageRestrictionsLPr(sourceUserId);
11655        }
11656    }
11657
11658    // Enforcing that callingUid is owning pkg on userId
11659    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11660        // The system owns everything.
11661        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11662            return;
11663        }
11664        int callingUserId = UserHandle.getUserId(callingUid);
11665        if (callingUserId != userId) {
11666            throw new SecurityException("calling uid " + callingUid
11667                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11668                    + callingUserId);
11669        }
11670        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11671        if (pi == null) {
11672            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11673                    + callingUserId);
11674        }
11675        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11676            throw new SecurityException("Calling uid " + callingUid
11677                    + " does not own package " + pkg);
11678        }
11679    }
11680
11681    @Override
11682    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11683        Intent intent = new Intent(Intent.ACTION_MAIN);
11684        intent.addCategory(Intent.CATEGORY_HOME);
11685
11686        final int callingUserId = UserHandle.getCallingUserId();
11687        List<ResolveInfo> list = queryIntentActivities(intent, null,
11688                PackageManager.GET_META_DATA, callingUserId);
11689        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11690                true, false, false, callingUserId);
11691
11692        allHomeCandidates.clear();
11693        if (list != null) {
11694            for (ResolveInfo ri : list) {
11695                allHomeCandidates.add(ri);
11696            }
11697        }
11698        return (preferred == null || preferred.activityInfo == null)
11699                ? null
11700                : new ComponentName(preferred.activityInfo.packageName,
11701                        preferred.activityInfo.name);
11702    }
11703
11704    @Override
11705    public void setApplicationEnabledSetting(String appPackageName,
11706            int newState, int flags, int userId, String callingPackage) {
11707        if (!sUserManager.exists(userId)) return;
11708        if (callingPackage == null) {
11709            callingPackage = Integer.toString(Binder.getCallingUid());
11710        }
11711        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11712    }
11713
11714    @Override
11715    public void setComponentEnabledSetting(ComponentName componentName,
11716            int newState, int flags, int userId) {
11717        if (!sUserManager.exists(userId)) return;
11718        setEnabledSetting(componentName.getPackageName(),
11719                componentName.getClassName(), newState, flags, userId, null);
11720    }
11721
11722    private void setEnabledSetting(final String packageName, String className, int newState,
11723            final int flags, int userId, String callingPackage) {
11724        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11725              || newState == COMPONENT_ENABLED_STATE_ENABLED
11726              || newState == COMPONENT_ENABLED_STATE_DISABLED
11727              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11728              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11729            throw new IllegalArgumentException("Invalid new component state: "
11730                    + newState);
11731        }
11732        PackageSetting pkgSetting;
11733        final int uid = Binder.getCallingUid();
11734        final int permission = mContext.checkCallingOrSelfPermission(
11735                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11736        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11737        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11738        boolean sendNow = false;
11739        boolean isApp = (className == null);
11740        String componentName = isApp ? packageName : className;
11741        int packageUid = -1;
11742        ArrayList<String> components;
11743
11744        // writer
11745        synchronized (mPackages) {
11746            pkgSetting = mSettings.mPackages.get(packageName);
11747            if (pkgSetting == null) {
11748                if (className == null) {
11749                    throw new IllegalArgumentException(
11750                            "Unknown package: " + packageName);
11751                }
11752                throw new IllegalArgumentException(
11753                        "Unknown component: " + packageName
11754                        + "/" + className);
11755            }
11756            // Allow root and verify that userId is not being specified by a different user
11757            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11758                throw new SecurityException(
11759                        "Permission Denial: attempt to change component state from pid="
11760                        + Binder.getCallingPid()
11761                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11762            }
11763            if (className == null) {
11764                // We're dealing with an application/package level state change
11765                if (pkgSetting.getEnabled(userId) == newState) {
11766                    // Nothing to do
11767                    return;
11768                }
11769                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11770                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11771                    // Don't care about who enables an app.
11772                    callingPackage = null;
11773                }
11774                pkgSetting.setEnabled(newState, userId, callingPackage);
11775                // pkgSetting.pkg.mSetEnabled = newState;
11776            } else {
11777                // We're dealing with a component level state change
11778                // First, verify that this is a valid class name.
11779                PackageParser.Package pkg = pkgSetting.pkg;
11780                if (pkg == null || !pkg.hasComponentClassName(className)) {
11781                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11782                        throw new IllegalArgumentException("Component class " + className
11783                                + " does not exist in " + packageName);
11784                    } else {
11785                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11786                                + className + " does not exist in " + packageName);
11787                    }
11788                }
11789                switch (newState) {
11790                case COMPONENT_ENABLED_STATE_ENABLED:
11791                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11792                        return;
11793                    }
11794                    break;
11795                case COMPONENT_ENABLED_STATE_DISABLED:
11796                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11797                        return;
11798                    }
11799                    break;
11800                case COMPONENT_ENABLED_STATE_DEFAULT:
11801                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11802                        return;
11803                    }
11804                    break;
11805                default:
11806                    Slog.e(TAG, "Invalid new component state: " + newState);
11807                    return;
11808                }
11809            }
11810            mSettings.writePackageRestrictionsLPr(userId);
11811            components = mPendingBroadcasts.get(userId, packageName);
11812            final boolean newPackage = components == null;
11813            if (newPackage) {
11814                components = new ArrayList<String>();
11815            }
11816            if (!components.contains(componentName)) {
11817                components.add(componentName);
11818            }
11819            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
11820                sendNow = true;
11821                // Purge entry from pending broadcast list if another one exists already
11822                // since we are sending one right away.
11823                mPendingBroadcasts.remove(userId, packageName);
11824            } else {
11825                if (newPackage) {
11826                    mPendingBroadcasts.put(userId, packageName, components);
11827                }
11828                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
11829                    // Schedule a message
11830                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
11831                }
11832            }
11833        }
11834
11835        long callingId = Binder.clearCallingIdentity();
11836        try {
11837            if (sendNow) {
11838                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
11839                sendPackageChangedBroadcast(packageName,
11840                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
11841            }
11842        } finally {
11843            Binder.restoreCallingIdentity(callingId);
11844        }
11845    }
11846
11847    private void sendPackageChangedBroadcast(String packageName,
11848            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
11849        if (DEBUG_INSTALL)
11850            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
11851                    + componentNames);
11852        Bundle extras = new Bundle(4);
11853        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
11854        String nameList[] = new String[componentNames.size()];
11855        componentNames.toArray(nameList);
11856        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
11857        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
11858        extras.putInt(Intent.EXTRA_UID, packageUid);
11859        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
11860                new int[] {UserHandle.getUserId(packageUid)});
11861    }
11862
11863    @Override
11864    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
11865        if (!sUserManager.exists(userId)) return;
11866        final int uid = Binder.getCallingUid();
11867        final int permission = mContext.checkCallingOrSelfPermission(
11868                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11869        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11870        enforceCrossUserPermission(uid, userId, true, true, "stop package");
11871        // writer
11872        synchronized (mPackages) {
11873            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
11874                    uid, userId)) {
11875                scheduleWritePackageRestrictionsLocked(userId);
11876            }
11877        }
11878    }
11879
11880    @Override
11881    public String getInstallerPackageName(String packageName) {
11882        // reader
11883        synchronized (mPackages) {
11884            return mSettings.getInstallerPackageNameLPr(packageName);
11885        }
11886    }
11887
11888    @Override
11889    public int getApplicationEnabledSetting(String packageName, int userId) {
11890        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11891        int uid = Binder.getCallingUid();
11892        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
11893        // reader
11894        synchronized (mPackages) {
11895            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
11896        }
11897    }
11898
11899    @Override
11900    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
11901        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
11902        int uid = Binder.getCallingUid();
11903        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
11904        // reader
11905        synchronized (mPackages) {
11906            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
11907        }
11908    }
11909
11910    @Override
11911    public void enterSafeMode() {
11912        enforceSystemOrRoot("Only the system can request entering safe mode");
11913
11914        if (!mSystemReady) {
11915            mSafeMode = true;
11916        }
11917    }
11918
11919    @Override
11920    public void systemReady() {
11921        mSystemReady = true;
11922
11923        // Read the compatibilty setting when the system is ready.
11924        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
11925                mContext.getContentResolver(),
11926                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
11927        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
11928        if (DEBUG_SETTINGS) {
11929            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
11930        }
11931
11932        synchronized (mPackages) {
11933            // Verify that all of the preferred activity components actually
11934            // exist.  It is possible for applications to be updated and at
11935            // that point remove a previously declared activity component that
11936            // had been set as a preferred activity.  We try to clean this up
11937            // the next time we encounter that preferred activity, but it is
11938            // possible for the user flow to never be able to return to that
11939            // situation so here we do a sanity check to make sure we haven't
11940            // left any junk around.
11941            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
11942            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11943                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11944                removed.clear();
11945                for (PreferredActivity pa : pir.filterSet()) {
11946                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
11947                        removed.add(pa);
11948                    }
11949                }
11950                if (removed.size() > 0) {
11951                    for (int r=0; r<removed.size(); r++) {
11952                        PreferredActivity pa = removed.get(r);
11953                        Slog.w(TAG, "Removing dangling preferred activity: "
11954                                + pa.mPref.mComponent);
11955                        pir.removeFilter(pa);
11956                    }
11957                    mSettings.writePackageRestrictionsLPr(
11958                            mSettings.mPreferredActivities.keyAt(i));
11959                }
11960            }
11961        }
11962        sUserManager.systemReady();
11963
11964        // Kick off any messages waiting for system ready
11965        if (mPostSystemReadyMessages != null) {
11966            for (Message msg : mPostSystemReadyMessages) {
11967                msg.sendToTarget();
11968            }
11969            mPostSystemReadyMessages = null;
11970        }
11971    }
11972
11973    @Override
11974    public boolean isSafeMode() {
11975        return mSafeMode;
11976    }
11977
11978    @Override
11979    public boolean hasSystemUidErrors() {
11980        return mHasSystemUidErrors;
11981    }
11982
11983    static String arrayToString(int[] array) {
11984        StringBuffer buf = new StringBuffer(128);
11985        buf.append('[');
11986        if (array != null) {
11987            for (int i=0; i<array.length; i++) {
11988                if (i > 0) buf.append(", ");
11989                buf.append(array[i]);
11990            }
11991        }
11992        buf.append(']');
11993        return buf.toString();
11994    }
11995
11996    static class DumpState {
11997        public static final int DUMP_LIBS = 1 << 0;
11998        public static final int DUMP_FEATURES = 1 << 1;
11999        public static final int DUMP_RESOLVERS = 1 << 2;
12000        public static final int DUMP_PERMISSIONS = 1 << 3;
12001        public static final int DUMP_PACKAGES = 1 << 4;
12002        public static final int DUMP_SHARED_USERS = 1 << 5;
12003        public static final int DUMP_MESSAGES = 1 << 6;
12004        public static final int DUMP_PROVIDERS = 1 << 7;
12005        public static final int DUMP_VERIFIERS = 1 << 8;
12006        public static final int DUMP_PREFERRED = 1 << 9;
12007        public static final int DUMP_PREFERRED_XML = 1 << 10;
12008        public static final int DUMP_KEYSETS = 1 << 11;
12009        public static final int DUMP_VERSION = 1 << 12;
12010        public static final int DUMP_INSTALLS = 1 << 13;
12011
12012        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12013
12014        private int mTypes;
12015
12016        private int mOptions;
12017
12018        private boolean mTitlePrinted;
12019
12020        private SharedUserSetting mSharedUser;
12021
12022        public boolean isDumping(int type) {
12023            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12024                return true;
12025            }
12026
12027            return (mTypes & type) != 0;
12028        }
12029
12030        public void setDump(int type) {
12031            mTypes |= type;
12032        }
12033
12034        public boolean isOptionEnabled(int option) {
12035            return (mOptions & option) != 0;
12036        }
12037
12038        public void setOptionEnabled(int option) {
12039            mOptions |= option;
12040        }
12041
12042        public boolean onTitlePrinted() {
12043            final boolean printed = mTitlePrinted;
12044            mTitlePrinted = true;
12045            return printed;
12046        }
12047
12048        public boolean getTitlePrinted() {
12049            return mTitlePrinted;
12050        }
12051
12052        public void setTitlePrinted(boolean enabled) {
12053            mTitlePrinted = enabled;
12054        }
12055
12056        public SharedUserSetting getSharedUser() {
12057            return mSharedUser;
12058        }
12059
12060        public void setSharedUser(SharedUserSetting user) {
12061            mSharedUser = user;
12062        }
12063    }
12064
12065    @Override
12066    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12067        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12068                != PackageManager.PERMISSION_GRANTED) {
12069            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12070                    + Binder.getCallingPid()
12071                    + ", uid=" + Binder.getCallingUid()
12072                    + " without permission "
12073                    + android.Manifest.permission.DUMP);
12074            return;
12075        }
12076
12077        DumpState dumpState = new DumpState();
12078        boolean fullPreferred = false;
12079        boolean checkin = false;
12080
12081        String packageName = null;
12082
12083        int opti = 0;
12084        while (opti < args.length) {
12085            String opt = args[opti];
12086            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12087                break;
12088            }
12089            opti++;
12090            if ("-a".equals(opt)) {
12091                // Right now we only know how to print all.
12092            } else if ("-h".equals(opt)) {
12093                pw.println("Package manager dump options:");
12094                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12095                pw.println("    --checkin: dump for a checkin");
12096                pw.println("    -f: print details of intent filters");
12097                pw.println("    -h: print this help");
12098                pw.println("  cmd may be one of:");
12099                pw.println("    l[ibraries]: list known shared libraries");
12100                pw.println("    f[ibraries]: list device features");
12101                pw.println("    k[eysets]: print known keysets");
12102                pw.println("    r[esolvers]: dump intent resolvers");
12103                pw.println("    perm[issions]: dump permissions");
12104                pw.println("    pref[erred]: print preferred package settings");
12105                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12106                pw.println("    prov[iders]: dump content providers");
12107                pw.println("    p[ackages]: dump installed packages");
12108                pw.println("    s[hared-users]: dump shared user IDs");
12109                pw.println("    m[essages]: print collected runtime messages");
12110                pw.println("    v[erifiers]: print package verifier info");
12111                pw.println("    version: print database version info");
12112                pw.println("    write: write current settings now");
12113                pw.println("    <package.name>: info about given package");
12114                pw.println("    installs: details about install sessions");
12115                return;
12116            } else if ("--checkin".equals(opt)) {
12117                checkin = true;
12118            } else if ("-f".equals(opt)) {
12119                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12120            } else {
12121                pw.println("Unknown argument: " + opt + "; use -h for help");
12122            }
12123        }
12124
12125        // Is the caller requesting to dump a particular piece of data?
12126        if (opti < args.length) {
12127            String cmd = args[opti];
12128            opti++;
12129            // Is this a package name?
12130            if ("android".equals(cmd) || cmd.contains(".")) {
12131                packageName = cmd;
12132                // When dumping a single package, we always dump all of its
12133                // filter information since the amount of data will be reasonable.
12134                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12135            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12136                dumpState.setDump(DumpState.DUMP_LIBS);
12137            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12138                dumpState.setDump(DumpState.DUMP_FEATURES);
12139            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12140                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12141            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12142                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12143            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12144                dumpState.setDump(DumpState.DUMP_PREFERRED);
12145            } else if ("preferred-xml".equals(cmd)) {
12146                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12147                if (opti < args.length && "--full".equals(args[opti])) {
12148                    fullPreferred = true;
12149                    opti++;
12150                }
12151            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12152                dumpState.setDump(DumpState.DUMP_PACKAGES);
12153            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12154                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12155            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12156                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12157            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12158                dumpState.setDump(DumpState.DUMP_MESSAGES);
12159            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12160                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12161            } else if ("version".equals(cmd)) {
12162                dumpState.setDump(DumpState.DUMP_VERSION);
12163            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12164                dumpState.setDump(DumpState.DUMP_KEYSETS);
12165            } else if ("installs".equals(cmd)) {
12166                dumpState.setDump(DumpState.DUMP_INSTALLS);
12167            } else if ("write".equals(cmd)) {
12168                synchronized (mPackages) {
12169                    mSettings.writeLPr();
12170                    pw.println("Settings written.");
12171                    return;
12172                }
12173            }
12174        }
12175
12176        if (checkin) {
12177            pw.println("vers,1");
12178        }
12179
12180        // reader
12181        synchronized (mPackages) {
12182            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12183                if (!checkin) {
12184                    if (dumpState.onTitlePrinted())
12185                        pw.println();
12186                    pw.println("Database versions:");
12187                    pw.print("  SDK Version:");
12188                    pw.print(" internal=");
12189                    pw.print(mSettings.mInternalSdkPlatform);
12190                    pw.print(" external=");
12191                    pw.println(mSettings.mExternalSdkPlatform);
12192                    pw.print("  DB Version:");
12193                    pw.print(" internal=");
12194                    pw.print(mSettings.mInternalDatabaseVersion);
12195                    pw.print(" external=");
12196                    pw.println(mSettings.mExternalDatabaseVersion);
12197                }
12198            }
12199
12200            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12201                if (!checkin) {
12202                    if (dumpState.onTitlePrinted())
12203                        pw.println();
12204                    pw.println("Verifiers:");
12205                    pw.print("  Required: ");
12206                    pw.print(mRequiredVerifierPackage);
12207                    pw.print(" (uid=");
12208                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12209                    pw.println(")");
12210                } else if (mRequiredVerifierPackage != null) {
12211                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12212                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12213                }
12214            }
12215
12216            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12217                boolean printedHeader = false;
12218                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12219                while (it.hasNext()) {
12220                    String name = it.next();
12221                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12222                    if (!checkin) {
12223                        if (!printedHeader) {
12224                            if (dumpState.onTitlePrinted())
12225                                pw.println();
12226                            pw.println("Libraries:");
12227                            printedHeader = true;
12228                        }
12229                        pw.print("  ");
12230                    } else {
12231                        pw.print("lib,");
12232                    }
12233                    pw.print(name);
12234                    if (!checkin) {
12235                        pw.print(" -> ");
12236                    }
12237                    if (ent.path != null) {
12238                        if (!checkin) {
12239                            pw.print("(jar) ");
12240                            pw.print(ent.path);
12241                        } else {
12242                            pw.print(",jar,");
12243                            pw.print(ent.path);
12244                        }
12245                    } else {
12246                        if (!checkin) {
12247                            pw.print("(apk) ");
12248                            pw.print(ent.apk);
12249                        } else {
12250                            pw.print(",apk,");
12251                            pw.print(ent.apk);
12252                        }
12253                    }
12254                    pw.println();
12255                }
12256            }
12257
12258            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12259                if (dumpState.onTitlePrinted())
12260                    pw.println();
12261                if (!checkin) {
12262                    pw.println("Features:");
12263                }
12264                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12265                while (it.hasNext()) {
12266                    String name = it.next();
12267                    if (!checkin) {
12268                        pw.print("  ");
12269                    } else {
12270                        pw.print("feat,");
12271                    }
12272                    pw.println(name);
12273                }
12274            }
12275
12276            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12277                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12278                        : "Activity Resolver Table:", "  ", packageName,
12279                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12280                    dumpState.setTitlePrinted(true);
12281                }
12282                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12283                        : "Receiver Resolver Table:", "  ", packageName,
12284                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12285                    dumpState.setTitlePrinted(true);
12286                }
12287                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12288                        : "Service Resolver Table:", "  ", packageName,
12289                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12290                    dumpState.setTitlePrinted(true);
12291                }
12292                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12293                        : "Provider Resolver Table:", "  ", packageName,
12294                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12295                    dumpState.setTitlePrinted(true);
12296                }
12297            }
12298
12299            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12300                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12301                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12302                    int user = mSettings.mPreferredActivities.keyAt(i);
12303                    if (pir.dump(pw,
12304                            dumpState.getTitlePrinted()
12305                                ? "\nPreferred Activities User " + user + ":"
12306                                : "Preferred Activities User " + user + ":", "  ",
12307                            packageName, true)) {
12308                        dumpState.setTitlePrinted(true);
12309                    }
12310                }
12311            }
12312
12313            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12314                pw.flush();
12315                FileOutputStream fout = new FileOutputStream(fd);
12316                BufferedOutputStream str = new BufferedOutputStream(fout);
12317                XmlSerializer serializer = new FastXmlSerializer();
12318                try {
12319                    serializer.setOutput(str, "utf-8");
12320                    serializer.startDocument(null, true);
12321                    serializer.setFeature(
12322                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12323                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12324                    serializer.endDocument();
12325                    serializer.flush();
12326                } catch (IllegalArgumentException e) {
12327                    pw.println("Failed writing: " + e);
12328                } catch (IllegalStateException e) {
12329                    pw.println("Failed writing: " + e);
12330                } catch (IOException e) {
12331                    pw.println("Failed writing: " + e);
12332                }
12333            }
12334
12335            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12336                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12337                if (packageName == null) {
12338                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12339                        if (iperm == 0) {
12340                            if (dumpState.onTitlePrinted())
12341                                pw.println();
12342                            pw.println("AppOp Permissions:");
12343                        }
12344                        pw.print("  AppOp Permission ");
12345                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12346                        pw.println(":");
12347                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12348                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12349                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12350                        }
12351                    }
12352                }
12353            }
12354
12355            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12356                boolean printedSomething = false;
12357                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12358                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12359                        continue;
12360                    }
12361                    if (!printedSomething) {
12362                        if (dumpState.onTitlePrinted())
12363                            pw.println();
12364                        pw.println("Registered ContentProviders:");
12365                        printedSomething = true;
12366                    }
12367                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12368                    pw.print("    "); pw.println(p.toString());
12369                }
12370                printedSomething = false;
12371                for (Map.Entry<String, PackageParser.Provider> entry :
12372                        mProvidersByAuthority.entrySet()) {
12373                    PackageParser.Provider p = entry.getValue();
12374                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12375                        continue;
12376                    }
12377                    if (!printedSomething) {
12378                        if (dumpState.onTitlePrinted())
12379                            pw.println();
12380                        pw.println("ContentProvider Authorities:");
12381                        printedSomething = true;
12382                    }
12383                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12384                    pw.print("    "); pw.println(p.toString());
12385                    if (p.info != null && p.info.applicationInfo != null) {
12386                        final String appInfo = p.info.applicationInfo.toString();
12387                        pw.print("      applicationInfo="); pw.println(appInfo);
12388                    }
12389                }
12390            }
12391
12392            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12393                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12394            }
12395
12396            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12397                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12398            }
12399
12400            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12401                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12402            }
12403
12404            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12405                // XXX should handle packageName != null by dumping only install data that
12406                // the given package is involved with.
12407                if (dumpState.onTitlePrinted()) pw.println();
12408                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12409            }
12410
12411            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12412                if (dumpState.onTitlePrinted()) pw.println();
12413                mSettings.dumpReadMessagesLPr(pw, dumpState);
12414
12415                pw.println();
12416                pw.println("Package warning messages:");
12417                final File fname = getSettingsProblemFile();
12418                FileInputStream in = null;
12419                try {
12420                    in = new FileInputStream(fname);
12421                    final int avail = in.available();
12422                    final byte[] data = new byte[avail];
12423                    in.read(data);
12424                    pw.print(new String(data));
12425                } catch (FileNotFoundException e) {
12426                } catch (IOException e) {
12427                } finally {
12428                    if (in != null) {
12429                        try {
12430                            in.close();
12431                        } catch (IOException e) {
12432                        }
12433                    }
12434                }
12435            }
12436        }
12437    }
12438
12439    // ------- apps on sdcard specific code -------
12440    static final boolean DEBUG_SD_INSTALL = false;
12441
12442    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12443
12444    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12445
12446    private boolean mMediaMounted = false;
12447
12448    static String getEncryptKey() {
12449        try {
12450            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12451                    SD_ENCRYPTION_KEYSTORE_NAME);
12452            if (sdEncKey == null) {
12453                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12454                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12455                if (sdEncKey == null) {
12456                    Slog.e(TAG, "Failed to create encryption keys");
12457                    return null;
12458                }
12459            }
12460            return sdEncKey;
12461        } catch (NoSuchAlgorithmException nsae) {
12462            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12463            return null;
12464        } catch (IOException ioe) {
12465            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12466            return null;
12467        }
12468    }
12469
12470    /*
12471     * Update media status on PackageManager.
12472     */
12473    @Override
12474    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12475        int callingUid = Binder.getCallingUid();
12476        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12477            throw new SecurityException("Media status can only be updated by the system");
12478        }
12479        // reader; this apparently protects mMediaMounted, but should probably
12480        // be a different lock in that case.
12481        synchronized (mPackages) {
12482            Log.i(TAG, "Updating external media status from "
12483                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12484                    + (mediaStatus ? "mounted" : "unmounted"));
12485            if (DEBUG_SD_INSTALL)
12486                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12487                        + ", mMediaMounted=" + mMediaMounted);
12488            if (mediaStatus == mMediaMounted) {
12489                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12490                        : 0, -1);
12491                mHandler.sendMessage(msg);
12492                return;
12493            }
12494            mMediaMounted = mediaStatus;
12495        }
12496        // Queue up an async operation since the package installation may take a
12497        // little while.
12498        mHandler.post(new Runnable() {
12499            public void run() {
12500                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12501            }
12502        });
12503    }
12504
12505    /**
12506     * Called by MountService when the initial ASECs to scan are available.
12507     * Should block until all the ASEC containers are finished being scanned.
12508     */
12509    public void scanAvailableAsecs() {
12510        updateExternalMediaStatusInner(true, false, false);
12511        if (mShouldRestoreconData) {
12512            SELinuxMMAC.setRestoreconDone();
12513            mShouldRestoreconData = false;
12514        }
12515    }
12516
12517    /*
12518     * Collect information of applications on external media, map them against
12519     * existing containers and update information based on current mount status.
12520     * Please note that we always have to report status if reportStatus has been
12521     * set to true especially when unloading packages.
12522     */
12523    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12524            boolean externalStorage) {
12525        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12526        int[] uidArr = EmptyArray.INT;
12527
12528        final String[] list = PackageHelper.getSecureContainerList();
12529        if (ArrayUtils.isEmpty(list)) {
12530            Log.i(TAG, "No secure containers found");
12531        } else {
12532            // Process list of secure containers and categorize them
12533            // as active or stale based on their package internal state.
12534
12535            // reader
12536            synchronized (mPackages) {
12537                for (String cid : list) {
12538                    // Leave stages untouched for now; installer service owns them
12539                    if (PackageInstallerService.isStageName(cid)) continue;
12540
12541                    if (DEBUG_SD_INSTALL)
12542                        Log.i(TAG, "Processing container " + cid);
12543                    String pkgName = getAsecPackageName(cid);
12544                    if (pkgName == null) {
12545                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12546                        continue;
12547                    }
12548                    if (DEBUG_SD_INSTALL)
12549                        Log.i(TAG, "Looking for pkg : " + pkgName);
12550
12551                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12552                    if (ps == null) {
12553                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12554                        continue;
12555                    }
12556
12557                    /*
12558                     * Skip packages that are not external if we're unmounting
12559                     * external storage.
12560                     */
12561                    if (externalStorage && !isMounted && !isExternal(ps)) {
12562                        continue;
12563                    }
12564
12565                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12566                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12567                    // The package status is changed only if the code path
12568                    // matches between settings and the container id.
12569                    if (ps.codePathString != null
12570                            && ps.codePathString.startsWith(args.getCodePath())) {
12571                        if (DEBUG_SD_INSTALL) {
12572                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12573                                    + " at code path: " + ps.codePathString);
12574                        }
12575
12576                        // We do have a valid package installed on sdcard
12577                        processCids.put(args, ps.codePathString);
12578                        final int uid = ps.appId;
12579                        if (uid != -1) {
12580                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12581                        }
12582                    } else {
12583                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12584                                + ps.codePathString);
12585                    }
12586                }
12587            }
12588
12589            Arrays.sort(uidArr);
12590        }
12591
12592        // Process packages with valid entries.
12593        if (isMounted) {
12594            if (DEBUG_SD_INSTALL)
12595                Log.i(TAG, "Loading packages");
12596            loadMediaPackages(processCids, uidArr);
12597            startCleaningPackages();
12598            mInstallerService.onSecureContainersAvailable();
12599        } else {
12600            if (DEBUG_SD_INSTALL)
12601                Log.i(TAG, "Unloading packages");
12602            unloadMediaPackages(processCids, uidArr, reportStatus);
12603        }
12604    }
12605
12606    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12607            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12608        int size = pkgList.size();
12609        if (size > 0) {
12610            // Send broadcasts here
12611            Bundle extras = new Bundle();
12612            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12613                    .toArray(new String[size]));
12614            if (uidArr != null) {
12615                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12616            }
12617            if (replacing) {
12618                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12619            }
12620            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12621                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12622            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12623        }
12624    }
12625
12626   /*
12627     * Look at potentially valid container ids from processCids If package
12628     * information doesn't match the one on record or package scanning fails,
12629     * the cid is added to list of removeCids. We currently don't delete stale
12630     * containers.
12631     */
12632    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12633        ArrayList<String> pkgList = new ArrayList<String>();
12634        Set<AsecInstallArgs> keys = processCids.keySet();
12635
12636        for (AsecInstallArgs args : keys) {
12637            String codePath = processCids.get(args);
12638            if (DEBUG_SD_INSTALL)
12639                Log.i(TAG, "Loading container : " + args.cid);
12640            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12641            try {
12642                // Make sure there are no container errors first.
12643                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12644                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12645                            + " when installing from sdcard");
12646                    continue;
12647                }
12648                // Check code path here.
12649                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12650                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12651                            + " does not match one in settings " + codePath);
12652                    continue;
12653                }
12654                // Parse package
12655                int parseFlags = mDefParseFlags;
12656                if (args.isExternal()) {
12657                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12658                }
12659                if (args.isFwdLocked()) {
12660                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12661                }
12662
12663                synchronized (mInstallLock) {
12664                    PackageParser.Package pkg = null;
12665                    try {
12666                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12667                    } catch (PackageManagerException e) {
12668                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12669                    }
12670                    // Scan the package
12671                    if (pkg != null) {
12672                        /*
12673                         * TODO why is the lock being held? doPostInstall is
12674                         * called in other places without the lock. This needs
12675                         * to be straightened out.
12676                         */
12677                        // writer
12678                        synchronized (mPackages) {
12679                            retCode = PackageManager.INSTALL_SUCCEEDED;
12680                            pkgList.add(pkg.packageName);
12681                            // Post process args
12682                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12683                                    pkg.applicationInfo.uid);
12684                        }
12685                    } else {
12686                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12687                    }
12688                }
12689
12690            } finally {
12691                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12692                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12693                }
12694            }
12695        }
12696        // writer
12697        synchronized (mPackages) {
12698            // If the platform SDK has changed since the last time we booted,
12699            // we need to re-grant app permission to catch any new ones that
12700            // appear. This is really a hack, and means that apps can in some
12701            // cases get permissions that the user didn't initially explicitly
12702            // allow... it would be nice to have some better way to handle
12703            // this situation.
12704            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12705            if (regrantPermissions)
12706                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12707                        + mSdkVersion + "; regranting permissions for external storage");
12708            mSettings.mExternalSdkPlatform = mSdkVersion;
12709
12710            // Make sure group IDs have been assigned, and any permission
12711            // changes in other apps are accounted for
12712            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12713                    | (regrantPermissions
12714                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12715                            : 0));
12716
12717            mSettings.updateExternalDatabaseVersion();
12718
12719            // can downgrade to reader
12720            // Persist settings
12721            mSettings.writeLPr();
12722        }
12723        // Send a broadcast to let everyone know we are done processing
12724        if (pkgList.size() > 0) {
12725            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12726        }
12727    }
12728
12729   /*
12730     * Utility method to unload a list of specified containers
12731     */
12732    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12733        // Just unmount all valid containers.
12734        for (AsecInstallArgs arg : cidArgs) {
12735            synchronized (mInstallLock) {
12736                arg.doPostDeleteLI(false);
12737           }
12738       }
12739   }
12740
12741    /*
12742     * Unload packages mounted on external media. This involves deleting package
12743     * data from internal structures, sending broadcasts about diabled packages,
12744     * gc'ing to free up references, unmounting all secure containers
12745     * corresponding to packages on external media, and posting a
12746     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12747     * that we always have to post this message if status has been requested no
12748     * matter what.
12749     */
12750    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12751            final boolean reportStatus) {
12752        if (DEBUG_SD_INSTALL)
12753            Log.i(TAG, "unloading media packages");
12754        ArrayList<String> pkgList = new ArrayList<String>();
12755        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12756        final Set<AsecInstallArgs> keys = processCids.keySet();
12757        for (AsecInstallArgs args : keys) {
12758            String pkgName = args.getPackageName();
12759            if (DEBUG_SD_INSTALL)
12760                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12761            // Delete package internally
12762            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12763            synchronized (mInstallLock) {
12764                boolean res = deletePackageLI(pkgName, null, false, null, null,
12765                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12766                if (res) {
12767                    pkgList.add(pkgName);
12768                } else {
12769                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12770                    failedList.add(args);
12771                }
12772            }
12773        }
12774
12775        // reader
12776        synchronized (mPackages) {
12777            // We didn't update the settings after removing each package;
12778            // write them now for all packages.
12779            mSettings.writeLPr();
12780        }
12781
12782        // We have to absolutely send UPDATED_MEDIA_STATUS only
12783        // after confirming that all the receivers processed the ordered
12784        // broadcast when packages get disabled, force a gc to clean things up.
12785        // and unload all the containers.
12786        if (pkgList.size() > 0) {
12787            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12788                    new IIntentReceiver.Stub() {
12789                public void performReceive(Intent intent, int resultCode, String data,
12790                        Bundle extras, boolean ordered, boolean sticky,
12791                        int sendingUser) throws RemoteException {
12792                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12793                            reportStatus ? 1 : 0, 1, keys);
12794                    mHandler.sendMessage(msg);
12795                }
12796            });
12797        } else {
12798            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12799                    keys);
12800            mHandler.sendMessage(msg);
12801        }
12802    }
12803
12804    /** Binder call */
12805    @Override
12806    public void movePackage(final String packageName, final IPackageMoveObserver observer,
12807            final int flags) {
12808        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
12809        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
12810        int returnCode = PackageManager.MOVE_SUCCEEDED;
12811        int currInstallFlags = 0;
12812        int newInstallFlags = 0;
12813
12814        File codeFile = null;
12815        String installerPackageName = null;
12816        String packageAbiOverride = null;
12817
12818        // reader
12819        synchronized (mPackages) {
12820            final PackageParser.Package pkg = mPackages.get(packageName);
12821            final PackageSetting ps = mSettings.mPackages.get(packageName);
12822            if (pkg == null || ps == null) {
12823                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
12824            } else {
12825                // Disable moving fwd locked apps and system packages
12826                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
12827                    Slog.w(TAG, "Cannot move system application");
12828                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
12829                } else if (pkg.mOperationPending) {
12830                    Slog.w(TAG, "Attempt to move package which has pending operations");
12831                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
12832                } else {
12833                    // Find install location first
12834                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12835                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
12836                        Slog.w(TAG, "Ambigous flags specified for move location.");
12837                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12838                    } else {
12839                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
12840                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12841                        currInstallFlags = isExternal(pkg)
12842                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
12843
12844                        if (newInstallFlags == currInstallFlags) {
12845                            Slog.w(TAG, "No move required. Trying to move to same location");
12846                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
12847                        } else {
12848                            if (isForwardLocked(pkg)) {
12849                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12850                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
12851                            }
12852                        }
12853                    }
12854                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
12855                        pkg.mOperationPending = true;
12856                    }
12857                }
12858
12859                codeFile = new File(pkg.codePath);
12860                installerPackageName = ps.installerPackageName;
12861                packageAbiOverride = ps.cpuAbiOverrideString;
12862            }
12863        }
12864
12865        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
12866            try {
12867                observer.packageMoved(packageName, returnCode);
12868            } catch (RemoteException ignored) {
12869            }
12870            return;
12871        }
12872
12873        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
12874            @Override
12875            public void onUserActionRequired(Intent intent) throws RemoteException {
12876                throw new IllegalStateException();
12877            }
12878
12879            @Override
12880            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
12881                    Bundle extras) throws RemoteException {
12882                Slog.d(TAG, "Install result for move: "
12883                        + PackageManager.installStatusToString(returnCode, msg));
12884
12885                // We usually have a new package now after the install, but if
12886                // we failed we need to clear the pending flag on the original
12887                // package object.
12888                synchronized (mPackages) {
12889                    final PackageParser.Package pkg = mPackages.get(packageName);
12890                    if (pkg != null) {
12891                        pkg.mOperationPending = false;
12892                    }
12893                }
12894
12895                final int status = PackageManager.installStatusToPublicStatus(returnCode);
12896                switch (status) {
12897                    case PackageInstaller.STATUS_SUCCESS:
12898                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
12899                        break;
12900                    case PackageInstaller.STATUS_FAILURE_STORAGE:
12901                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
12902                        break;
12903                    default:
12904                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
12905                        break;
12906                }
12907            }
12908        };
12909
12910        // Treat a move like reinstalling an existing app, which ensures that we
12911        // process everythign uniformly, like unpacking native libraries.
12912        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
12913
12914        final Message msg = mHandler.obtainMessage(INIT_COPY);
12915        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
12916        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
12917                installerPackageName, null, user, packageAbiOverride);
12918        mHandler.sendMessage(msg);
12919    }
12920
12921    @Override
12922    public boolean setInstallLocation(int loc) {
12923        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
12924                null);
12925        if (getInstallLocation() == loc) {
12926            return true;
12927        }
12928        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
12929                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
12930            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
12931                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
12932            return true;
12933        }
12934        return false;
12935   }
12936
12937    @Override
12938    public int getInstallLocation() {
12939        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
12940                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
12941                PackageHelper.APP_INSTALL_AUTO);
12942    }
12943
12944    /** Called by UserManagerService */
12945    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
12946        mDirtyUsers.remove(userHandle);
12947        mSettings.removeUserLPw(userHandle);
12948        mPendingBroadcasts.remove(userHandle);
12949        if (mInstaller != null) {
12950            // Technically, we shouldn't be doing this with the package lock
12951            // held.  However, this is very rare, and there is already so much
12952            // other disk I/O going on, that we'll let it slide for now.
12953            mInstaller.removeUserDataDirs(userHandle);
12954        }
12955        mUserNeedsBadging.delete(userHandle);
12956        removeUnusedPackagesLILPw(userManager, userHandle);
12957    }
12958
12959    /**
12960     * We're removing userHandle and would like to remove any downloaded packages
12961     * that are no longer in use by any other user.
12962     * @param userHandle the user being removed
12963     */
12964    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
12965        final boolean DEBUG_CLEAN_APKS = false;
12966        int [] users = userManager.getUserIdsLPr();
12967        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
12968        while (psit.hasNext()) {
12969            PackageSetting ps = psit.next();
12970            if (ps.pkg == null) {
12971                continue;
12972            }
12973            final String packageName = ps.pkg.packageName;
12974            // Skip over if system app
12975            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
12976                continue;
12977            }
12978            if (DEBUG_CLEAN_APKS) {
12979                Slog.i(TAG, "Checking package " + packageName);
12980            }
12981            boolean keep = false;
12982            for (int i = 0; i < users.length; i++) {
12983                if (users[i] != userHandle && ps.getInstalled(users[i])) {
12984                    keep = true;
12985                    if (DEBUG_CLEAN_APKS) {
12986                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
12987                                + users[i]);
12988                    }
12989                    break;
12990                }
12991            }
12992            if (!keep) {
12993                if (DEBUG_CLEAN_APKS) {
12994                    Slog.i(TAG, "  Removing package " + packageName);
12995                }
12996                mHandler.post(new Runnable() {
12997                    public void run() {
12998                        deletePackageX(packageName, userHandle, 0);
12999                    } //end run
13000                });
13001            }
13002        }
13003    }
13004
13005    /** Called by UserManagerService */
13006    void createNewUserLILPw(int userHandle, File path) {
13007        if (mInstaller != null) {
13008            mInstaller.createUserConfig(userHandle);
13009            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13010        }
13011    }
13012
13013    @Override
13014    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13015        mContext.enforceCallingOrSelfPermission(
13016                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13017                "Only package verification agents can read the verifier device identity");
13018
13019        synchronized (mPackages) {
13020            return mSettings.getVerifierDeviceIdentityLPw();
13021        }
13022    }
13023
13024    @Override
13025    public void setPermissionEnforced(String permission, boolean enforced) {
13026        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13027        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13028            synchronized (mPackages) {
13029                if (mSettings.mReadExternalStorageEnforced == null
13030                        || mSettings.mReadExternalStorageEnforced != enforced) {
13031                    mSettings.mReadExternalStorageEnforced = enforced;
13032                    mSettings.writeLPr();
13033                }
13034            }
13035            // kill any non-foreground processes so we restart them and
13036            // grant/revoke the GID.
13037            final IActivityManager am = ActivityManagerNative.getDefault();
13038            if (am != null) {
13039                final long token = Binder.clearCallingIdentity();
13040                try {
13041                    am.killProcessesBelowForeground("setPermissionEnforcement");
13042                } catch (RemoteException e) {
13043                } finally {
13044                    Binder.restoreCallingIdentity(token);
13045                }
13046            }
13047        } else {
13048            throw new IllegalArgumentException("No selective enforcement for " + permission);
13049        }
13050    }
13051
13052    @Override
13053    @Deprecated
13054    public boolean isPermissionEnforced(String permission) {
13055        return true;
13056    }
13057
13058    @Override
13059    public boolean isStorageLow() {
13060        final long token = Binder.clearCallingIdentity();
13061        try {
13062            final DeviceStorageMonitorInternal
13063                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13064            if (dsm != null) {
13065                return dsm.isMemoryLow();
13066            } else {
13067                return false;
13068            }
13069        } finally {
13070            Binder.restoreCallingIdentity(token);
13071        }
13072    }
13073
13074    @Override
13075    public IPackageInstaller getPackageInstaller() {
13076        return mInstallerService;
13077    }
13078
13079    private boolean userNeedsBadging(int userId) {
13080        int index = mUserNeedsBadging.indexOfKey(userId);
13081        if (index < 0) {
13082            final UserInfo userInfo;
13083            final long token = Binder.clearCallingIdentity();
13084            try {
13085                userInfo = sUserManager.getUserInfo(userId);
13086            } finally {
13087                Binder.restoreCallingIdentity(token);
13088            }
13089            final boolean b;
13090            if (userInfo != null && userInfo.isManagedProfile()) {
13091                b = true;
13092            } else {
13093                b = false;
13094            }
13095            mUserNeedsBadging.put(userId, b);
13096            return b;
13097        }
13098        return mUserNeedsBadging.valueAt(index);
13099    }
13100
13101    @Override
13102    public KeySet getKeySetByAlias(String packageName, String alias) {
13103        if (packageName == null || alias == null) {
13104            return null;
13105        }
13106        synchronized(mPackages) {
13107            final PackageParser.Package pkg = mPackages.get(packageName);
13108            if (pkg == null) {
13109                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13110                throw new IllegalArgumentException("Unknown package: " + packageName);
13111            }
13112            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13113            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13114        }
13115    }
13116
13117    @Override
13118    public KeySet getSigningKeySet(String packageName) {
13119        if (packageName == null) {
13120            return null;
13121        }
13122        synchronized(mPackages) {
13123            final PackageParser.Package pkg = mPackages.get(packageName);
13124            if (pkg == null) {
13125                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13126                throw new IllegalArgumentException("Unknown package: " + packageName);
13127            }
13128            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13129                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13130                throw new SecurityException("May not access signing KeySet of other apps.");
13131            }
13132            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13133            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13134        }
13135    }
13136
13137    @Override
13138    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13139        if (packageName == null || ks == null) {
13140            return false;
13141        }
13142        synchronized(mPackages) {
13143            final PackageParser.Package pkg = mPackages.get(packageName);
13144            if (pkg == null) {
13145                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13146                throw new IllegalArgumentException("Unknown package: " + packageName);
13147            }
13148            IBinder ksh = ks.getToken();
13149            if (ksh instanceof KeySetHandle) {
13150                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13151                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13152            }
13153            return false;
13154        }
13155    }
13156
13157    @Override
13158    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13159        if (packageName == null || ks == null) {
13160            return false;
13161        }
13162        synchronized(mPackages) {
13163            final PackageParser.Package pkg = mPackages.get(packageName);
13164            if (pkg == null) {
13165                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13166                throw new IllegalArgumentException("Unknown package: " + packageName);
13167            }
13168            IBinder ksh = ks.getToken();
13169            if (ksh instanceof KeySetHandle) {
13170                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13171                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13172            }
13173            return false;
13174        }
13175    }
13176}
13177