PackageManagerService.java revision 272bf3a274daff62995caf05da338c1f2a73dae3
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.AppGlobals;
84import android.app.IActivityManager;
85import android.app.admin.IDevicePolicyManager;
86import android.app.backup.IBackupManager;
87import android.content.BroadcastReceiver;
88import android.content.ComponentName;
89import android.content.Context;
90import android.content.IIntentReceiver;
91import android.content.Intent;
92import android.content.IntentFilter;
93import android.content.IntentSender;
94import android.content.IntentSender.SendIntentException;
95import android.content.ServiceConnection;
96import android.content.pm.ActivityInfo;
97import android.content.pm.ApplicationInfo;
98import android.content.pm.FeatureInfo;
99import android.content.pm.IPackageDataObserver;
100import android.content.pm.IPackageDeleteObserver;
101import android.content.pm.IPackageDeleteObserver2;
102import android.content.pm.IPackageInstallObserver2;
103import android.content.pm.IPackageInstaller;
104import android.content.pm.IPackageManager;
105import android.content.pm.IPackageMoveObserver;
106import android.content.pm.IPackageStatsObserver;
107import android.content.pm.InstrumentationInfo;
108import android.content.pm.KeySet;
109import android.content.pm.ManifestDigest;
110import android.content.pm.PackageCleanItem;
111import android.content.pm.PackageInfo;
112import android.content.pm.PackageInfoLite;
113import android.content.pm.PackageInstaller;
114import android.content.pm.PackageManager;
115import android.content.pm.PackageManager.LegacyPackageDeleteObserver;
116import android.content.pm.PackageParser.ActivityIntentInfo;
117import android.content.pm.PackageParser.PackageLite;
118import android.content.pm.PackageParser.PackageParserException;
119import android.content.pm.PackageParser;
120import android.content.pm.PackageStats;
121import android.content.pm.PackageUserState;
122import android.content.pm.ParceledListSlice;
123import android.content.pm.PermissionGroupInfo;
124import android.content.pm.PermissionInfo;
125import android.content.pm.ProviderInfo;
126import android.content.pm.ResolveInfo;
127import android.content.pm.ServiceInfo;
128import android.content.pm.Signature;
129import android.content.pm.UserInfo;
130import android.content.pm.VerificationParams;
131import android.content.pm.VerifierDeviceIdentity;
132import android.content.pm.VerifierInfo;
133import android.content.res.Resources;
134import android.hardware.display.DisplayManager;
135import android.net.Uri;
136import android.os.Binder;
137import android.os.Build;
138import android.os.Bundle;
139import android.os.Environment;
140import android.os.Environment.UserEnvironment;
141import android.os.storage.StorageManager;
142import android.os.Debug;
143import android.os.FileUtils;
144import android.os.Handler;
145import android.os.IBinder;
146import android.os.Looper;
147import android.os.Message;
148import android.os.Parcel;
149import android.os.ParcelFileDescriptor;
150import android.os.Process;
151import android.os.RemoteException;
152import android.os.SELinux;
153import android.os.ServiceManager;
154import android.os.SystemClock;
155import android.os.SystemProperties;
156import android.os.UserHandle;
157import android.os.UserManager;
158import android.security.KeyStore;
159import android.security.SystemKeyStore;
160import android.system.ErrnoException;
161import android.system.Os;
162import android.system.StructStat;
163import android.text.TextUtils;
164import android.util.ArraySet;
165import android.util.AtomicFile;
166import android.util.DisplayMetrics;
167import android.util.EventLog;
168import android.util.ExceptionUtils;
169import android.util.Log;
170import android.util.LogPrinter;
171import android.util.PrintStreamPrinter;
172import android.util.Slog;
173import android.util.SparseArray;
174import android.util.SparseBooleanArray;
175import android.view.Display;
176
177import java.io.BufferedInputStream;
178import java.io.BufferedOutputStream;
179import java.io.BufferedReader;
180import java.io.File;
181import java.io.FileDescriptor;
182import java.io.FileInputStream;
183import java.io.FileNotFoundException;
184import java.io.FileOutputStream;
185import java.io.FileReader;
186import java.io.FilenameFilter;
187import java.io.IOException;
188import java.io.InputStream;
189import java.io.PrintWriter;
190import java.nio.charset.StandardCharsets;
191import java.security.NoSuchAlgorithmException;
192import java.security.PublicKey;
193import java.security.cert.CertificateEncodingException;
194import java.security.cert.CertificateException;
195import java.text.SimpleDateFormat;
196import java.util.ArrayList;
197import java.util.Arrays;
198import java.util.Collection;
199import java.util.Collections;
200import java.util.Comparator;
201import java.util.Date;
202import java.util.HashMap;
203import java.util.HashSet;
204import java.util.Iterator;
205import java.util.List;
206import java.util.Map;
207import java.util.Objects;
208import java.util.Set;
209import java.util.concurrent.atomic.AtomicBoolean;
210import java.util.concurrent.atomic.AtomicLong;
211
212import dalvik.system.DexFile;
213import dalvik.system.StaleDexCacheError;
214import dalvik.system.VMRuntime;
215
216import libcore.io.IoUtils;
217import libcore.util.EmptyArray;
218
219/**
220 * Keep track of all those .apks everywhere.
221 *
222 * This is very central to the platform's security; please run the unit
223 * tests whenever making modifications here:
224 *
225mmm frameworks/base/tests/AndroidTests
226adb install -r -f out/target/product/passion/data/app/AndroidTests.apk
227adb shell am instrument -w -e class com.android.unit_tests.PackageManagerTests com.android.unit_tests/android.test.InstrumentationTestRunner
228 *
229 * {@hide}
230 */
231public class PackageManagerService extends IPackageManager.Stub {
232    static final String TAG = "PackageManager";
233    static final boolean DEBUG_SETTINGS = false;
234    static final boolean DEBUG_PREFERRED = false;
235    static final boolean DEBUG_UPGRADE = false;
236    private static final boolean DEBUG_INSTALL = false;
237    private static final boolean DEBUG_REMOVE = false;
238    private static final boolean DEBUG_BROADCASTS = false;
239    private static final boolean DEBUG_SHOW_INFO = false;
240    private static final boolean DEBUG_PACKAGE_INFO = false;
241    private static final boolean DEBUG_INTENT_MATCHING = false;
242    private static final boolean DEBUG_PACKAGE_SCANNING = false;
243    private static final boolean DEBUG_VERIFY = false;
244    private static final boolean DEBUG_DEXOPT = false;
245    private static final boolean DEBUG_ABI_SELECTION = false;
246
247    private static final int RADIO_UID = Process.PHONE_UID;
248    private static final int LOG_UID = Process.LOG_UID;
249    private static final int NFC_UID = Process.NFC_UID;
250    private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID;
251    private static final int SHELL_UID = Process.SHELL_UID;
252
253    // Cap the size of permission trees that 3rd party apps can define
254    private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768;     // characters of text
255
256    // Suffix used during package installation when copying/moving
257    // package apks to install directory.
258    private static final String INSTALL_PACKAGE_SUFFIX = "-";
259
260    static final int SCAN_NO_DEX = 1<<1;
261    static final int SCAN_FORCE_DEX = 1<<2;
262    static final int SCAN_UPDATE_SIGNATURE = 1<<3;
263    static final int SCAN_NEW_INSTALL = 1<<4;
264    static final int SCAN_NO_PATHS = 1<<5;
265    static final int SCAN_UPDATE_TIME = 1<<6;
266    static final int SCAN_DEFER_DEX = 1<<7;
267    static final int SCAN_BOOTING = 1<<8;
268    static final int SCAN_TRUSTED_OVERLAY = 1<<9;
269    static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10;
270    static final int SCAN_REPLACING = 1<<11;
271
272    static final int REMOVE_CHATTY = 1<<16;
273
274    /**
275     * Timeout (in milliseconds) after which the watchdog should declare that
276     * our handler thread is wedged.  The usual default for such things is one
277     * minute but we sometimes do very lengthy I/O operations on this thread,
278     * such as installing multi-gigabyte applications, so ours needs to be longer.
279     */
280    private static final long WATCHDOG_TIMEOUT = 1000*60*10;     // ten minutes
281
282    /**
283     * Whether verification is enabled by default.
284     */
285    private static final boolean DEFAULT_VERIFY_ENABLE = true;
286
287    /**
288     * The default maximum time to wait for the verification agent to return in
289     * milliseconds.
290     */
291    private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000;
292
293    /**
294     * The default response for package verification timeout.
295     *
296     * This can be either PackageManager.VERIFICATION_ALLOW or
297     * PackageManager.VERIFICATION_REJECT.
298     */
299    private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW;
300
301    static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer";
302
303    static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName(
304            DEFAULT_CONTAINER_PACKAGE,
305            "com.android.defcontainer.DefaultContainerService");
306
307    private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive";
308
309    private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay";
310
311    private static String sPreferredInstructionSet;
312
313    final ServiceThread mHandlerThread;
314
315    private static final String IDMAP_PREFIX = "/data/resource-cache/";
316    private static final String IDMAP_SUFFIX = "@idmap";
317
318    final PackageHandler mHandler;
319
320    /**
321     * Messages for {@link #mHandler} that need to wait for system ready before
322     * being dispatched.
323     */
324    private ArrayList<Message> mPostSystemReadyMessages;
325
326    final int mSdkVersion = Build.VERSION.SDK_INT;
327
328    final Context mContext;
329    final boolean mFactoryTest;
330    final boolean mOnlyCore;
331    final boolean mLazyDexOpt;
332    final DisplayMetrics mMetrics;
333    final int mDefParseFlags;
334    final String[] mSeparateProcesses;
335
336    // This is where all application persistent data goes.
337    final File mAppDataDir;
338
339    // This is where all application persistent data goes for secondary users.
340    final File mUserAppDataDir;
341
342    /** The location for ASEC container files on internal storage. */
343    final String mAsecInternalPath;
344
345    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
346    // LOCK HELD.  Can be called with mInstallLock held.
347    final Installer mInstaller;
348
349    /** Directory where installed third-party apps stored */
350    final File mAppInstallDir;
351
352    /**
353     * Directory to which applications installed internally have their
354     * 32 bit native libraries copied.
355     */
356    private File mAppLib32InstallDir;
357
358    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
359    // apps.
360    final File mDrmAppPrivateInstallDir;
361
362    // ----------------------------------------------------------------
363
364    // Lock for state used when installing and doing other long running
365    // operations.  Methods that must be called with this lock held have
366    // the suffix "LI".
367    final Object mInstallLock = new Object();
368
369    // ----------------------------------------------------------------
370
371    // Keys are String (package name), values are Package.  This also serves
372    // as the lock for the global state.  Methods that must be called with
373    // this lock held have the prefix "LP".
374    final HashMap<String, PackageParser.Package> mPackages =
375            new HashMap<String, PackageParser.Package>();
376
377    // Tracks available target package names -> overlay package paths.
378    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
379        new HashMap<String, HashMap<String, PackageParser.Package>>();
380
381    final Settings mSettings;
382    boolean mRestoredSettings;
383
384    // System configuration read by SystemConfig.
385    final int[] mGlobalGids;
386    final SparseArray<HashSet<String>> mSystemPermissions;
387    final HashMap<String, FeatureInfo> mAvailableFeatures;
388
389    // If mac_permissions.xml was found for seinfo labeling.
390    boolean mFoundPolicyFile;
391
392    // If a recursive restorecon of /data/data/<pkg> is needed.
393    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
394
395    public static final class SharedLibraryEntry {
396        public final String path;
397        public final String apk;
398
399        SharedLibraryEntry(String _path, String _apk) {
400            path = _path;
401            apk = _apk;
402        }
403    }
404
405    // Currently known shared libraries.
406    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
407            new HashMap<String, SharedLibraryEntry>();
408
409    // All available activities, for your resolving pleasure.
410    final ActivityIntentResolver mActivities =
411            new ActivityIntentResolver();
412
413    // All available receivers, for your resolving pleasure.
414    final ActivityIntentResolver mReceivers =
415            new ActivityIntentResolver();
416
417    // All available services, for your resolving pleasure.
418    final ServiceIntentResolver mServices = new ServiceIntentResolver();
419
420    // All available providers, for your resolving pleasure.
421    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
422
423    // Mapping from provider base names (first directory in content URI codePath)
424    // to the provider information.
425    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
426            new HashMap<String, PackageParser.Provider>();
427
428    // Mapping from instrumentation class names to info about them.
429    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
430            new HashMap<ComponentName, PackageParser.Instrumentation>();
431
432    // Mapping from permission names to info about them.
433    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
434            new HashMap<String, PackageParser.PermissionGroup>();
435
436    // Packages whose data we have transfered into another package, thus
437    // should no longer exist.
438    final HashSet<String> mTransferedPackages = new HashSet<String>();
439
440    // Broadcast actions that are only available to the system.
441    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
442
443    /** List of packages waiting for verification. */
444    final SparseArray<PackageVerificationState> mPendingVerification
445            = new SparseArray<PackageVerificationState>();
446
447    /** Set of packages associated with each app op permission. */
448    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
449
450    final PackageInstallerService mInstallerService;
451
452    HashSet<PackageParser.Package> mDeferredDexOpt = null;
453
454    // Cache of users who need badging.
455    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
456
457    /** Token for keys in mPendingVerification. */
458    private int mPendingVerificationToken = 0;
459
460    volatile boolean mSystemReady;
461    volatile boolean mSafeMode;
462    volatile boolean mHasSystemUidErrors;
463
464    ApplicationInfo mAndroidApplication;
465    final ActivityInfo mResolveActivity = new ActivityInfo();
466    final ResolveInfo mResolveInfo = new ResolveInfo();
467    ComponentName mResolveComponentName;
468    PackageParser.Package mPlatformPackage;
469    ComponentName mCustomResolverComponentName;
470
471    boolean mResolverReplaced = false;
472
473    // Set of pending broadcasts for aggregating enable/disable of components.
474    static class PendingPackageBroadcasts {
475        // for each user id, a map of <package name -> components within that package>
476        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
477
478        public PendingPackageBroadcasts() {
479            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
480        }
481
482        public ArrayList<String> get(int userId, String packageName) {
483            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
484            return packages.get(packageName);
485        }
486
487        public void put(int userId, String packageName, ArrayList<String> components) {
488            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
489            packages.put(packageName, components);
490        }
491
492        public void remove(int userId, String packageName) {
493            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
494            if (packages != null) {
495                packages.remove(packageName);
496            }
497        }
498
499        public void remove(int userId) {
500            mUidMap.remove(userId);
501        }
502
503        public int userIdCount() {
504            return mUidMap.size();
505        }
506
507        public int userIdAt(int n) {
508            return mUidMap.keyAt(n);
509        }
510
511        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
512            return mUidMap.get(userId);
513        }
514
515        public int size() {
516            // total number of pending broadcast entries across all userIds
517            int num = 0;
518            for (int i = 0; i< mUidMap.size(); i++) {
519                num += mUidMap.valueAt(i).size();
520            }
521            return num;
522        }
523
524        public void clear() {
525            mUidMap.clear();
526        }
527
528        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
529            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
530            if (map == null) {
531                map = new HashMap<String, ArrayList<String>>();
532                mUidMap.put(userId, map);
533            }
534            return map;
535        }
536    }
537    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
538
539    // Service Connection to remote media container service to copy
540    // package uri's from external media onto secure containers
541    // or internal storage.
542    private IMediaContainerService mContainerService = null;
543
544    static final int SEND_PENDING_BROADCAST = 1;
545    static final int MCS_BOUND = 3;
546    static final int END_COPY = 4;
547    static final int INIT_COPY = 5;
548    static final int MCS_UNBIND = 6;
549    static final int START_CLEANING_PACKAGE = 7;
550    static final int FIND_INSTALL_LOC = 8;
551    static final int POST_INSTALL = 9;
552    static final int MCS_RECONNECT = 10;
553    static final int MCS_GIVE_UP = 11;
554    static final int UPDATED_MEDIA_STATUS = 12;
555    static final int WRITE_SETTINGS = 13;
556    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
557    static final int PACKAGE_VERIFIED = 15;
558    static final int CHECK_PENDING_VERIFICATION = 16;
559
560    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
561
562    // Delay time in millisecs
563    static final int BROADCAST_DELAY = 10 * 1000;
564
565    static UserManagerService sUserManager;
566
567    // Stores a list of users whose package restrictions file needs to be updated
568    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
569
570    final private DefaultContainerConnection mDefContainerConn =
571            new DefaultContainerConnection();
572    class DefaultContainerConnection implements ServiceConnection {
573        public void onServiceConnected(ComponentName name, IBinder service) {
574            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
575            IMediaContainerService imcs =
576                IMediaContainerService.Stub.asInterface(service);
577            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
578        }
579
580        public void onServiceDisconnected(ComponentName name) {
581            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
582        }
583    };
584
585    // Recordkeeping of restore-after-install operations that are currently in flight
586    // between the Package Manager and the Backup Manager
587    class PostInstallData {
588        public InstallArgs args;
589        public PackageInstalledInfo res;
590
591        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
592            args = _a;
593            res = _r;
594        }
595    };
596    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
597    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
598
599    private final String mRequiredVerifierPackage;
600
601    private final PackageUsage mPackageUsage = new PackageUsage();
602
603    private class PackageUsage {
604        private static final int WRITE_INTERVAL
605            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
606
607        private final Object mFileLock = new Object();
608        private final AtomicLong mLastWritten = new AtomicLong(0);
609        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
610
611        private boolean mIsHistoricalPackageUsageAvailable = true;
612
613        boolean isHistoricalPackageUsageAvailable() {
614            return mIsHistoricalPackageUsageAvailable;
615        }
616
617        void write(boolean force) {
618            if (force) {
619                writeInternal();
620                return;
621            }
622            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
623                && !DEBUG_DEXOPT) {
624                return;
625            }
626            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
627                new Thread("PackageUsage_DiskWriter") {
628                    @Override
629                    public void run() {
630                        try {
631                            writeInternal();
632                        } finally {
633                            mBackgroundWriteRunning.set(false);
634                        }
635                    }
636                }.start();
637            }
638        }
639
640        private void writeInternal() {
641            synchronized (mPackages) {
642                synchronized (mFileLock) {
643                    AtomicFile file = getFile();
644                    FileOutputStream f = null;
645                    try {
646                        f = file.startWrite();
647                        BufferedOutputStream out = new BufferedOutputStream(f);
648                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
649                        StringBuilder sb = new StringBuilder();
650                        for (PackageParser.Package pkg : mPackages.values()) {
651                            if (pkg.mLastPackageUsageTimeInMills == 0) {
652                                continue;
653                            }
654                            sb.setLength(0);
655                            sb.append(pkg.packageName);
656                            sb.append(' ');
657                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
658                            sb.append('\n');
659                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
660                        }
661                        out.flush();
662                        file.finishWrite(f);
663                    } catch (IOException e) {
664                        if (f != null) {
665                            file.failWrite(f);
666                        }
667                        Log.e(TAG, "Failed to write package usage times", e);
668                    }
669                }
670            }
671            mLastWritten.set(SystemClock.elapsedRealtime());
672        }
673
674        void readLP() {
675            synchronized (mFileLock) {
676                AtomicFile file = getFile();
677                BufferedInputStream in = null;
678                try {
679                    in = new BufferedInputStream(file.openRead());
680                    StringBuffer sb = new StringBuffer();
681                    while (true) {
682                        String packageName = readToken(in, sb, ' ');
683                        if (packageName == null) {
684                            break;
685                        }
686                        String timeInMillisString = readToken(in, sb, '\n');
687                        if (timeInMillisString == null) {
688                            throw new IOException("Failed to find last usage time for package "
689                                                  + packageName);
690                        }
691                        PackageParser.Package pkg = mPackages.get(packageName);
692                        if (pkg == null) {
693                            continue;
694                        }
695                        long timeInMillis;
696                        try {
697                            timeInMillis = Long.parseLong(timeInMillisString.toString());
698                        } catch (NumberFormatException e) {
699                            throw new IOException("Failed to parse " + timeInMillisString
700                                                  + " as a long.", e);
701                        }
702                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
703                    }
704                } catch (FileNotFoundException expected) {
705                    mIsHistoricalPackageUsageAvailable = false;
706                } catch (IOException e) {
707                    Log.w(TAG, "Failed to read package usage times", e);
708                } finally {
709                    IoUtils.closeQuietly(in);
710                }
711            }
712            mLastWritten.set(SystemClock.elapsedRealtime());
713        }
714
715        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
716                throws IOException {
717            sb.setLength(0);
718            while (true) {
719                int ch = in.read();
720                if (ch == -1) {
721                    if (sb.length() == 0) {
722                        return null;
723                    }
724                    throw new IOException("Unexpected EOF");
725                }
726                if (ch == endOfToken) {
727                    return sb.toString();
728                }
729                sb.append((char)ch);
730            }
731        }
732
733        private AtomicFile getFile() {
734            File dataDir = Environment.getDataDirectory();
735            File systemDir = new File(dataDir, "system");
736            File fname = new File(systemDir, "package-usage.list");
737            return new AtomicFile(fname);
738        }
739    }
740
741    class PackageHandler extends Handler {
742        private boolean mBound = false;
743        final ArrayList<HandlerParams> mPendingInstalls =
744            new ArrayList<HandlerParams>();
745
746        private boolean connectToService() {
747            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
748                    " DefaultContainerService");
749            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
750            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
751            if (mContext.bindServiceAsUser(service, mDefContainerConn,
752                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
753                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
754                mBound = true;
755                return true;
756            }
757            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
758            return false;
759        }
760
761        private void disconnectService() {
762            mContainerService = null;
763            mBound = false;
764            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
765            mContext.unbindService(mDefContainerConn);
766            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
767        }
768
769        PackageHandler(Looper looper) {
770            super(looper);
771        }
772
773        public void handleMessage(Message msg) {
774            try {
775                doHandleMessage(msg);
776            } finally {
777                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
778            }
779        }
780
781        void doHandleMessage(Message msg) {
782            switch (msg.what) {
783                case INIT_COPY: {
784                    HandlerParams params = (HandlerParams) msg.obj;
785                    int idx = mPendingInstalls.size();
786                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
787                    // If a bind was already initiated we dont really
788                    // need to do anything. The pending install
789                    // will be processed later on.
790                    if (!mBound) {
791                        // If this is the only one pending we might
792                        // have to bind to the service again.
793                        if (!connectToService()) {
794                            Slog.e(TAG, "Failed to bind to media container service");
795                            params.serviceError();
796                            return;
797                        } else {
798                            // Once we bind to the service, the first
799                            // pending request will be processed.
800                            mPendingInstalls.add(idx, params);
801                        }
802                    } else {
803                        mPendingInstalls.add(idx, params);
804                        // Already bound to the service. Just make
805                        // sure we trigger off processing the first request.
806                        if (idx == 0) {
807                            mHandler.sendEmptyMessage(MCS_BOUND);
808                        }
809                    }
810                    break;
811                }
812                case MCS_BOUND: {
813                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
814                    if (msg.obj != null) {
815                        mContainerService = (IMediaContainerService) msg.obj;
816                    }
817                    if (mContainerService == null) {
818                        // Something seriously wrong. Bail out
819                        Slog.e(TAG, "Cannot bind to media container service");
820                        for (HandlerParams params : mPendingInstalls) {
821                            // Indicate service bind error
822                            params.serviceError();
823                        }
824                        mPendingInstalls.clear();
825                    } else if (mPendingInstalls.size() > 0) {
826                        HandlerParams params = mPendingInstalls.get(0);
827                        if (params != null) {
828                            if (params.startCopy()) {
829                                // We are done...  look for more work or to
830                                // go idle.
831                                if (DEBUG_SD_INSTALL) Log.i(TAG,
832                                        "Checking for more work or unbind...");
833                                // Delete pending install
834                                if (mPendingInstalls.size() > 0) {
835                                    mPendingInstalls.remove(0);
836                                }
837                                if (mPendingInstalls.size() == 0) {
838                                    if (mBound) {
839                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
840                                                "Posting delayed MCS_UNBIND");
841                                        removeMessages(MCS_UNBIND);
842                                        Message ubmsg = obtainMessage(MCS_UNBIND);
843                                        // Unbind after a little delay, to avoid
844                                        // continual thrashing.
845                                        sendMessageDelayed(ubmsg, 10000);
846                                    }
847                                } else {
848                                    // There are more pending requests in queue.
849                                    // Just post MCS_BOUND message to trigger processing
850                                    // of next pending install.
851                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
852                                            "Posting MCS_BOUND for next work");
853                                    mHandler.sendEmptyMessage(MCS_BOUND);
854                                }
855                            }
856                        }
857                    } else {
858                        // Should never happen ideally.
859                        Slog.w(TAG, "Empty queue");
860                    }
861                    break;
862                }
863                case MCS_RECONNECT: {
864                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
865                    if (mPendingInstalls.size() > 0) {
866                        if (mBound) {
867                            disconnectService();
868                        }
869                        if (!connectToService()) {
870                            Slog.e(TAG, "Failed to bind to media container service");
871                            for (HandlerParams params : mPendingInstalls) {
872                                // Indicate service bind error
873                                params.serviceError();
874                            }
875                            mPendingInstalls.clear();
876                        }
877                    }
878                    break;
879                }
880                case MCS_UNBIND: {
881                    // If there is no actual work left, then time to unbind.
882                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
883
884                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
885                        if (mBound) {
886                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
887
888                            disconnectService();
889                        }
890                    } else if (mPendingInstalls.size() > 0) {
891                        // There are more pending requests in queue.
892                        // Just post MCS_BOUND message to trigger processing
893                        // of next pending install.
894                        mHandler.sendEmptyMessage(MCS_BOUND);
895                    }
896
897                    break;
898                }
899                case MCS_GIVE_UP: {
900                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
901                    mPendingInstalls.remove(0);
902                    break;
903                }
904                case SEND_PENDING_BROADCAST: {
905                    String packages[];
906                    ArrayList<String> components[];
907                    int size = 0;
908                    int uids[];
909                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
910                    synchronized (mPackages) {
911                        if (mPendingBroadcasts == null) {
912                            return;
913                        }
914                        size = mPendingBroadcasts.size();
915                        if (size <= 0) {
916                            // Nothing to be done. Just return
917                            return;
918                        }
919                        packages = new String[size];
920                        components = new ArrayList[size];
921                        uids = new int[size];
922                        int i = 0;  // filling out the above arrays
923
924                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
925                            int packageUserId = mPendingBroadcasts.userIdAt(n);
926                            Iterator<Map.Entry<String, ArrayList<String>>> it
927                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
928                                            .entrySet().iterator();
929                            while (it.hasNext() && i < size) {
930                                Map.Entry<String, ArrayList<String>> ent = it.next();
931                                packages[i] = ent.getKey();
932                                components[i] = ent.getValue();
933                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
934                                uids[i] = (ps != null)
935                                        ? UserHandle.getUid(packageUserId, ps.appId)
936                                        : -1;
937                                i++;
938                            }
939                        }
940                        size = i;
941                        mPendingBroadcasts.clear();
942                    }
943                    // Send broadcasts
944                    for (int i = 0; i < size; i++) {
945                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
946                    }
947                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
948                    break;
949                }
950                case START_CLEANING_PACKAGE: {
951                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
952                    final String packageName = (String)msg.obj;
953                    final int userId = msg.arg1;
954                    final boolean andCode = msg.arg2 != 0;
955                    synchronized (mPackages) {
956                        if (userId == UserHandle.USER_ALL) {
957                            int[] users = sUserManager.getUserIds();
958                            for (int user : users) {
959                                mSettings.addPackageToCleanLPw(
960                                        new PackageCleanItem(user, packageName, andCode));
961                            }
962                        } else {
963                            mSettings.addPackageToCleanLPw(
964                                    new PackageCleanItem(userId, packageName, andCode));
965                        }
966                    }
967                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
968                    startCleaningPackages();
969                } break;
970                case POST_INSTALL: {
971                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
972                    PostInstallData data = mRunningInstalls.get(msg.arg1);
973                    mRunningInstalls.delete(msg.arg1);
974                    boolean deleteOld = false;
975
976                    if (data != null) {
977                        InstallArgs args = data.args;
978                        PackageInstalledInfo res = data.res;
979
980                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
981                            res.removedInfo.sendBroadcast(false, true, false);
982                            Bundle extras = new Bundle(1);
983                            extras.putInt(Intent.EXTRA_UID, res.uid);
984                            // Determine the set of users who are adding this
985                            // package for the first time vs. those who are seeing
986                            // an update.
987                            int[] firstUsers;
988                            int[] updateUsers = new int[0];
989                            if (res.origUsers == null || res.origUsers.length == 0) {
990                                firstUsers = res.newUsers;
991                            } else {
992                                firstUsers = new int[0];
993                                for (int i=0; i<res.newUsers.length; i++) {
994                                    int user = res.newUsers[i];
995                                    boolean isNew = true;
996                                    for (int j=0; j<res.origUsers.length; j++) {
997                                        if (res.origUsers[j] == user) {
998                                            isNew = false;
999                                            break;
1000                                        }
1001                                    }
1002                                    if (isNew) {
1003                                        int[] newFirst = new int[firstUsers.length+1];
1004                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1005                                                firstUsers.length);
1006                                        newFirst[firstUsers.length] = user;
1007                                        firstUsers = newFirst;
1008                                    } else {
1009                                        int[] newUpdate = new int[updateUsers.length+1];
1010                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1011                                                updateUsers.length);
1012                                        newUpdate[updateUsers.length] = user;
1013                                        updateUsers = newUpdate;
1014                                    }
1015                                }
1016                            }
1017                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1018                                    res.pkg.applicationInfo.packageName,
1019                                    extras, null, null, firstUsers);
1020                            final boolean update = res.removedInfo.removedPackage != null;
1021                            if (update) {
1022                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1023                            }
1024                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1025                                    res.pkg.applicationInfo.packageName,
1026                                    extras, null, null, updateUsers);
1027                            if (update) {
1028                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1029                                        res.pkg.applicationInfo.packageName,
1030                                        extras, null, null, updateUsers);
1031                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1032                                        null, null,
1033                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1034
1035                                // treat asec-hosted packages like removable media on upgrade
1036                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1037                                    if (DEBUG_INSTALL) {
1038                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1039                                                + " is ASEC-hosted -> AVAILABLE");
1040                                    }
1041                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1042                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1043                                    pkgList.add(res.pkg.applicationInfo.packageName);
1044                                    sendResourcesChangedBroadcast(true, true,
1045                                            pkgList,uidArray, null);
1046                                }
1047                            }
1048                            if (res.removedInfo.args != null) {
1049                                // Remove the replaced package's older resources safely now
1050                                deleteOld = true;
1051                            }
1052
1053                            // Log current value of "unknown sources" setting
1054                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1055                                getUnknownSourcesSettings());
1056                        }
1057                        // Force a gc to clear up things
1058                        Runtime.getRuntime().gc();
1059                        // We delete after a gc for applications  on sdcard.
1060                        if (deleteOld) {
1061                            synchronized (mInstallLock) {
1062                                res.removedInfo.args.doPostDeleteLI(true);
1063                            }
1064                        }
1065                        if (args.observer != null) {
1066                            try {
1067                                Bundle extras = extrasForInstallResult(res);
1068                                args.observer.onPackageInstalled(res.name, res.returnCode,
1069                                        res.returnMsg, extras);
1070                            } catch (RemoteException e) {
1071                                Slog.i(TAG, "Observer no longer exists.");
1072                            }
1073                        }
1074                    } else {
1075                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1076                    }
1077                } break;
1078                case UPDATED_MEDIA_STATUS: {
1079                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1080                    boolean reportStatus = msg.arg1 == 1;
1081                    boolean doGc = msg.arg2 == 1;
1082                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1083                    if (doGc) {
1084                        // Force a gc to clear up stale containers.
1085                        Runtime.getRuntime().gc();
1086                    }
1087                    if (msg.obj != null) {
1088                        @SuppressWarnings("unchecked")
1089                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1090                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1091                        // Unload containers
1092                        unloadAllContainers(args);
1093                    }
1094                    if (reportStatus) {
1095                        try {
1096                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1097                            PackageHelper.getMountService().finishMediaUpdate();
1098                        } catch (RemoteException e) {
1099                            Log.e(TAG, "MountService not running?");
1100                        }
1101                    }
1102                } break;
1103                case WRITE_SETTINGS: {
1104                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1105                    synchronized (mPackages) {
1106                        removeMessages(WRITE_SETTINGS);
1107                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1108                        mSettings.writeLPr();
1109                        mDirtyUsers.clear();
1110                    }
1111                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1112                } break;
1113                case WRITE_PACKAGE_RESTRICTIONS: {
1114                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1115                    synchronized (mPackages) {
1116                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1117                        for (int userId : mDirtyUsers) {
1118                            mSettings.writePackageRestrictionsLPr(userId);
1119                        }
1120                        mDirtyUsers.clear();
1121                    }
1122                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1123                } break;
1124                case CHECK_PENDING_VERIFICATION: {
1125                    final int verificationId = msg.arg1;
1126                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1127
1128                    if ((state != null) && !state.timeoutExtended()) {
1129                        final InstallArgs args = state.getInstallArgs();
1130                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1131
1132                        Slog.i(TAG, "Verification timed out for " + originUri);
1133                        mPendingVerification.remove(verificationId);
1134
1135                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1136
1137                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1138                            Slog.i(TAG, "Continuing with installation of " + originUri);
1139                            state.setVerifierResponse(Binder.getCallingUid(),
1140                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1141                            broadcastPackageVerified(verificationId, originUri,
1142                                    PackageManager.VERIFICATION_ALLOW,
1143                                    state.getInstallArgs().getUser());
1144                            try {
1145                                ret = args.copyApk(mContainerService, true);
1146                            } catch (RemoteException e) {
1147                                Slog.e(TAG, "Could not contact the ContainerService");
1148                            }
1149                        } else {
1150                            broadcastPackageVerified(verificationId, originUri,
1151                                    PackageManager.VERIFICATION_REJECT,
1152                                    state.getInstallArgs().getUser());
1153                        }
1154
1155                        processPendingInstall(args, ret);
1156                        mHandler.sendEmptyMessage(MCS_UNBIND);
1157                    }
1158                    break;
1159                }
1160                case PACKAGE_VERIFIED: {
1161                    final int verificationId = msg.arg1;
1162
1163                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1164                    if (state == null) {
1165                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1166                        break;
1167                    }
1168
1169                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1170
1171                    state.setVerifierResponse(response.callerUid, response.code);
1172
1173                    if (state.isVerificationComplete()) {
1174                        mPendingVerification.remove(verificationId);
1175
1176                        final InstallArgs args = state.getInstallArgs();
1177                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1178
1179                        int ret;
1180                        if (state.isInstallAllowed()) {
1181                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1182                            broadcastPackageVerified(verificationId, originUri,
1183                                    response.code, state.getInstallArgs().getUser());
1184                            try {
1185                                ret = args.copyApk(mContainerService, true);
1186                            } catch (RemoteException e) {
1187                                Slog.e(TAG, "Could not contact the ContainerService");
1188                            }
1189                        } else {
1190                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1191                        }
1192
1193                        processPendingInstall(args, ret);
1194
1195                        mHandler.sendEmptyMessage(MCS_UNBIND);
1196                    }
1197
1198                    break;
1199                }
1200            }
1201        }
1202    }
1203
1204    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1205        Bundle extras = null;
1206        switch (res.returnCode) {
1207            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1208                extras = new Bundle();
1209                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1210                        res.origPermission);
1211                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1212                        res.origPackage);
1213                break;
1214            }
1215        }
1216        return extras;
1217    }
1218
1219    void scheduleWriteSettingsLocked() {
1220        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1221            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1222        }
1223    }
1224
1225    void scheduleWritePackageRestrictionsLocked(int userId) {
1226        if (!sUserManager.exists(userId)) return;
1227        mDirtyUsers.add(userId);
1228        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1229            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1230        }
1231    }
1232
1233    public static final PackageManagerService main(Context context, Installer installer,
1234            boolean factoryTest, boolean onlyCore) {
1235        PackageManagerService m = new PackageManagerService(context, installer,
1236                factoryTest, onlyCore);
1237        ServiceManager.addService("package", m);
1238        return m;
1239    }
1240
1241    static String[] splitString(String str, char sep) {
1242        int count = 1;
1243        int i = 0;
1244        while ((i=str.indexOf(sep, i)) >= 0) {
1245            count++;
1246            i++;
1247        }
1248
1249        String[] res = new String[count];
1250        i=0;
1251        count = 0;
1252        int lastI=0;
1253        while ((i=str.indexOf(sep, i)) >= 0) {
1254            res[count] = str.substring(lastI, i);
1255            count++;
1256            i++;
1257            lastI = i;
1258        }
1259        res[count] = str.substring(lastI, str.length());
1260        return res;
1261    }
1262
1263    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1264        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1265                Context.DISPLAY_SERVICE);
1266        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1267    }
1268
1269    public PackageManagerService(Context context, Installer installer,
1270            boolean factoryTest, boolean onlyCore) {
1271        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1272                SystemClock.uptimeMillis());
1273
1274        if (mSdkVersion <= 0) {
1275            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1276        }
1277
1278        mContext = context;
1279        mFactoryTest = factoryTest;
1280        mOnlyCore = onlyCore;
1281        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1282        mMetrics = new DisplayMetrics();
1283        mSettings = new Settings(context);
1284        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1285                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1286        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1287                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1288        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1289                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1290        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1291                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1292        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1293                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1294        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1295                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1296
1297        String separateProcesses = SystemProperties.get("debug.separate_processes");
1298        if (separateProcesses != null && separateProcesses.length() > 0) {
1299            if ("*".equals(separateProcesses)) {
1300                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1301                mSeparateProcesses = null;
1302                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1303            } else {
1304                mDefParseFlags = 0;
1305                mSeparateProcesses = separateProcesses.split(",");
1306                Slog.w(TAG, "Running with debug.separate_processes: "
1307                        + separateProcesses);
1308            }
1309        } else {
1310            mDefParseFlags = 0;
1311            mSeparateProcesses = null;
1312        }
1313
1314        mInstaller = installer;
1315
1316        getDefaultDisplayMetrics(context, mMetrics);
1317
1318        SystemConfig systemConfig = SystemConfig.getInstance();
1319        mGlobalGids = systemConfig.getGlobalGids();
1320        mSystemPermissions = systemConfig.getSystemPermissions();
1321        mAvailableFeatures = systemConfig.getAvailableFeatures();
1322
1323        synchronized (mInstallLock) {
1324        // writer
1325        synchronized (mPackages) {
1326            mHandlerThread = new ServiceThread(TAG,
1327                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1328            mHandlerThread.start();
1329            mHandler = new PackageHandler(mHandlerThread.getLooper());
1330            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1331
1332            File dataDir = Environment.getDataDirectory();
1333            mAppDataDir = new File(dataDir, "data");
1334            mAppInstallDir = new File(dataDir, "app");
1335            mAppLib32InstallDir = new File(dataDir, "app-lib");
1336            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1337            mUserAppDataDir = new File(dataDir, "user");
1338            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1339
1340            sUserManager = new UserManagerService(context, this,
1341                    mInstallLock, mPackages);
1342
1343            // Propagate permission configuration in to package manager.
1344            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1345                    = systemConfig.getPermissions();
1346            for (int i=0; i<permConfig.size(); i++) {
1347                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1348                BasePermission bp = mSettings.mPermissions.get(perm.name);
1349                if (bp == null) {
1350                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1351                    mSettings.mPermissions.put(perm.name, bp);
1352                }
1353                if (perm.gids != null) {
1354                    bp.gids = appendInts(bp.gids, perm.gids);
1355                }
1356            }
1357
1358            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1359            for (int i=0; i<libConfig.size(); i++) {
1360                mSharedLibraries.put(libConfig.keyAt(i),
1361                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1362            }
1363
1364            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1365
1366            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1367                    mSdkVersion, mOnlyCore);
1368
1369            String customResolverActivity = Resources.getSystem().getString(
1370                    R.string.config_customResolverActivity);
1371            if (TextUtils.isEmpty(customResolverActivity)) {
1372                customResolverActivity = null;
1373            } else {
1374                mCustomResolverComponentName = ComponentName.unflattenFromString(
1375                        customResolverActivity);
1376            }
1377
1378            long startTime = SystemClock.uptimeMillis();
1379
1380            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1381                    startTime);
1382
1383            // Set flag to monitor and not change apk file paths when
1384            // scanning install directories.
1385            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1386
1387            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1388
1389            /**
1390             * Add everything in the in the boot class path to the
1391             * list of process files because dexopt will have been run
1392             * if necessary during zygote startup.
1393             */
1394            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1395            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1396
1397            if (bootClassPath != null) {
1398                String[] bootClassPathElements = splitString(bootClassPath, ':');
1399                for (String element : bootClassPathElements) {
1400                    alreadyDexOpted.add(element);
1401                }
1402            } else {
1403                Slog.w(TAG, "No BOOTCLASSPATH found!");
1404            }
1405
1406            if (systemServerClassPath != null) {
1407                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1408                for (String element : systemServerClassPathElements) {
1409                    alreadyDexOpted.add(element);
1410                }
1411            } else {
1412                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1413            }
1414
1415            boolean didDexOptLibraryOrTool = false;
1416
1417            final List<String> allInstructionSets = getAllInstructionSets();
1418            final String[] dexCodeInstructionSets =
1419                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1420
1421            /**
1422             * Ensure all external libraries have had dexopt run on them.
1423             */
1424            if (mSharedLibraries.size() > 0) {
1425                // NOTE: For now, we're compiling these system "shared libraries"
1426                // (and framework jars) into all available architectures. It's possible
1427                // to compile them only when we come across an app that uses them (there's
1428                // already logic for that in scanPackageLI) but that adds some complexity.
1429                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1430                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1431                        final String lib = libEntry.path;
1432                        if (lib == null) {
1433                            continue;
1434                        }
1435
1436                        try {
1437                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1438                                                                                 dexCodeInstructionSet,
1439                                                                                 false);
1440                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1441                                alreadyDexOpted.add(lib);
1442
1443                                // The list of "shared libraries" we have at this point is
1444                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1445                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1446                                } else {
1447                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1448                                }
1449                                didDexOptLibraryOrTool = true;
1450                            }
1451                        } catch (FileNotFoundException e) {
1452                            Slog.w(TAG, "Library not found: " + lib);
1453                        } catch (IOException e) {
1454                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1455                                    + e.getMessage());
1456                        }
1457                    }
1458                }
1459            }
1460
1461            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1462
1463            // Gross hack for now: we know this file doesn't contain any
1464            // code, so don't dexopt it to avoid the resulting log spew.
1465            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1466
1467            // Gross hack for now: we know this file is only part of
1468            // the boot class path for art, so don't dexopt it to
1469            // avoid the resulting log spew.
1470            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1471
1472            /**
1473             * And there are a number of commands implemented in Java, which
1474             * we currently need to do the dexopt on so that they can be
1475             * run from a non-root shell.
1476             */
1477            String[] frameworkFiles = frameworkDir.list();
1478            if (frameworkFiles != null) {
1479                // TODO: We could compile these only for the most preferred ABI. We should
1480                // first double check that the dex files for these commands are not referenced
1481                // by other system apps.
1482                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1483                    for (int i=0; i<frameworkFiles.length; i++) {
1484                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1485                        String path = libPath.getPath();
1486                        // Skip the file if we already did it.
1487                        if (alreadyDexOpted.contains(path)) {
1488                            continue;
1489                        }
1490                        // Skip the file if it is not a type we want to dexopt.
1491                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1492                            continue;
1493                        }
1494                        try {
1495                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1496                                                                                 dexCodeInstructionSet,
1497                                                                                 false);
1498                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1499                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1500                                didDexOptLibraryOrTool = true;
1501                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1502                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1503                                didDexOptLibraryOrTool = true;
1504                            }
1505                        } catch (FileNotFoundException e) {
1506                            Slog.w(TAG, "Jar not found: " + path);
1507                        } catch (IOException e) {
1508                            Slog.w(TAG, "Exception reading jar: " + path, e);
1509                        }
1510                    }
1511                }
1512            }
1513
1514            // Collect vendor overlay packages.
1515            // (Do this before scanning any apps.)
1516            // For security and version matching reason, only consider
1517            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1518            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1519            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1520                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1521
1522            // Find base frameworks (resource packages without code).
1523            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1524                    | PackageParser.PARSE_IS_SYSTEM_DIR
1525                    | PackageParser.PARSE_IS_PRIVILEGED,
1526                    scanFlags | SCAN_NO_DEX, 0);
1527
1528            // Collected privileged system packages.
1529            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1530            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1531                    | PackageParser.PARSE_IS_SYSTEM_DIR
1532                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1533
1534            // Collect ordinary system packages.
1535            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1536            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1537                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1538
1539            // Collect all vendor packages.
1540            File vendorAppDir = new File("/vendor/app");
1541            try {
1542                vendorAppDir = vendorAppDir.getCanonicalFile();
1543            } catch (IOException e) {
1544                // failed to look up canonical path, continue with original one
1545            }
1546            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1547                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1548
1549            // Collect all OEM packages.
1550            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1551            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1552                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1553
1554            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1555            mInstaller.moveFiles();
1556
1557            // Prune any system packages that no longer exist.
1558            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1559            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1560            if (!mOnlyCore) {
1561                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1562                while (psit.hasNext()) {
1563                    PackageSetting ps = psit.next();
1564
1565                    /*
1566                     * If this is not a system app, it can't be a
1567                     * disable system app.
1568                     */
1569                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1570                        continue;
1571                    }
1572
1573                    /*
1574                     * If the package is scanned, it's not erased.
1575                     */
1576                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1577                    if (scannedPkg != null) {
1578                        /*
1579                         * If the system app is both scanned and in the
1580                         * disabled packages list, then it must have been
1581                         * added via OTA. Remove it from the currently
1582                         * scanned package so the previously user-installed
1583                         * application can be scanned.
1584                         */
1585                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1586                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1587                                    + ps.name + "; removing system app.  Last known codePath="
1588                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1589                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1590                                    + scannedPkg.mVersionCode);
1591                            removePackageLI(ps, true);
1592                            expectingBetter.put(ps.name, ps.codePath);
1593                        }
1594
1595                        continue;
1596                    }
1597
1598                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1599                        psit.remove();
1600                        logCriticalInfo(Log.WARN, "System package " + ps.name
1601                                + " no longer exists; wiping its data");
1602                        removeDataDirsLI(ps.name);
1603                    } else {
1604                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1605                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1606                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1607                        }
1608                    }
1609                }
1610            }
1611
1612            //look for any incomplete package installations
1613            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1614            //clean up list
1615            for(int i = 0; i < deletePkgsList.size(); i++) {
1616                //clean up here
1617                cleanupInstallFailedPackage(deletePkgsList.get(i));
1618            }
1619            //delete tmp files
1620            deleteTempPackageFiles();
1621
1622            // Remove any shared userIDs that have no associated packages
1623            mSettings.pruneSharedUsersLPw();
1624
1625            if (!mOnlyCore) {
1626                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1627                        SystemClock.uptimeMillis());
1628                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1629
1630                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1631                        scanFlags, 0);
1632
1633                /**
1634                 * Remove disable package settings for any updated system
1635                 * apps that were removed via an OTA. If they're not a
1636                 * previously-updated app, remove them completely.
1637                 * Otherwise, just revoke their system-level permissions.
1638                 */
1639                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1640                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1641                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1642
1643                    String msg;
1644                    if (deletedPkg == null) {
1645                        msg = "Updated system package " + deletedAppName
1646                                + " no longer exists; wiping its data";
1647                        removeDataDirsLI(deletedAppName);
1648                    } else {
1649                        msg = "Updated system app + " + deletedAppName
1650                                + " no longer present; removing system privileges for "
1651                                + deletedAppName;
1652
1653                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1654
1655                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1656                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1657                    }
1658                    logCriticalInfo(Log.WARN, msg);
1659                }
1660
1661                /**
1662                 * Make sure all system apps that we expected to appear on
1663                 * the userdata partition actually showed up. If they never
1664                 * appeared, crawl back and revive the system version.
1665                 */
1666                for (int i = 0; i < expectingBetter.size(); i++) {
1667                    final String packageName = expectingBetter.keyAt(i);
1668                    if (!mPackages.containsKey(packageName)) {
1669                        final File scanFile = expectingBetter.valueAt(i);
1670
1671                        logCriticalInfo(Log.WARN, "Expected better " + packageName
1672                                + " but never showed up; reverting to system");
1673
1674                        final int reparseFlags;
1675                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
1676                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1677                                    | PackageParser.PARSE_IS_SYSTEM_DIR
1678                                    | PackageParser.PARSE_IS_PRIVILEGED;
1679                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
1680                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1681                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1682                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
1683                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1684                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1685                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
1686                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1687                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1688                        } else {
1689                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
1690                            continue;
1691                        }
1692
1693                        mSettings.enableSystemPackageLPw(packageName);
1694
1695                        try {
1696                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
1697                        } catch (PackageManagerException e) {
1698                            Slog.e(TAG, "Failed to parse original system package: "
1699                                    + e.getMessage());
1700                        }
1701                    }
1702                }
1703            }
1704
1705            // Now that we know all of the shared libraries, update all clients to have
1706            // the correct library paths.
1707            updateAllSharedLibrariesLPw();
1708
1709            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1710                // NOTE: We ignore potential failures here during a system scan (like
1711                // the rest of the commands above) because there's precious little we
1712                // can do about it. A settings error is reported, though.
1713                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1714                        false /* force dexopt */, false /* defer dexopt */);
1715            }
1716
1717            // Now that we know all the packages we are keeping,
1718            // read and update their last usage times.
1719            mPackageUsage.readLP();
1720
1721            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1722                    SystemClock.uptimeMillis());
1723            Slog.i(TAG, "Time to scan packages: "
1724                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1725                    + " seconds");
1726
1727            // If the platform SDK has changed since the last time we booted,
1728            // we need to re-grant app permission to catch any new ones that
1729            // appear.  This is really a hack, and means that apps can in some
1730            // cases get permissions that the user didn't initially explicitly
1731            // allow...  it would be nice to have some better way to handle
1732            // this situation.
1733            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1734                    != mSdkVersion;
1735            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1736                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1737                    + "; regranting permissions for internal storage");
1738            mSettings.mInternalSdkPlatform = mSdkVersion;
1739
1740            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1741                    | (regrantPermissions
1742                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1743                            : 0));
1744
1745            // If this is the first boot, and it is a normal boot, then
1746            // we need to initialize the default preferred apps.
1747            if (!mRestoredSettings && !onlyCore) {
1748                mSettings.readDefaultPreferredAppsLPw(this, 0);
1749            }
1750
1751            // If this is first boot after an OTA, and a normal boot, then
1752            // we need to clear code cache directories.
1753            if (!Build.FINGERPRINT.equals(mSettings.mFingerprint) && !onlyCore) {
1754                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1755                for (String pkgName : mSettings.mPackages.keySet()) {
1756                    deleteCodeCacheDirsLI(pkgName);
1757                }
1758                mSettings.mFingerprint = Build.FINGERPRINT;
1759            }
1760
1761            // All the changes are done during package scanning.
1762            mSettings.updateInternalDatabaseVersion();
1763
1764            // can downgrade to reader
1765            mSettings.writeLPr();
1766
1767            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1768                    SystemClock.uptimeMillis());
1769
1770
1771            mRequiredVerifierPackage = getRequiredVerifierLPr();
1772        } // synchronized (mPackages)
1773        } // synchronized (mInstallLock)
1774
1775        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1776
1777        // Now after opening every single application zip, make sure they
1778        // are all flushed.  Not really needed, but keeps things nice and
1779        // tidy.
1780        Runtime.getRuntime().gc();
1781    }
1782
1783    @Override
1784    public boolean isFirstBoot() {
1785        return !mRestoredSettings;
1786    }
1787
1788    @Override
1789    public boolean isOnlyCoreApps() {
1790        return mOnlyCore;
1791    }
1792
1793    private String getRequiredVerifierLPr() {
1794        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1795        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1796                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1797
1798        String requiredVerifier = null;
1799
1800        final int N = receivers.size();
1801        for (int i = 0; i < N; i++) {
1802            final ResolveInfo info = receivers.get(i);
1803
1804            if (info.activityInfo == null) {
1805                continue;
1806            }
1807
1808            final String packageName = info.activityInfo.packageName;
1809
1810            final PackageSetting ps = mSettings.mPackages.get(packageName);
1811            if (ps == null) {
1812                continue;
1813            }
1814
1815            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1816            if (!gp.grantedPermissions
1817                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1818                continue;
1819            }
1820
1821            if (requiredVerifier != null) {
1822                throw new RuntimeException("There can be only one required verifier");
1823            }
1824
1825            requiredVerifier = packageName;
1826        }
1827
1828        return requiredVerifier;
1829    }
1830
1831    @Override
1832    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1833            throws RemoteException {
1834        try {
1835            return super.onTransact(code, data, reply, flags);
1836        } catch (RuntimeException e) {
1837            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1838                Slog.wtf(TAG, "Package Manager Crash", e);
1839            }
1840            throw e;
1841        }
1842    }
1843
1844    void cleanupInstallFailedPackage(PackageSetting ps) {
1845        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
1846
1847        removeDataDirsLI(ps.name);
1848        if (ps.codePath != null) {
1849            if (ps.codePath.isDirectory()) {
1850                FileUtils.deleteContents(ps.codePath);
1851            }
1852            ps.codePath.delete();
1853        }
1854        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1855            if (ps.resourcePath.isDirectory()) {
1856                FileUtils.deleteContents(ps.resourcePath);
1857            }
1858            ps.resourcePath.delete();
1859        }
1860        mSettings.removePackageLPw(ps.name);
1861    }
1862
1863    static int[] appendInts(int[] cur, int[] add) {
1864        if (add == null) return cur;
1865        if (cur == null) return add;
1866        final int N = add.length;
1867        for (int i=0; i<N; i++) {
1868            cur = appendInt(cur, add[i]);
1869        }
1870        return cur;
1871    }
1872
1873    static int[] removeInts(int[] cur, int[] rem) {
1874        if (rem == null) return cur;
1875        if (cur == null) return cur;
1876        final int N = rem.length;
1877        for (int i=0; i<N; i++) {
1878            cur = removeInt(cur, rem[i]);
1879        }
1880        return cur;
1881    }
1882
1883    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1884        if (!sUserManager.exists(userId)) return null;
1885        final PackageSetting ps = (PackageSetting) p.mExtras;
1886        if (ps == null) {
1887            return null;
1888        }
1889        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1890        final PackageUserState state = ps.readUserState(userId);
1891        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1892                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1893                state, userId);
1894    }
1895
1896    @Override
1897    public boolean isPackageAvailable(String packageName, int userId) {
1898        if (!sUserManager.exists(userId)) return false;
1899        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1900        synchronized (mPackages) {
1901            PackageParser.Package p = mPackages.get(packageName);
1902            if (p != null) {
1903                final PackageSetting ps = (PackageSetting) p.mExtras;
1904                if (ps != null) {
1905                    final PackageUserState state = ps.readUserState(userId);
1906                    if (state != null) {
1907                        return PackageParser.isAvailable(state);
1908                    }
1909                }
1910            }
1911        }
1912        return false;
1913    }
1914
1915    @Override
1916    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1917        if (!sUserManager.exists(userId)) return null;
1918        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
1919        // reader
1920        synchronized (mPackages) {
1921            PackageParser.Package p = mPackages.get(packageName);
1922            if (DEBUG_PACKAGE_INFO)
1923                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1924            if (p != null) {
1925                return generatePackageInfo(p, flags, userId);
1926            }
1927            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1928                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1929            }
1930        }
1931        return null;
1932    }
1933
1934    @Override
1935    public String[] currentToCanonicalPackageNames(String[] names) {
1936        String[] out = new String[names.length];
1937        // reader
1938        synchronized (mPackages) {
1939            for (int i=names.length-1; i>=0; i--) {
1940                PackageSetting ps = mSettings.mPackages.get(names[i]);
1941                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1942            }
1943        }
1944        return out;
1945    }
1946
1947    @Override
1948    public String[] canonicalToCurrentPackageNames(String[] names) {
1949        String[] out = new String[names.length];
1950        // reader
1951        synchronized (mPackages) {
1952            for (int i=names.length-1; i>=0; i--) {
1953                String cur = mSettings.mRenamedPackages.get(names[i]);
1954                out[i] = cur != null ? cur : names[i];
1955            }
1956        }
1957        return out;
1958    }
1959
1960    @Override
1961    public int getPackageUid(String packageName, int userId) {
1962        if (!sUserManager.exists(userId)) return -1;
1963        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
1964        // reader
1965        synchronized (mPackages) {
1966            PackageParser.Package p = mPackages.get(packageName);
1967            if(p != null) {
1968                return UserHandle.getUid(userId, p.applicationInfo.uid);
1969            }
1970            PackageSetting ps = mSettings.mPackages.get(packageName);
1971            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1972                return -1;
1973            }
1974            p = ps.pkg;
1975            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1976        }
1977    }
1978
1979    @Override
1980    public int[] getPackageGids(String packageName) {
1981        // reader
1982        synchronized (mPackages) {
1983            PackageParser.Package p = mPackages.get(packageName);
1984            if (DEBUG_PACKAGE_INFO)
1985                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1986            if (p != null) {
1987                final PackageSetting ps = (PackageSetting)p.mExtras;
1988                return ps.getGids();
1989            }
1990        }
1991        // stupid thing to indicate an error.
1992        return new int[0];
1993    }
1994
1995    static final PermissionInfo generatePermissionInfo(
1996            BasePermission bp, int flags) {
1997        if (bp.perm != null) {
1998            return PackageParser.generatePermissionInfo(bp.perm, flags);
1999        }
2000        PermissionInfo pi = new PermissionInfo();
2001        pi.name = bp.name;
2002        pi.packageName = bp.sourcePackage;
2003        pi.nonLocalizedLabel = bp.name;
2004        pi.protectionLevel = bp.protectionLevel;
2005        return pi;
2006    }
2007
2008    @Override
2009    public PermissionInfo getPermissionInfo(String name, int flags) {
2010        // reader
2011        synchronized (mPackages) {
2012            final BasePermission p = mSettings.mPermissions.get(name);
2013            if (p != null) {
2014                return generatePermissionInfo(p, flags);
2015            }
2016            return null;
2017        }
2018    }
2019
2020    @Override
2021    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2022        // reader
2023        synchronized (mPackages) {
2024            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2025            for (BasePermission p : mSettings.mPermissions.values()) {
2026                if (group == null) {
2027                    if (p.perm == null || p.perm.info.group == null) {
2028                        out.add(generatePermissionInfo(p, flags));
2029                    }
2030                } else {
2031                    if (p.perm != null && group.equals(p.perm.info.group)) {
2032                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2033                    }
2034                }
2035            }
2036
2037            if (out.size() > 0) {
2038                return out;
2039            }
2040            return mPermissionGroups.containsKey(group) ? out : null;
2041        }
2042    }
2043
2044    @Override
2045    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2046        // reader
2047        synchronized (mPackages) {
2048            return PackageParser.generatePermissionGroupInfo(
2049                    mPermissionGroups.get(name), flags);
2050        }
2051    }
2052
2053    @Override
2054    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2055        // reader
2056        synchronized (mPackages) {
2057            final int N = mPermissionGroups.size();
2058            ArrayList<PermissionGroupInfo> out
2059                    = new ArrayList<PermissionGroupInfo>(N);
2060            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2061                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2062            }
2063            return out;
2064        }
2065    }
2066
2067    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2068            int userId) {
2069        if (!sUserManager.exists(userId)) return null;
2070        PackageSetting ps = mSettings.mPackages.get(packageName);
2071        if (ps != null) {
2072            if (ps.pkg == null) {
2073                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2074                        flags, userId);
2075                if (pInfo != null) {
2076                    return pInfo.applicationInfo;
2077                }
2078                return null;
2079            }
2080            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2081                    ps.readUserState(userId), userId);
2082        }
2083        return null;
2084    }
2085
2086    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2087            int userId) {
2088        if (!sUserManager.exists(userId)) return null;
2089        PackageSetting ps = mSettings.mPackages.get(packageName);
2090        if (ps != null) {
2091            PackageParser.Package pkg = ps.pkg;
2092            if (pkg == null) {
2093                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2094                    return null;
2095                }
2096                // Only data remains, so we aren't worried about code paths
2097                pkg = new PackageParser.Package(packageName);
2098                pkg.applicationInfo.packageName = packageName;
2099                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2100                pkg.applicationInfo.dataDir =
2101                        getDataPathForPackage(packageName, 0).getPath();
2102                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2103                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2104            }
2105            return generatePackageInfo(pkg, flags, userId);
2106        }
2107        return null;
2108    }
2109
2110    @Override
2111    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2112        if (!sUserManager.exists(userId)) return null;
2113        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2114        // writer
2115        synchronized (mPackages) {
2116            PackageParser.Package p = mPackages.get(packageName);
2117            if (DEBUG_PACKAGE_INFO) Log.v(
2118                    TAG, "getApplicationInfo " + packageName
2119                    + ": " + p);
2120            if (p != null) {
2121                PackageSetting ps = mSettings.mPackages.get(packageName);
2122                if (ps == null) return null;
2123                // Note: isEnabledLP() does not apply here - always return info
2124                return PackageParser.generateApplicationInfo(
2125                        p, flags, ps.readUserState(userId), userId);
2126            }
2127            if ("android".equals(packageName)||"system".equals(packageName)) {
2128                return mAndroidApplication;
2129            }
2130            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2131                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2132            }
2133        }
2134        return null;
2135    }
2136
2137
2138    @Override
2139    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2140        mContext.enforceCallingOrSelfPermission(
2141                android.Manifest.permission.CLEAR_APP_CACHE, null);
2142        // Queue up an async operation since clearing cache may take a little while.
2143        mHandler.post(new Runnable() {
2144            public void run() {
2145                mHandler.removeCallbacks(this);
2146                int retCode = -1;
2147                synchronized (mInstallLock) {
2148                    retCode = mInstaller.freeCache(freeStorageSize);
2149                    if (retCode < 0) {
2150                        Slog.w(TAG, "Couldn't clear application caches");
2151                    }
2152                }
2153                if (observer != null) {
2154                    try {
2155                        observer.onRemoveCompleted(null, (retCode >= 0));
2156                    } catch (RemoteException e) {
2157                        Slog.w(TAG, "RemoveException when invoking call back");
2158                    }
2159                }
2160            }
2161        });
2162    }
2163
2164    @Override
2165    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2166        mContext.enforceCallingOrSelfPermission(
2167                android.Manifest.permission.CLEAR_APP_CACHE, null);
2168        // Queue up an async operation since clearing cache may take a little while.
2169        mHandler.post(new Runnable() {
2170            public void run() {
2171                mHandler.removeCallbacks(this);
2172                int retCode = -1;
2173                synchronized (mInstallLock) {
2174                    retCode = mInstaller.freeCache(freeStorageSize);
2175                    if (retCode < 0) {
2176                        Slog.w(TAG, "Couldn't clear application caches");
2177                    }
2178                }
2179                if(pi != null) {
2180                    try {
2181                        // Callback via pending intent
2182                        int code = (retCode >= 0) ? 1 : 0;
2183                        pi.sendIntent(null, code, null,
2184                                null, null);
2185                    } catch (SendIntentException e1) {
2186                        Slog.i(TAG, "Failed to send pending intent");
2187                    }
2188                }
2189            }
2190        });
2191    }
2192
2193    void freeStorage(long freeStorageSize) throws IOException {
2194        synchronized (mInstallLock) {
2195            if (mInstaller.freeCache(freeStorageSize) < 0) {
2196                throw new IOException("Failed to free enough space");
2197            }
2198        }
2199    }
2200
2201    @Override
2202    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2203        if (!sUserManager.exists(userId)) return null;
2204        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2205        synchronized (mPackages) {
2206            PackageParser.Activity a = mActivities.mActivities.get(component);
2207
2208            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2209            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2210                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2211                if (ps == null) return null;
2212                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2213                        userId);
2214            }
2215            if (mResolveComponentName.equals(component)) {
2216                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2217                        new PackageUserState(), userId);
2218            }
2219        }
2220        return null;
2221    }
2222
2223    @Override
2224    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2225            String resolvedType) {
2226        synchronized (mPackages) {
2227            PackageParser.Activity a = mActivities.mActivities.get(component);
2228            if (a == null) {
2229                return false;
2230            }
2231            for (int i=0; i<a.intents.size(); i++) {
2232                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2233                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2234                    return true;
2235                }
2236            }
2237            return false;
2238        }
2239    }
2240
2241    @Override
2242    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2243        if (!sUserManager.exists(userId)) return null;
2244        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2245        synchronized (mPackages) {
2246            PackageParser.Activity a = mReceivers.mActivities.get(component);
2247            if (DEBUG_PACKAGE_INFO) Log.v(
2248                TAG, "getReceiverInfo " + component + ": " + a);
2249            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2250                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2251                if (ps == null) return null;
2252                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2253                        userId);
2254            }
2255        }
2256        return null;
2257    }
2258
2259    @Override
2260    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2261        if (!sUserManager.exists(userId)) return null;
2262        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2263        synchronized (mPackages) {
2264            PackageParser.Service s = mServices.mServices.get(component);
2265            if (DEBUG_PACKAGE_INFO) Log.v(
2266                TAG, "getServiceInfo " + component + ": " + s);
2267            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2268                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2269                if (ps == null) return null;
2270                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2271                        userId);
2272            }
2273        }
2274        return null;
2275    }
2276
2277    @Override
2278    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2279        if (!sUserManager.exists(userId)) return null;
2280        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2281        synchronized (mPackages) {
2282            PackageParser.Provider p = mProviders.mProviders.get(component);
2283            if (DEBUG_PACKAGE_INFO) Log.v(
2284                TAG, "getProviderInfo " + component + ": " + p);
2285            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2286                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2287                if (ps == null) return null;
2288                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2289                        userId);
2290            }
2291        }
2292        return null;
2293    }
2294
2295    @Override
2296    public String[] getSystemSharedLibraryNames() {
2297        Set<String> libSet;
2298        synchronized (mPackages) {
2299            libSet = mSharedLibraries.keySet();
2300            int size = libSet.size();
2301            if (size > 0) {
2302                String[] libs = new String[size];
2303                libSet.toArray(libs);
2304                return libs;
2305            }
2306        }
2307        return null;
2308    }
2309
2310    @Override
2311    public FeatureInfo[] getSystemAvailableFeatures() {
2312        Collection<FeatureInfo> featSet;
2313        synchronized (mPackages) {
2314            featSet = mAvailableFeatures.values();
2315            int size = featSet.size();
2316            if (size > 0) {
2317                FeatureInfo[] features = new FeatureInfo[size+1];
2318                featSet.toArray(features);
2319                FeatureInfo fi = new FeatureInfo();
2320                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2321                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2322                features[size] = fi;
2323                return features;
2324            }
2325        }
2326        return null;
2327    }
2328
2329    @Override
2330    public boolean hasSystemFeature(String name) {
2331        synchronized (mPackages) {
2332            return mAvailableFeatures.containsKey(name);
2333        }
2334    }
2335
2336    private void checkValidCaller(int uid, int userId) {
2337        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2338            return;
2339
2340        throw new SecurityException("Caller uid=" + uid
2341                + " is not privileged to communicate with user=" + userId);
2342    }
2343
2344    @Override
2345    public int checkPermission(String permName, String pkgName) {
2346        synchronized (mPackages) {
2347            PackageParser.Package p = mPackages.get(pkgName);
2348            if (p != null && p.mExtras != null) {
2349                PackageSetting ps = (PackageSetting)p.mExtras;
2350                if (ps.sharedUser != null) {
2351                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2352                        return PackageManager.PERMISSION_GRANTED;
2353                    }
2354                } else if (ps.grantedPermissions.contains(permName)) {
2355                    return PackageManager.PERMISSION_GRANTED;
2356                }
2357            }
2358        }
2359        return PackageManager.PERMISSION_DENIED;
2360    }
2361
2362    @Override
2363    public int checkUidPermission(String permName, int uid) {
2364        synchronized (mPackages) {
2365            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2366            if (obj != null) {
2367                GrantedPermissions gp = (GrantedPermissions)obj;
2368                if (gp.grantedPermissions.contains(permName)) {
2369                    return PackageManager.PERMISSION_GRANTED;
2370                }
2371            } else {
2372                HashSet<String> perms = mSystemPermissions.get(uid);
2373                if (perms != null && perms.contains(permName)) {
2374                    return PackageManager.PERMISSION_GRANTED;
2375                }
2376            }
2377        }
2378        return PackageManager.PERMISSION_DENIED;
2379    }
2380
2381    /**
2382     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2383     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2384     * @param checkShell TODO(yamasani):
2385     * @param message the message to log on security exception
2386     */
2387    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2388            boolean checkShell, String message) {
2389        if (userId < 0) {
2390            throw new IllegalArgumentException("Invalid userId " + userId);
2391        }
2392        if (checkShell) {
2393            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2394        }
2395        if (userId == UserHandle.getUserId(callingUid)) return;
2396        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2397            if (requireFullPermission) {
2398                mContext.enforceCallingOrSelfPermission(
2399                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2400            } else {
2401                try {
2402                    mContext.enforceCallingOrSelfPermission(
2403                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2404                } catch (SecurityException se) {
2405                    mContext.enforceCallingOrSelfPermission(
2406                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2407                }
2408            }
2409        }
2410    }
2411
2412    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2413        if (callingUid == Process.SHELL_UID) {
2414            if (userHandle >= 0
2415                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2416                throw new SecurityException("Shell does not have permission to access user "
2417                        + userHandle);
2418            } else if (userHandle < 0) {
2419                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2420                        + Debug.getCallers(3));
2421            }
2422        }
2423    }
2424
2425    private BasePermission findPermissionTreeLP(String permName) {
2426        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2427            if (permName.startsWith(bp.name) &&
2428                    permName.length() > bp.name.length() &&
2429                    permName.charAt(bp.name.length()) == '.') {
2430                return bp;
2431            }
2432        }
2433        return null;
2434    }
2435
2436    private BasePermission checkPermissionTreeLP(String permName) {
2437        if (permName != null) {
2438            BasePermission bp = findPermissionTreeLP(permName);
2439            if (bp != null) {
2440                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2441                    return bp;
2442                }
2443                throw new SecurityException("Calling uid "
2444                        + Binder.getCallingUid()
2445                        + " is not allowed to add to permission tree "
2446                        + bp.name + " owned by uid " + bp.uid);
2447            }
2448        }
2449        throw new SecurityException("No permission tree found for " + permName);
2450    }
2451
2452    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2453        if (s1 == null) {
2454            return s2 == null;
2455        }
2456        if (s2 == null) {
2457            return false;
2458        }
2459        if (s1.getClass() != s2.getClass()) {
2460            return false;
2461        }
2462        return s1.equals(s2);
2463    }
2464
2465    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2466        if (pi1.icon != pi2.icon) return false;
2467        if (pi1.logo != pi2.logo) return false;
2468        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2469        if (!compareStrings(pi1.name, pi2.name)) return false;
2470        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2471        // We'll take care of setting this one.
2472        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2473        // These are not currently stored in settings.
2474        //if (!compareStrings(pi1.group, pi2.group)) return false;
2475        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2476        //if (pi1.labelRes != pi2.labelRes) return false;
2477        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2478        return true;
2479    }
2480
2481    int permissionInfoFootprint(PermissionInfo info) {
2482        int size = info.name.length();
2483        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2484        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2485        return size;
2486    }
2487
2488    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2489        int size = 0;
2490        for (BasePermission perm : mSettings.mPermissions.values()) {
2491            if (perm.uid == tree.uid) {
2492                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2493            }
2494        }
2495        return size;
2496    }
2497
2498    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2499        // We calculate the max size of permissions defined by this uid and throw
2500        // if that plus the size of 'info' would exceed our stated maximum.
2501        if (tree.uid != Process.SYSTEM_UID) {
2502            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2503            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2504                throw new SecurityException("Permission tree size cap exceeded");
2505            }
2506        }
2507    }
2508
2509    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2510        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2511            throw new SecurityException("Label must be specified in permission");
2512        }
2513        BasePermission tree = checkPermissionTreeLP(info.name);
2514        BasePermission bp = mSettings.mPermissions.get(info.name);
2515        boolean added = bp == null;
2516        boolean changed = true;
2517        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2518        if (added) {
2519            enforcePermissionCapLocked(info, tree);
2520            bp = new BasePermission(info.name, tree.sourcePackage,
2521                    BasePermission.TYPE_DYNAMIC);
2522        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2523            throw new SecurityException(
2524                    "Not allowed to modify non-dynamic permission "
2525                    + info.name);
2526        } else {
2527            if (bp.protectionLevel == fixedLevel
2528                    && bp.perm.owner.equals(tree.perm.owner)
2529                    && bp.uid == tree.uid
2530                    && comparePermissionInfos(bp.perm.info, info)) {
2531                changed = false;
2532            }
2533        }
2534        bp.protectionLevel = fixedLevel;
2535        info = new PermissionInfo(info);
2536        info.protectionLevel = fixedLevel;
2537        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2538        bp.perm.info.packageName = tree.perm.info.packageName;
2539        bp.uid = tree.uid;
2540        if (added) {
2541            mSettings.mPermissions.put(info.name, bp);
2542        }
2543        if (changed) {
2544            if (!async) {
2545                mSettings.writeLPr();
2546            } else {
2547                scheduleWriteSettingsLocked();
2548            }
2549        }
2550        return added;
2551    }
2552
2553    @Override
2554    public boolean addPermission(PermissionInfo info) {
2555        synchronized (mPackages) {
2556            return addPermissionLocked(info, false);
2557        }
2558    }
2559
2560    @Override
2561    public boolean addPermissionAsync(PermissionInfo info) {
2562        synchronized (mPackages) {
2563            return addPermissionLocked(info, true);
2564        }
2565    }
2566
2567    @Override
2568    public void removePermission(String name) {
2569        synchronized (mPackages) {
2570            checkPermissionTreeLP(name);
2571            BasePermission bp = mSettings.mPermissions.get(name);
2572            if (bp != null) {
2573                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2574                    throw new SecurityException(
2575                            "Not allowed to modify non-dynamic permission "
2576                            + name);
2577                }
2578                mSettings.mPermissions.remove(name);
2579                mSettings.writeLPr();
2580            }
2581        }
2582    }
2583
2584    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2585        int index = pkg.requestedPermissions.indexOf(bp.name);
2586        if (index == -1) {
2587            throw new SecurityException("Package " + pkg.packageName
2588                    + " has not requested permission " + bp.name);
2589        }
2590        boolean isNormal =
2591                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2592                        == PermissionInfo.PROTECTION_NORMAL);
2593        boolean isDangerous =
2594                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2595                        == PermissionInfo.PROTECTION_DANGEROUS);
2596        boolean isDevelopment =
2597                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2598
2599        if (!isNormal && !isDangerous && !isDevelopment) {
2600            throw new SecurityException("Permission " + bp.name
2601                    + " is not a changeable permission type");
2602        }
2603
2604        if (isNormal || isDangerous) {
2605            if (pkg.requestedPermissionsRequired.get(index)) {
2606                throw new SecurityException("Can't change " + bp.name
2607                        + ". It is required by the application");
2608            }
2609        }
2610    }
2611
2612    @Override
2613    public void grantPermission(String packageName, String permissionName) {
2614        mContext.enforceCallingOrSelfPermission(
2615                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2616        synchronized (mPackages) {
2617            final PackageParser.Package pkg = mPackages.get(packageName);
2618            if (pkg == null) {
2619                throw new IllegalArgumentException("Unknown package: " + packageName);
2620            }
2621            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2622            if (bp == null) {
2623                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2624            }
2625
2626            checkGrantRevokePermissions(pkg, bp);
2627
2628            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2629            if (ps == null) {
2630                return;
2631            }
2632            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2633            if (gp.grantedPermissions.add(permissionName)) {
2634                if (ps.haveGids) {
2635                    gp.gids = appendInts(gp.gids, bp.gids);
2636                }
2637                mSettings.writeLPr();
2638            }
2639        }
2640    }
2641
2642    @Override
2643    public void revokePermission(String packageName, String permissionName) {
2644        int changedAppId = -1;
2645
2646        synchronized (mPackages) {
2647            final PackageParser.Package pkg = mPackages.get(packageName);
2648            if (pkg == null) {
2649                throw new IllegalArgumentException("Unknown package: " + packageName);
2650            }
2651            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2652                mContext.enforceCallingOrSelfPermission(
2653                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2654            }
2655            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2656            if (bp == null) {
2657                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2658            }
2659
2660            checkGrantRevokePermissions(pkg, bp);
2661
2662            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2663            if (ps == null) {
2664                return;
2665            }
2666            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2667            if (gp.grantedPermissions.remove(permissionName)) {
2668                gp.grantedPermissions.remove(permissionName);
2669                if (ps.haveGids) {
2670                    gp.gids = removeInts(gp.gids, bp.gids);
2671                }
2672                mSettings.writeLPr();
2673                changedAppId = ps.appId;
2674            }
2675        }
2676
2677        if (changedAppId >= 0) {
2678            // We changed the perm on someone, kill its processes.
2679            IActivityManager am = ActivityManagerNative.getDefault();
2680            if (am != null) {
2681                final int callingUserId = UserHandle.getCallingUserId();
2682                final long ident = Binder.clearCallingIdentity();
2683                try {
2684                    //XXX we should only revoke for the calling user's app permissions,
2685                    // but for now we impact all users.
2686                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2687                    //        "revoke " + permissionName);
2688                    int[] users = sUserManager.getUserIds();
2689                    for (int user : users) {
2690                        am.killUid(UserHandle.getUid(user, changedAppId),
2691                                "revoke " + permissionName);
2692                    }
2693                } catch (RemoteException e) {
2694                } finally {
2695                    Binder.restoreCallingIdentity(ident);
2696                }
2697            }
2698        }
2699    }
2700
2701    @Override
2702    public boolean isProtectedBroadcast(String actionName) {
2703        synchronized (mPackages) {
2704            return mProtectedBroadcasts.contains(actionName);
2705        }
2706    }
2707
2708    @Override
2709    public int checkSignatures(String pkg1, String pkg2) {
2710        synchronized (mPackages) {
2711            final PackageParser.Package p1 = mPackages.get(pkg1);
2712            final PackageParser.Package p2 = mPackages.get(pkg2);
2713            if (p1 == null || p1.mExtras == null
2714                    || p2 == null || p2.mExtras == null) {
2715                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2716            }
2717            return compareSignatures(p1.mSignatures, p2.mSignatures);
2718        }
2719    }
2720
2721    @Override
2722    public int checkUidSignatures(int uid1, int uid2) {
2723        // Map to base uids.
2724        uid1 = UserHandle.getAppId(uid1);
2725        uid2 = UserHandle.getAppId(uid2);
2726        // reader
2727        synchronized (mPackages) {
2728            Signature[] s1;
2729            Signature[] s2;
2730            Object obj = mSettings.getUserIdLPr(uid1);
2731            if (obj != null) {
2732                if (obj instanceof SharedUserSetting) {
2733                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2734                } else if (obj instanceof PackageSetting) {
2735                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2736                } else {
2737                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2738                }
2739            } else {
2740                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2741            }
2742            obj = mSettings.getUserIdLPr(uid2);
2743            if (obj != null) {
2744                if (obj instanceof SharedUserSetting) {
2745                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2746                } else if (obj instanceof PackageSetting) {
2747                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2748                } else {
2749                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2750                }
2751            } else {
2752                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2753            }
2754            return compareSignatures(s1, s2);
2755        }
2756    }
2757
2758    /**
2759     * Compares two sets of signatures. Returns:
2760     * <br />
2761     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2762     * <br />
2763     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2764     * <br />
2765     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2766     * <br />
2767     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2768     * <br />
2769     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2770     */
2771    static int compareSignatures(Signature[] s1, Signature[] s2) {
2772        if (s1 == null) {
2773            return s2 == null
2774                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2775                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2776        }
2777
2778        if (s2 == null) {
2779            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2780        }
2781
2782        if (s1.length != s2.length) {
2783            return PackageManager.SIGNATURE_NO_MATCH;
2784        }
2785
2786        // Since both signature sets are of size 1, we can compare without HashSets.
2787        if (s1.length == 1) {
2788            return s1[0].equals(s2[0]) ?
2789                    PackageManager.SIGNATURE_MATCH :
2790                    PackageManager.SIGNATURE_NO_MATCH;
2791        }
2792
2793        HashSet<Signature> set1 = new HashSet<Signature>();
2794        for (Signature sig : s1) {
2795            set1.add(sig);
2796        }
2797        HashSet<Signature> set2 = new HashSet<Signature>();
2798        for (Signature sig : s2) {
2799            set2.add(sig);
2800        }
2801        // Make sure s2 contains all signatures in s1.
2802        if (set1.equals(set2)) {
2803            return PackageManager.SIGNATURE_MATCH;
2804        }
2805        return PackageManager.SIGNATURE_NO_MATCH;
2806    }
2807
2808    /**
2809     * If the database version for this type of package (internal storage or
2810     * external storage) is less than the version where package signatures
2811     * were updated, return true.
2812     */
2813    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2814        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2815                DatabaseVersion.SIGNATURE_END_ENTITY))
2816                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2817                        DatabaseVersion.SIGNATURE_END_ENTITY));
2818    }
2819
2820    /**
2821     * Used for backward compatibility to make sure any packages with
2822     * certificate chains get upgraded to the new style. {@code existingSigs}
2823     * will be in the old format (since they were stored on disk from before the
2824     * system upgrade) and {@code scannedSigs} will be in the newer format.
2825     */
2826    private int compareSignaturesCompat(PackageSignatures existingSigs,
2827            PackageParser.Package scannedPkg) {
2828        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2829            return PackageManager.SIGNATURE_NO_MATCH;
2830        }
2831
2832        HashSet<Signature> existingSet = new HashSet<Signature>();
2833        for (Signature sig : existingSigs.mSignatures) {
2834            existingSet.add(sig);
2835        }
2836        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2837        for (Signature sig : scannedPkg.mSignatures) {
2838            try {
2839                Signature[] chainSignatures = sig.getChainSignatures();
2840                for (Signature chainSig : chainSignatures) {
2841                    scannedCompatSet.add(chainSig);
2842                }
2843            } catch (CertificateEncodingException e) {
2844                scannedCompatSet.add(sig);
2845            }
2846        }
2847        /*
2848         * Make sure the expanded scanned set contains all signatures in the
2849         * existing one.
2850         */
2851        if (scannedCompatSet.equals(existingSet)) {
2852            // Migrate the old signatures to the new scheme.
2853            existingSigs.assignSignatures(scannedPkg.mSignatures);
2854            // The new KeySets will be re-added later in the scanning process.
2855            synchronized (mPackages) {
2856                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2857            }
2858            return PackageManager.SIGNATURE_MATCH;
2859        }
2860        return PackageManager.SIGNATURE_NO_MATCH;
2861    }
2862
2863    @Override
2864    public String[] getPackagesForUid(int uid) {
2865        uid = UserHandle.getAppId(uid);
2866        // reader
2867        synchronized (mPackages) {
2868            Object obj = mSettings.getUserIdLPr(uid);
2869            if (obj instanceof SharedUserSetting) {
2870                final SharedUserSetting sus = (SharedUserSetting) obj;
2871                final int N = sus.packages.size();
2872                final String[] res = new String[N];
2873                final Iterator<PackageSetting> it = sus.packages.iterator();
2874                int i = 0;
2875                while (it.hasNext()) {
2876                    res[i++] = it.next().name;
2877                }
2878                return res;
2879            } else if (obj instanceof PackageSetting) {
2880                final PackageSetting ps = (PackageSetting) obj;
2881                return new String[] { ps.name };
2882            }
2883        }
2884        return null;
2885    }
2886
2887    @Override
2888    public String getNameForUid(int uid) {
2889        // reader
2890        synchronized (mPackages) {
2891            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2892            if (obj instanceof SharedUserSetting) {
2893                final SharedUserSetting sus = (SharedUserSetting) obj;
2894                return sus.name + ":" + sus.userId;
2895            } else if (obj instanceof PackageSetting) {
2896                final PackageSetting ps = (PackageSetting) obj;
2897                return ps.name;
2898            }
2899        }
2900        return null;
2901    }
2902
2903    @Override
2904    public int getUidForSharedUser(String sharedUserName) {
2905        if(sharedUserName == null) {
2906            return -1;
2907        }
2908        // reader
2909        synchronized (mPackages) {
2910            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2911            if (suid == null) {
2912                return -1;
2913            }
2914            return suid.userId;
2915        }
2916    }
2917
2918    @Override
2919    public int getFlagsForUid(int uid) {
2920        synchronized (mPackages) {
2921            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2922            if (obj instanceof SharedUserSetting) {
2923                final SharedUserSetting sus = (SharedUserSetting) obj;
2924                return sus.pkgFlags;
2925            } else if (obj instanceof PackageSetting) {
2926                final PackageSetting ps = (PackageSetting) obj;
2927                return ps.pkgFlags;
2928            }
2929        }
2930        return 0;
2931    }
2932
2933    @Override
2934    public boolean isUidPrivileged(int uid) {
2935        uid = UserHandle.getAppId(uid);
2936        // reader
2937        synchronized (mPackages) {
2938            Object obj = mSettings.getUserIdLPr(uid);
2939            if (obj instanceof SharedUserSetting) {
2940                final SharedUserSetting sus = (SharedUserSetting) obj;
2941                final Iterator<PackageSetting> it = sus.packages.iterator();
2942                while (it.hasNext()) {
2943                    if (it.next().isPrivileged()) {
2944                        return true;
2945                    }
2946                }
2947            } else if (obj instanceof PackageSetting) {
2948                final PackageSetting ps = (PackageSetting) obj;
2949                return ps.isPrivileged();
2950            }
2951        }
2952        return false;
2953    }
2954
2955    @Override
2956    public String[] getAppOpPermissionPackages(String permissionName) {
2957        synchronized (mPackages) {
2958            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2959            if (pkgs == null) {
2960                return null;
2961            }
2962            return pkgs.toArray(new String[pkgs.size()]);
2963        }
2964    }
2965
2966    @Override
2967    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
2968            int flags, int userId) {
2969        if (!sUserManager.exists(userId)) return null;
2970        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
2971        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2972        return chooseBestActivity(intent, resolvedType, flags, query, userId);
2973    }
2974
2975    @Override
2976    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
2977            IntentFilter filter, int match, ComponentName activity) {
2978        final int userId = UserHandle.getCallingUserId();
2979        if (DEBUG_PREFERRED) {
2980            Log.v(TAG, "setLastChosenActivity intent=" + intent
2981                + " resolvedType=" + resolvedType
2982                + " flags=" + flags
2983                + " filter=" + filter
2984                + " match=" + match
2985                + " activity=" + activity);
2986            filter.dump(new PrintStreamPrinter(System.out), "    ");
2987        }
2988        intent.setComponent(null);
2989        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
2990        // Find any earlier preferred or last chosen entries and nuke them
2991        findPreferredActivity(intent, resolvedType,
2992                flags, query, 0, false, true, false, userId);
2993        // Add the new activity as the last chosen for this filter
2994        addPreferredActivityInternal(filter, match, null, activity, false, userId,
2995                "Setting last chosen");
2996    }
2997
2998    @Override
2999    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3000        final int userId = UserHandle.getCallingUserId();
3001        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3002        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3003        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3004                false, false, false, userId);
3005    }
3006
3007    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3008            int flags, List<ResolveInfo> query, int userId) {
3009        if (query != null) {
3010            final int N = query.size();
3011            if (N == 1) {
3012                return query.get(0);
3013            } else if (N > 1) {
3014                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3015                // If there is more than one activity with the same priority,
3016                // then let the user decide between them.
3017                ResolveInfo r0 = query.get(0);
3018                ResolveInfo r1 = query.get(1);
3019                if (DEBUG_INTENT_MATCHING || debug) {
3020                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3021                            + r1.activityInfo.name + "=" + r1.priority);
3022                }
3023                // If the first activity has a higher priority, or a different
3024                // default, then it is always desireable to pick it.
3025                if (r0.priority != r1.priority
3026                        || r0.preferredOrder != r1.preferredOrder
3027                        || r0.isDefault != r1.isDefault) {
3028                    return query.get(0);
3029                }
3030                // If we have saved a preference for a preferred activity for
3031                // this Intent, use that.
3032                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3033                        flags, query, r0.priority, true, false, debug, userId);
3034                if (ri != null) {
3035                    return ri;
3036                }
3037                if (userId != 0) {
3038                    ri = new ResolveInfo(mResolveInfo);
3039                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3040                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3041                            ri.activityInfo.applicationInfo);
3042                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3043                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3044                    return ri;
3045                }
3046                return mResolveInfo;
3047            }
3048        }
3049        return null;
3050    }
3051
3052    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3053            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3054        final int N = query.size();
3055        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3056                .get(userId);
3057        // Get the list of persistent preferred activities that handle the intent
3058        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3059        List<PersistentPreferredActivity> pprefs = ppir != null
3060                ? ppir.queryIntent(intent, resolvedType,
3061                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3062                : null;
3063        if (pprefs != null && pprefs.size() > 0) {
3064            final int M = pprefs.size();
3065            for (int i=0; i<M; i++) {
3066                final PersistentPreferredActivity ppa = pprefs.get(i);
3067                if (DEBUG_PREFERRED || debug) {
3068                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3069                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3070                            + "\n  component=" + ppa.mComponent);
3071                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3072                }
3073                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3074                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3075                if (DEBUG_PREFERRED || debug) {
3076                    Slog.v(TAG, "Found persistent preferred activity:");
3077                    if (ai != null) {
3078                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3079                    } else {
3080                        Slog.v(TAG, "  null");
3081                    }
3082                }
3083                if (ai == null) {
3084                    // This previously registered persistent preferred activity
3085                    // component is no longer known. Ignore it and do NOT remove it.
3086                    continue;
3087                }
3088                for (int j=0; j<N; j++) {
3089                    final ResolveInfo ri = query.get(j);
3090                    if (!ri.activityInfo.applicationInfo.packageName
3091                            .equals(ai.applicationInfo.packageName)) {
3092                        continue;
3093                    }
3094                    if (!ri.activityInfo.name.equals(ai.name)) {
3095                        continue;
3096                    }
3097                    //  Found a persistent preference that can handle the intent.
3098                    if (DEBUG_PREFERRED || debug) {
3099                        Slog.v(TAG, "Returning persistent preferred activity: " +
3100                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3101                    }
3102                    return ri;
3103                }
3104            }
3105        }
3106        return null;
3107    }
3108
3109    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3110            List<ResolveInfo> query, int priority, boolean always,
3111            boolean removeMatches, boolean debug, int userId) {
3112        if (!sUserManager.exists(userId)) return null;
3113        // writer
3114        synchronized (mPackages) {
3115            if (intent.getSelector() != null) {
3116                intent = intent.getSelector();
3117            }
3118            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3119
3120            // Try to find a matching persistent preferred activity.
3121            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3122                    debug, userId);
3123
3124            // If a persistent preferred activity matched, use it.
3125            if (pri != null) {
3126                return pri;
3127            }
3128
3129            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3130            // Get the list of preferred activities that handle the intent
3131            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3132            List<PreferredActivity> prefs = pir != null
3133                    ? pir.queryIntent(intent, resolvedType,
3134                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3135                    : null;
3136            if (prefs != null && prefs.size() > 0) {
3137                boolean changed = false;
3138                try {
3139                    // First figure out how good the original match set is.
3140                    // We will only allow preferred activities that came
3141                    // from the same match quality.
3142                    int match = 0;
3143
3144                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3145
3146                    final int N = query.size();
3147                    for (int j=0; j<N; j++) {
3148                        final ResolveInfo ri = query.get(j);
3149                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3150                                + ": 0x" + Integer.toHexString(match));
3151                        if (ri.match > match) {
3152                            match = ri.match;
3153                        }
3154                    }
3155
3156                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3157                            + Integer.toHexString(match));
3158
3159                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3160                    final int M = prefs.size();
3161                    for (int i=0; i<M; i++) {
3162                        final PreferredActivity pa = prefs.get(i);
3163                        if (DEBUG_PREFERRED || debug) {
3164                            Slog.v(TAG, "Checking PreferredActivity ds="
3165                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3166                                    + "\n  component=" + pa.mPref.mComponent);
3167                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3168                        }
3169                        if (pa.mPref.mMatch != match) {
3170                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3171                                    + Integer.toHexString(pa.mPref.mMatch));
3172                            continue;
3173                        }
3174                        // If it's not an "always" type preferred activity and that's what we're
3175                        // looking for, skip it.
3176                        if (always && !pa.mPref.mAlways) {
3177                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3178                            continue;
3179                        }
3180                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3181                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3182                        if (DEBUG_PREFERRED || debug) {
3183                            Slog.v(TAG, "Found preferred activity:");
3184                            if (ai != null) {
3185                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3186                            } else {
3187                                Slog.v(TAG, "  null");
3188                            }
3189                        }
3190                        if (ai == null) {
3191                            // This previously registered preferred activity
3192                            // component is no longer known.  Most likely an update
3193                            // to the app was installed and in the new version this
3194                            // component no longer exists.  Clean it up by removing
3195                            // it from the preferred activities list, and skip it.
3196                            Slog.w(TAG, "Removing dangling preferred activity: "
3197                                    + pa.mPref.mComponent);
3198                            pir.removeFilter(pa);
3199                            changed = true;
3200                            continue;
3201                        }
3202                        for (int j=0; j<N; j++) {
3203                            final ResolveInfo ri = query.get(j);
3204                            if (!ri.activityInfo.applicationInfo.packageName
3205                                    .equals(ai.applicationInfo.packageName)) {
3206                                continue;
3207                            }
3208                            if (!ri.activityInfo.name.equals(ai.name)) {
3209                                continue;
3210                            }
3211
3212                            if (removeMatches) {
3213                                pir.removeFilter(pa);
3214                                changed = true;
3215                                if (DEBUG_PREFERRED) {
3216                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3217                                }
3218                                break;
3219                            }
3220
3221                            // Okay we found a previously set preferred or last chosen app.
3222                            // If the result set is different from when this
3223                            // was created, we need to clear it and re-ask the
3224                            // user their preference, if we're looking for an "always" type entry.
3225                            if (always && !pa.mPref.sameSet(query, priority)) {
3226                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3227                                        + intent + " type " + resolvedType);
3228                                if (DEBUG_PREFERRED) {
3229                                    Slog.v(TAG, "Removing preferred activity since set changed "
3230                                            + pa.mPref.mComponent);
3231                                }
3232                                pir.removeFilter(pa);
3233                                // Re-add the filter as a "last chosen" entry (!always)
3234                                PreferredActivity lastChosen = new PreferredActivity(
3235                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3236                                pir.addFilter(lastChosen);
3237                                changed = true;
3238                                return null;
3239                            }
3240
3241                            // Yay! Either the set matched or we're looking for the last chosen
3242                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3243                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3244                            return ri;
3245                        }
3246                    }
3247                } finally {
3248                    if (changed) {
3249                        if (DEBUG_PREFERRED) {
3250                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3251                        }
3252                        mSettings.writePackageRestrictionsLPr(userId);
3253                    }
3254                }
3255            }
3256        }
3257        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3258        return null;
3259    }
3260
3261    /*
3262     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3263     */
3264    @Override
3265    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3266            int targetUserId) {
3267        mContext.enforceCallingOrSelfPermission(
3268                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3269        List<CrossProfileIntentFilter> matches =
3270                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3271        if (matches != null) {
3272            int size = matches.size();
3273            for (int i = 0; i < size; i++) {
3274                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3275            }
3276        }
3277        return false;
3278    }
3279
3280    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3281            String resolvedType, int userId) {
3282        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3283        if (resolver != null) {
3284            return resolver.queryIntent(intent, resolvedType, false, userId);
3285        }
3286        return null;
3287    }
3288
3289    @Override
3290    public List<ResolveInfo> queryIntentActivities(Intent intent,
3291            String resolvedType, int flags, int userId) {
3292        if (!sUserManager.exists(userId)) return Collections.emptyList();
3293        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3294        ComponentName comp = intent.getComponent();
3295        if (comp == null) {
3296            if (intent.getSelector() != null) {
3297                intent = intent.getSelector();
3298                comp = intent.getComponent();
3299            }
3300        }
3301
3302        if (comp != null) {
3303            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3304            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3305            if (ai != null) {
3306                final ResolveInfo ri = new ResolveInfo();
3307                ri.activityInfo = ai;
3308                list.add(ri);
3309            }
3310            return list;
3311        }
3312
3313        // reader
3314        synchronized (mPackages) {
3315            final String pkgName = intent.getPackage();
3316            if (pkgName == null) {
3317                List<CrossProfileIntentFilter> matchingFilters =
3318                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3319                // Check for results that need to skip the current profile.
3320                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3321                        resolvedType, flags, userId);
3322                if (resolveInfo != null) {
3323                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3324                    result.add(resolveInfo);
3325                    return result;
3326                }
3327                // Check for cross profile results.
3328                resolveInfo = queryCrossProfileIntents(
3329                        matchingFilters, intent, resolvedType, flags, userId);
3330
3331                // Check for results in the current profile.
3332                List<ResolveInfo> result = mActivities.queryIntent(
3333                        intent, resolvedType, flags, userId);
3334                if (resolveInfo != null) {
3335                    result.add(resolveInfo);
3336                    Collections.sort(result, mResolvePrioritySorter);
3337                }
3338                return result;
3339            }
3340            final PackageParser.Package pkg = mPackages.get(pkgName);
3341            if (pkg != null) {
3342                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3343                        pkg.activities, userId);
3344            }
3345            return new ArrayList<ResolveInfo>();
3346        }
3347    }
3348
3349    private ResolveInfo querySkipCurrentProfileIntents(
3350            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3351            int flags, int sourceUserId) {
3352        if (matchingFilters != null) {
3353            int size = matchingFilters.size();
3354            for (int i = 0; i < size; i ++) {
3355                CrossProfileIntentFilter filter = matchingFilters.get(i);
3356                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3357                    // Checking if there are activities in the target user that can handle the
3358                    // intent.
3359                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3360                            flags, sourceUserId);
3361                    if (resolveInfo != null) {
3362                        return resolveInfo;
3363                    }
3364                }
3365            }
3366        }
3367        return null;
3368    }
3369
3370    // Return matching ResolveInfo if any for skip current profile intent filters.
3371    private ResolveInfo queryCrossProfileIntents(
3372            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3373            int flags, int sourceUserId) {
3374        if (matchingFilters != null) {
3375            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3376            // match the same intent. For performance reasons, it is better not to
3377            // run queryIntent twice for the same userId
3378            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3379            int size = matchingFilters.size();
3380            for (int i = 0; i < size; i++) {
3381                CrossProfileIntentFilter filter = matchingFilters.get(i);
3382                int targetUserId = filter.getTargetUserId();
3383                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3384                        && !alreadyTriedUserIds.get(targetUserId)) {
3385                    // Checking if there are activities in the target user that can handle the
3386                    // intent.
3387                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3388                            flags, sourceUserId);
3389                    if (resolveInfo != null) return resolveInfo;
3390                    alreadyTriedUserIds.put(targetUserId, true);
3391                }
3392            }
3393        }
3394        return null;
3395    }
3396
3397    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3398            String resolvedType, int flags, int sourceUserId) {
3399        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3400                resolvedType, flags, filter.getTargetUserId());
3401        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3402            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3403        }
3404        return null;
3405    }
3406
3407    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3408            int sourceUserId, int targetUserId) {
3409        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3410        String className;
3411        if (targetUserId == UserHandle.USER_OWNER) {
3412            className = FORWARD_INTENT_TO_USER_OWNER;
3413        } else {
3414            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3415        }
3416        ComponentName forwardingActivityComponentName = new ComponentName(
3417                mAndroidApplication.packageName, className);
3418        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3419                sourceUserId);
3420        if (targetUserId == UserHandle.USER_OWNER) {
3421            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3422            forwardingResolveInfo.noResourceId = true;
3423        }
3424        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3425        forwardingResolveInfo.priority = 0;
3426        forwardingResolveInfo.preferredOrder = 0;
3427        forwardingResolveInfo.match = 0;
3428        forwardingResolveInfo.isDefault = true;
3429        forwardingResolveInfo.filter = filter;
3430        forwardingResolveInfo.targetUserId = targetUserId;
3431        return forwardingResolveInfo;
3432    }
3433
3434    @Override
3435    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3436            Intent[] specifics, String[] specificTypes, Intent intent,
3437            String resolvedType, int flags, int userId) {
3438        if (!sUserManager.exists(userId)) return Collections.emptyList();
3439        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3440                false, "query intent activity options");
3441        final String resultsAction = intent.getAction();
3442
3443        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3444                | PackageManager.GET_RESOLVED_FILTER, userId);
3445
3446        if (DEBUG_INTENT_MATCHING) {
3447            Log.v(TAG, "Query " + intent + ": " + results);
3448        }
3449
3450        int specificsPos = 0;
3451        int N;
3452
3453        // todo: note that the algorithm used here is O(N^2).  This
3454        // isn't a problem in our current environment, but if we start running
3455        // into situations where we have more than 5 or 10 matches then this
3456        // should probably be changed to something smarter...
3457
3458        // First we go through and resolve each of the specific items
3459        // that were supplied, taking care of removing any corresponding
3460        // duplicate items in the generic resolve list.
3461        if (specifics != null) {
3462            for (int i=0; i<specifics.length; i++) {
3463                final Intent sintent = specifics[i];
3464                if (sintent == null) {
3465                    continue;
3466                }
3467
3468                if (DEBUG_INTENT_MATCHING) {
3469                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3470                }
3471
3472                String action = sintent.getAction();
3473                if (resultsAction != null && resultsAction.equals(action)) {
3474                    // If this action was explicitly requested, then don't
3475                    // remove things that have it.
3476                    action = null;
3477                }
3478
3479                ResolveInfo ri = null;
3480                ActivityInfo ai = null;
3481
3482                ComponentName comp = sintent.getComponent();
3483                if (comp == null) {
3484                    ri = resolveIntent(
3485                        sintent,
3486                        specificTypes != null ? specificTypes[i] : null,
3487                            flags, userId);
3488                    if (ri == null) {
3489                        continue;
3490                    }
3491                    if (ri == mResolveInfo) {
3492                        // ACK!  Must do something better with this.
3493                    }
3494                    ai = ri.activityInfo;
3495                    comp = new ComponentName(ai.applicationInfo.packageName,
3496                            ai.name);
3497                } else {
3498                    ai = getActivityInfo(comp, flags, userId);
3499                    if (ai == null) {
3500                        continue;
3501                    }
3502                }
3503
3504                // Look for any generic query activities that are duplicates
3505                // of this specific one, and remove them from the results.
3506                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3507                N = results.size();
3508                int j;
3509                for (j=specificsPos; j<N; j++) {
3510                    ResolveInfo sri = results.get(j);
3511                    if ((sri.activityInfo.name.equals(comp.getClassName())
3512                            && sri.activityInfo.applicationInfo.packageName.equals(
3513                                    comp.getPackageName()))
3514                        || (action != null && sri.filter.matchAction(action))) {
3515                        results.remove(j);
3516                        if (DEBUG_INTENT_MATCHING) Log.v(
3517                            TAG, "Removing duplicate item from " + j
3518                            + " due to specific " + specificsPos);
3519                        if (ri == null) {
3520                            ri = sri;
3521                        }
3522                        j--;
3523                        N--;
3524                    }
3525                }
3526
3527                // Add this specific item to its proper place.
3528                if (ri == null) {
3529                    ri = new ResolveInfo();
3530                    ri.activityInfo = ai;
3531                }
3532                results.add(specificsPos, ri);
3533                ri.specificIndex = i;
3534                specificsPos++;
3535            }
3536        }
3537
3538        // Now we go through the remaining generic results and remove any
3539        // duplicate actions that are found here.
3540        N = results.size();
3541        for (int i=specificsPos; i<N-1; i++) {
3542            final ResolveInfo rii = results.get(i);
3543            if (rii.filter == null) {
3544                continue;
3545            }
3546
3547            // Iterate over all of the actions of this result's intent
3548            // filter...  typically this should be just one.
3549            final Iterator<String> it = rii.filter.actionsIterator();
3550            if (it == null) {
3551                continue;
3552            }
3553            while (it.hasNext()) {
3554                final String action = it.next();
3555                if (resultsAction != null && resultsAction.equals(action)) {
3556                    // If this action was explicitly requested, then don't
3557                    // remove things that have it.
3558                    continue;
3559                }
3560                for (int j=i+1; j<N; j++) {
3561                    final ResolveInfo rij = results.get(j);
3562                    if (rij.filter != null && rij.filter.hasAction(action)) {
3563                        results.remove(j);
3564                        if (DEBUG_INTENT_MATCHING) Log.v(
3565                            TAG, "Removing duplicate item from " + j
3566                            + " due to action " + action + " at " + i);
3567                        j--;
3568                        N--;
3569                    }
3570                }
3571            }
3572
3573            // If the caller didn't request filter information, drop it now
3574            // so we don't have to marshall/unmarshall it.
3575            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3576                rii.filter = null;
3577            }
3578        }
3579
3580        // Filter out the caller activity if so requested.
3581        if (caller != null) {
3582            N = results.size();
3583            for (int i=0; i<N; i++) {
3584                ActivityInfo ainfo = results.get(i).activityInfo;
3585                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3586                        && caller.getClassName().equals(ainfo.name)) {
3587                    results.remove(i);
3588                    break;
3589                }
3590            }
3591        }
3592
3593        // If the caller didn't request filter information,
3594        // drop them now so we don't have to
3595        // marshall/unmarshall it.
3596        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3597            N = results.size();
3598            for (int i=0; i<N; i++) {
3599                results.get(i).filter = null;
3600            }
3601        }
3602
3603        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3604        return results;
3605    }
3606
3607    @Override
3608    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3609            int userId) {
3610        if (!sUserManager.exists(userId)) return Collections.emptyList();
3611        ComponentName comp = intent.getComponent();
3612        if (comp == null) {
3613            if (intent.getSelector() != null) {
3614                intent = intent.getSelector();
3615                comp = intent.getComponent();
3616            }
3617        }
3618        if (comp != null) {
3619            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3620            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3621            if (ai != null) {
3622                ResolveInfo ri = new ResolveInfo();
3623                ri.activityInfo = ai;
3624                list.add(ri);
3625            }
3626            return list;
3627        }
3628
3629        // reader
3630        synchronized (mPackages) {
3631            String pkgName = intent.getPackage();
3632            if (pkgName == null) {
3633                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3634            }
3635            final PackageParser.Package pkg = mPackages.get(pkgName);
3636            if (pkg != null) {
3637                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3638                        userId);
3639            }
3640            return null;
3641        }
3642    }
3643
3644    @Override
3645    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3646        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3647        if (!sUserManager.exists(userId)) return null;
3648        if (query != null) {
3649            if (query.size() >= 1) {
3650                // If there is more than one service with the same priority,
3651                // just arbitrarily pick the first one.
3652                return query.get(0);
3653            }
3654        }
3655        return null;
3656    }
3657
3658    @Override
3659    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3660            int userId) {
3661        if (!sUserManager.exists(userId)) return Collections.emptyList();
3662        ComponentName comp = intent.getComponent();
3663        if (comp == null) {
3664            if (intent.getSelector() != null) {
3665                intent = intent.getSelector();
3666                comp = intent.getComponent();
3667            }
3668        }
3669        if (comp != null) {
3670            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3671            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3672            if (si != null) {
3673                final ResolveInfo ri = new ResolveInfo();
3674                ri.serviceInfo = si;
3675                list.add(ri);
3676            }
3677            return list;
3678        }
3679
3680        // reader
3681        synchronized (mPackages) {
3682            String pkgName = intent.getPackage();
3683            if (pkgName == null) {
3684                return mServices.queryIntent(intent, resolvedType, flags, userId);
3685            }
3686            final PackageParser.Package pkg = mPackages.get(pkgName);
3687            if (pkg != null) {
3688                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3689                        userId);
3690            }
3691            return null;
3692        }
3693    }
3694
3695    @Override
3696    public List<ResolveInfo> queryIntentContentProviders(
3697            Intent intent, String resolvedType, int flags, int userId) {
3698        if (!sUserManager.exists(userId)) return Collections.emptyList();
3699        ComponentName comp = intent.getComponent();
3700        if (comp == null) {
3701            if (intent.getSelector() != null) {
3702                intent = intent.getSelector();
3703                comp = intent.getComponent();
3704            }
3705        }
3706        if (comp != null) {
3707            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3708            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3709            if (pi != null) {
3710                final ResolveInfo ri = new ResolveInfo();
3711                ri.providerInfo = pi;
3712                list.add(ri);
3713            }
3714            return list;
3715        }
3716
3717        // reader
3718        synchronized (mPackages) {
3719            String pkgName = intent.getPackage();
3720            if (pkgName == null) {
3721                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3722            }
3723            final PackageParser.Package pkg = mPackages.get(pkgName);
3724            if (pkg != null) {
3725                return mProviders.queryIntentForPackage(
3726                        intent, resolvedType, flags, pkg.providers, userId);
3727            }
3728            return null;
3729        }
3730    }
3731
3732    @Override
3733    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3734        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3735
3736        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3737
3738        // writer
3739        synchronized (mPackages) {
3740            ArrayList<PackageInfo> list;
3741            if (listUninstalled) {
3742                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3743                for (PackageSetting ps : mSettings.mPackages.values()) {
3744                    PackageInfo pi;
3745                    if (ps.pkg != null) {
3746                        pi = generatePackageInfo(ps.pkg, flags, userId);
3747                    } else {
3748                        pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3749                    }
3750                    if (pi != null) {
3751                        list.add(pi);
3752                    }
3753                }
3754            } else {
3755                list = new ArrayList<PackageInfo>(mPackages.size());
3756                for (PackageParser.Package p : mPackages.values()) {
3757                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3758                    if (pi != null) {
3759                        list.add(pi);
3760                    }
3761                }
3762            }
3763
3764            return new ParceledListSlice<PackageInfo>(list);
3765        }
3766    }
3767
3768    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3769            String[] permissions, boolean[] tmp, int flags, int userId) {
3770        int numMatch = 0;
3771        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3772        for (int i=0; i<permissions.length; i++) {
3773            if (gp.grantedPermissions.contains(permissions[i])) {
3774                tmp[i] = true;
3775                numMatch++;
3776            } else {
3777                tmp[i] = false;
3778            }
3779        }
3780        if (numMatch == 0) {
3781            return;
3782        }
3783        PackageInfo pi;
3784        if (ps.pkg != null) {
3785            pi = generatePackageInfo(ps.pkg, flags, userId);
3786        } else {
3787            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3788        }
3789        // The above might return null in cases of uninstalled apps or install-state
3790        // skew across users/profiles.
3791        if (pi != null) {
3792            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3793                if (numMatch == permissions.length) {
3794                    pi.requestedPermissions = permissions;
3795                } else {
3796                    pi.requestedPermissions = new String[numMatch];
3797                    numMatch = 0;
3798                    for (int i=0; i<permissions.length; i++) {
3799                        if (tmp[i]) {
3800                            pi.requestedPermissions[numMatch] = permissions[i];
3801                            numMatch++;
3802                        }
3803                    }
3804                }
3805            }
3806            list.add(pi);
3807        }
3808    }
3809
3810    @Override
3811    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3812            String[] permissions, int flags, int userId) {
3813        if (!sUserManager.exists(userId)) return null;
3814        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3815
3816        // writer
3817        synchronized (mPackages) {
3818            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3819            boolean[] tmpBools = new boolean[permissions.length];
3820            if (listUninstalled) {
3821                for (PackageSetting ps : mSettings.mPackages.values()) {
3822                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3823                }
3824            } else {
3825                for (PackageParser.Package pkg : mPackages.values()) {
3826                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3827                    if (ps != null) {
3828                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3829                                userId);
3830                    }
3831                }
3832            }
3833
3834            return new ParceledListSlice<PackageInfo>(list);
3835        }
3836    }
3837
3838    @Override
3839    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3840        if (!sUserManager.exists(userId)) return null;
3841        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3842
3843        // writer
3844        synchronized (mPackages) {
3845            ArrayList<ApplicationInfo> list;
3846            if (listUninstalled) {
3847                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3848                for (PackageSetting ps : mSettings.mPackages.values()) {
3849                    ApplicationInfo ai;
3850                    if (ps.pkg != null) {
3851                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3852                                ps.readUserState(userId), userId);
3853                    } else {
3854                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3855                    }
3856                    if (ai != null) {
3857                        list.add(ai);
3858                    }
3859                }
3860            } else {
3861                list = new ArrayList<ApplicationInfo>(mPackages.size());
3862                for (PackageParser.Package p : mPackages.values()) {
3863                    if (p.mExtras != null) {
3864                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3865                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3866                        if (ai != null) {
3867                            list.add(ai);
3868                        }
3869                    }
3870                }
3871            }
3872
3873            return new ParceledListSlice<ApplicationInfo>(list);
3874        }
3875    }
3876
3877    public List<ApplicationInfo> getPersistentApplications(int flags) {
3878        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3879
3880        // reader
3881        synchronized (mPackages) {
3882            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3883            final int userId = UserHandle.getCallingUserId();
3884            while (i.hasNext()) {
3885                final PackageParser.Package p = i.next();
3886                if (p.applicationInfo != null
3887                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3888                        && (!mSafeMode || isSystemApp(p))) {
3889                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3890                    if (ps != null) {
3891                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3892                                ps.readUserState(userId), userId);
3893                        if (ai != null) {
3894                            finalList.add(ai);
3895                        }
3896                    }
3897                }
3898            }
3899        }
3900
3901        return finalList;
3902    }
3903
3904    @Override
3905    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3906        if (!sUserManager.exists(userId)) return null;
3907        // reader
3908        synchronized (mPackages) {
3909            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3910            PackageSetting ps = provider != null
3911                    ? mSettings.mPackages.get(provider.owner.packageName)
3912                    : null;
3913            return ps != null
3914                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3915                    && (!mSafeMode || (provider.info.applicationInfo.flags
3916                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3917                    ? PackageParser.generateProviderInfo(provider, flags,
3918                            ps.readUserState(userId), userId)
3919                    : null;
3920        }
3921    }
3922
3923    /**
3924     * @deprecated
3925     */
3926    @Deprecated
3927    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3928        // reader
3929        synchronized (mPackages) {
3930            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3931                    .entrySet().iterator();
3932            final int userId = UserHandle.getCallingUserId();
3933            while (i.hasNext()) {
3934                Map.Entry<String, PackageParser.Provider> entry = i.next();
3935                PackageParser.Provider p = entry.getValue();
3936                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3937
3938                if (ps != null && p.syncable
3939                        && (!mSafeMode || (p.info.applicationInfo.flags
3940                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3941                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3942                            ps.readUserState(userId), userId);
3943                    if (info != null) {
3944                        outNames.add(entry.getKey());
3945                        outInfo.add(info);
3946                    }
3947                }
3948            }
3949        }
3950    }
3951
3952    @Override
3953    public List<ProviderInfo> queryContentProviders(String processName,
3954            int uid, int flags) {
3955        ArrayList<ProviderInfo> finalList = null;
3956        // reader
3957        synchronized (mPackages) {
3958            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3959            final int userId = processName != null ?
3960                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
3961            while (i.hasNext()) {
3962                final PackageParser.Provider p = i.next();
3963                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3964                if (ps != null && p.info.authority != null
3965                        && (processName == null
3966                                || (p.info.processName.equals(processName)
3967                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
3968                        && mSettings.isEnabledLPr(p.info, flags, userId)
3969                        && (!mSafeMode
3970                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
3971                    if (finalList == null) {
3972                        finalList = new ArrayList<ProviderInfo>(3);
3973                    }
3974                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
3975                            ps.readUserState(userId), userId);
3976                    if (info != null) {
3977                        finalList.add(info);
3978                    }
3979                }
3980            }
3981        }
3982
3983        if (finalList != null) {
3984            Collections.sort(finalList, mProviderInitOrderSorter);
3985        }
3986
3987        return finalList;
3988    }
3989
3990    @Override
3991    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
3992            int flags) {
3993        // reader
3994        synchronized (mPackages) {
3995            final PackageParser.Instrumentation i = mInstrumentation.get(name);
3996            return PackageParser.generateInstrumentationInfo(i, flags);
3997        }
3998    }
3999
4000    @Override
4001    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4002            int flags) {
4003        ArrayList<InstrumentationInfo> finalList =
4004            new ArrayList<InstrumentationInfo>();
4005
4006        // reader
4007        synchronized (mPackages) {
4008            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4009            while (i.hasNext()) {
4010                final PackageParser.Instrumentation p = i.next();
4011                if (targetPackage == null
4012                        || targetPackage.equals(p.info.targetPackage)) {
4013                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4014                            flags);
4015                    if (ii != null) {
4016                        finalList.add(ii);
4017                    }
4018                }
4019            }
4020        }
4021
4022        return finalList;
4023    }
4024
4025    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4026        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4027        if (overlays == null) {
4028            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4029            return;
4030        }
4031        for (PackageParser.Package opkg : overlays.values()) {
4032            // Not much to do if idmap fails: we already logged the error
4033            // and we certainly don't want to abort installation of pkg simply
4034            // because an overlay didn't fit properly. For these reasons,
4035            // ignore the return value of createIdmapForPackagePairLI.
4036            createIdmapForPackagePairLI(pkg, opkg);
4037        }
4038    }
4039
4040    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4041            PackageParser.Package opkg) {
4042        if (!opkg.mTrustedOverlay) {
4043            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4044                    opkg.baseCodePath + ": overlay not trusted");
4045            return false;
4046        }
4047        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4048        if (overlaySet == null) {
4049            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4050                    opkg.baseCodePath + " but target package has no known overlays");
4051            return false;
4052        }
4053        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4054        // TODO: generate idmap for split APKs
4055        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4056            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4057                    + opkg.baseCodePath);
4058            return false;
4059        }
4060        PackageParser.Package[] overlayArray =
4061            overlaySet.values().toArray(new PackageParser.Package[0]);
4062        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4063            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4064                return p1.mOverlayPriority - p2.mOverlayPriority;
4065            }
4066        };
4067        Arrays.sort(overlayArray, cmp);
4068
4069        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4070        int i = 0;
4071        for (PackageParser.Package p : overlayArray) {
4072            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4073        }
4074        return true;
4075    }
4076
4077    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4078        final File[] files = dir.listFiles();
4079        if (ArrayUtils.isEmpty(files)) {
4080            Log.d(TAG, "No files in app dir " + dir);
4081            return;
4082        }
4083
4084        if (DEBUG_PACKAGE_SCANNING) {
4085            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4086                    + " flags=0x" + Integer.toHexString(parseFlags));
4087        }
4088
4089        for (File file : files) {
4090            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4091                    && !PackageInstallerService.isStageName(file.getName());
4092            if (!isPackage) {
4093                // Ignore entries which are not packages
4094                continue;
4095            }
4096            try {
4097                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4098                        scanFlags, currentTime, null);
4099            } catch (PackageManagerException e) {
4100                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4101
4102                // Delete invalid userdata apps
4103                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4104                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4105                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4106                    if (file.isDirectory()) {
4107                        FileUtils.deleteContents(file);
4108                    }
4109                    file.delete();
4110                }
4111            }
4112        }
4113    }
4114
4115    private static File getSettingsProblemFile() {
4116        File dataDir = Environment.getDataDirectory();
4117        File systemDir = new File(dataDir, "system");
4118        File fname = new File(systemDir, "uiderrors.txt");
4119        return fname;
4120    }
4121
4122    static void reportSettingsProblem(int priority, String msg) {
4123        logCriticalInfo(priority, msg);
4124    }
4125
4126    static void logCriticalInfo(int priority, String msg) {
4127        Slog.println(priority, TAG, msg);
4128        EventLogTags.writePmCriticalInfo(msg);
4129        try {
4130            File fname = getSettingsProblemFile();
4131            FileOutputStream out = new FileOutputStream(fname, true);
4132            PrintWriter pw = new FastPrintWriter(out);
4133            SimpleDateFormat formatter = new SimpleDateFormat();
4134            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4135            pw.println(dateString + ": " + msg);
4136            pw.close();
4137            FileUtils.setPermissions(
4138                    fname.toString(),
4139                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4140                    -1, -1);
4141        } catch (java.io.IOException e) {
4142        }
4143    }
4144
4145    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4146            PackageParser.Package pkg, File srcFile, int parseFlags)
4147            throws PackageManagerException {
4148        if (ps != null
4149                && ps.codePath.equals(srcFile)
4150                && ps.timeStamp == srcFile.lastModified()
4151                && !isCompatSignatureUpdateNeeded(pkg)) {
4152            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4153            if (ps.signatures.mSignatures != null
4154                    && ps.signatures.mSignatures.length != 0
4155                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4156                // Optimization: reuse the existing cached certificates
4157                // if the package appears to be unchanged.
4158                pkg.mSignatures = ps.signatures.mSignatures;
4159                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4160                synchronized (mPackages) {
4161                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4162                }
4163                return;
4164            }
4165
4166            Slog.w(TAG, "PackageSetting for " + ps.name
4167                    + " is missing signatures.  Collecting certs again to recover them.");
4168        } else {
4169            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4170        }
4171
4172        try {
4173            pp.collectCertificates(pkg, parseFlags);
4174            pp.collectManifestDigest(pkg);
4175        } catch (PackageParserException e) {
4176            throw PackageManagerException.from(e);
4177        }
4178    }
4179
4180    /*
4181     *  Scan a package and return the newly parsed package.
4182     *  Returns null in case of errors and the error code is stored in mLastScanError
4183     */
4184    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4185            long currentTime, UserHandle user) throws PackageManagerException {
4186        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4187        parseFlags |= mDefParseFlags;
4188        PackageParser pp = new PackageParser();
4189        pp.setSeparateProcesses(mSeparateProcesses);
4190        pp.setOnlyCoreApps(mOnlyCore);
4191        pp.setDisplayMetrics(mMetrics);
4192
4193        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4194            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4195        }
4196
4197        final PackageParser.Package pkg;
4198        try {
4199            pkg = pp.parsePackage(scanFile, parseFlags);
4200        } catch (PackageParserException e) {
4201            throw PackageManagerException.from(e);
4202        }
4203
4204        PackageSetting ps = null;
4205        PackageSetting updatedPkg;
4206        // reader
4207        synchronized (mPackages) {
4208            // Look to see if we already know about this package.
4209            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4210            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4211                // This package has been renamed to its original name.  Let's
4212                // use that.
4213                ps = mSettings.peekPackageLPr(oldName);
4214            }
4215            // If there was no original package, see one for the real package name.
4216            if (ps == null) {
4217                ps = mSettings.peekPackageLPr(pkg.packageName);
4218            }
4219            // Check to see if this package could be hiding/updating a system
4220            // package.  Must look for it either under the original or real
4221            // package name depending on our state.
4222            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4223            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4224        }
4225        boolean updatedPkgBetter = false;
4226        // First check if this is a system package that may involve an update
4227        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4228            if (ps != null && !ps.codePath.equals(scanFile)) {
4229                // The path has changed from what was last scanned...  check the
4230                // version of the new path against what we have stored to determine
4231                // what to do.
4232                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4233                if (pkg.mVersionCode < ps.versionCode) {
4234                    // The system package has been updated and the code path does not match
4235                    // Ignore entry. Skip it.
4236                    logCriticalInfo(Log.INFO, "Package " + ps.name + " at " + scanFile
4237                            + " ignored: updated version " + ps.versionCode
4238                            + " better than this " + pkg.mVersionCode);
4239                    if (!updatedPkg.codePath.equals(scanFile)) {
4240                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4241                                + ps.name + " changing from " + updatedPkg.codePathString
4242                                + " to " + scanFile);
4243                        updatedPkg.codePath = scanFile;
4244                        updatedPkg.codePathString = scanFile.toString();
4245                        // This is the point at which we know that the system-disk APK
4246                        // for this package has moved during a reboot (e.g. due to an OTA),
4247                        // so we need to reevaluate it for privilege policy.
4248                        if (locationIsPrivileged(scanFile)) {
4249                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4250                        }
4251                    }
4252                    updatedPkg.pkg = pkg;
4253                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4254                } else {
4255                    // The current app on the system partition is better than
4256                    // what we have updated to on the data partition; switch
4257                    // back to the system partition version.
4258                    // At this point, its safely assumed that package installation for
4259                    // apps in system partition will go through. If not there won't be a working
4260                    // version of the app
4261                    // writer
4262                    synchronized (mPackages) {
4263                        // Just remove the loaded entries from package lists.
4264                        mPackages.remove(ps.name);
4265                    }
4266
4267                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4268                            + " reverting from " + ps.codePathString
4269                            + ": new version " + pkg.mVersionCode
4270                            + " better than installed " + ps.versionCode);
4271
4272                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4273                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4274                            getAppDexInstructionSets(ps));
4275                    synchronized (mInstallLock) {
4276                        args.cleanUpResourcesLI();
4277                    }
4278                    synchronized (mPackages) {
4279                        mSettings.enableSystemPackageLPw(ps.name);
4280                    }
4281                    updatedPkgBetter = true;
4282                }
4283            }
4284        }
4285
4286        if (updatedPkg != null) {
4287            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4288            // initially
4289            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4290
4291            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4292            // flag set initially
4293            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4294                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4295            }
4296        }
4297
4298        // Verify certificates against what was last scanned
4299        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4300
4301        /*
4302         * A new system app appeared, but we already had a non-system one of the
4303         * same name installed earlier.
4304         */
4305        boolean shouldHideSystemApp = false;
4306        if (updatedPkg == null && ps != null
4307                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4308            /*
4309             * Check to make sure the signatures match first. If they don't,
4310             * wipe the installed application and its data.
4311             */
4312            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4313                    != PackageManager.SIGNATURE_MATCH) {
4314                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
4315                        + " signatures don't match existing userdata copy; removing");
4316                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4317                ps = null;
4318            } else {
4319                /*
4320                 * If the newly-added system app is an older version than the
4321                 * already installed version, hide it. It will be scanned later
4322                 * and re-added like an update.
4323                 */
4324                if (pkg.mVersionCode < ps.versionCode) {
4325                    shouldHideSystemApp = true;
4326                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
4327                            + " but new version " + pkg.mVersionCode + " better than installed "
4328                            + ps.versionCode + "; hiding system");
4329                } else {
4330                    /*
4331                     * The newly found system app is a newer version that the
4332                     * one previously installed. Simply remove the
4333                     * already-installed application and replace it with our own
4334                     * while keeping the application data.
4335                     */
4336                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4337                            + " reverting from " + ps.codePathString + ": new version "
4338                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
4339                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4340                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4341                            getAppDexInstructionSets(ps));
4342                    synchronized (mInstallLock) {
4343                        args.cleanUpResourcesLI();
4344                    }
4345                }
4346            }
4347        }
4348
4349        // The apk is forward locked (not public) if its code and resources
4350        // are kept in different files. (except for app in either system or
4351        // vendor path).
4352        // TODO grab this value from PackageSettings
4353        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4354            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4355                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4356            }
4357        }
4358
4359        // TODO: extend to support forward-locked splits
4360        String resourcePath = null;
4361        String baseResourcePath = null;
4362        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4363            if (ps != null && ps.resourcePathString != null) {
4364                resourcePath = ps.resourcePathString;
4365                baseResourcePath = ps.resourcePathString;
4366            } else {
4367                // Should not happen at all. Just log an error.
4368                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4369            }
4370        } else {
4371            resourcePath = pkg.codePath;
4372            baseResourcePath = pkg.baseCodePath;
4373        }
4374
4375        // Set application objects path explicitly.
4376        pkg.applicationInfo.setCodePath(pkg.codePath);
4377        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4378        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4379        pkg.applicationInfo.setResourcePath(resourcePath);
4380        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4381        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4382
4383        // Note that we invoke the following method only if we are about to unpack an application
4384        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4385                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4386
4387        /*
4388         * If the system app should be overridden by a previously installed
4389         * data, hide the system app now and let the /data/app scan pick it up
4390         * again.
4391         */
4392        if (shouldHideSystemApp) {
4393            synchronized (mPackages) {
4394                /*
4395                 * We have to grant systems permissions before we hide, because
4396                 * grantPermissions will assume the package update is trying to
4397                 * expand its permissions.
4398                 */
4399                grantPermissionsLPw(pkg, true, pkg.packageName);
4400                mSettings.disableSystemPackageLPw(pkg.packageName);
4401            }
4402        }
4403
4404        return scannedPkg;
4405    }
4406
4407    private static String fixProcessName(String defProcessName,
4408            String processName, int uid) {
4409        if (processName == null) {
4410            return defProcessName;
4411        }
4412        return processName;
4413    }
4414
4415    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4416            throws PackageManagerException {
4417        if (pkgSetting.signatures.mSignatures != null) {
4418            // Already existing package. Make sure signatures match
4419            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4420                    == PackageManager.SIGNATURE_MATCH;
4421            if (!match) {
4422                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4423                        == PackageManager.SIGNATURE_MATCH;
4424            }
4425            if (!match) {
4426                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4427                        + pkg.packageName + " signatures do not match the "
4428                        + "previously installed version; ignoring!");
4429            }
4430        }
4431
4432        // Check for shared user signatures
4433        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4434            // Already existing package. Make sure signatures match
4435            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4436                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4437            if (!match) {
4438                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4439                        == PackageManager.SIGNATURE_MATCH;
4440            }
4441            if (!match) {
4442                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4443                        "Package " + pkg.packageName
4444                        + " has no signatures that match those in shared user "
4445                        + pkgSetting.sharedUser.name + "; ignoring!");
4446            }
4447        }
4448    }
4449
4450    /**
4451     * Enforces that only the system UID or root's UID can call a method exposed
4452     * via Binder.
4453     *
4454     * @param message used as message if SecurityException is thrown
4455     * @throws SecurityException if the caller is not system or root
4456     */
4457    private static final void enforceSystemOrRoot(String message) {
4458        final int uid = Binder.getCallingUid();
4459        if (uid != Process.SYSTEM_UID && uid != 0) {
4460            throw new SecurityException(message);
4461        }
4462    }
4463
4464    @Override
4465    public void performBootDexOpt() {
4466        enforceSystemOrRoot("Only the system can request dexopt be performed");
4467
4468        final HashSet<PackageParser.Package> pkgs;
4469        synchronized (mPackages) {
4470            pkgs = mDeferredDexOpt;
4471            mDeferredDexOpt = null;
4472        }
4473
4474        if (pkgs != null) {
4475            // Sort apps by importance for dexopt ordering. Important apps are given more priority
4476            // in case the device runs out of space.
4477            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
4478            // Give priority to core apps.
4479            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4480                PackageParser.Package pkg = it.next();
4481                if (pkg.coreApp) {
4482                    if (DEBUG_DEXOPT) {
4483                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
4484                    }
4485                    sortedPkgs.add(pkg);
4486                    it.remove();
4487                }
4488            }
4489            // Give priority to system apps that listen for pre boot complete.
4490            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
4491            HashSet<String> pkgNames = getPackageNamesForIntent(intent);
4492            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4493                PackageParser.Package pkg = it.next();
4494                if (pkgNames.contains(pkg.packageName)) {
4495                    if (DEBUG_DEXOPT) {
4496                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
4497                    }
4498                    sortedPkgs.add(pkg);
4499                    it.remove();
4500                }
4501            }
4502            // Give priority to system apps.
4503            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4504                PackageParser.Package pkg = it.next();
4505                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4506                    if (DEBUG_DEXOPT) {
4507                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
4508                    }
4509                    sortedPkgs.add(pkg);
4510                    it.remove();
4511                }
4512            }
4513            // Give priority to updated system apps.
4514            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4515                PackageParser.Package pkg = it.next();
4516                if (isUpdatedSystemApp(pkg)) {
4517                    if (DEBUG_DEXOPT) {
4518                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
4519                    }
4520                    sortedPkgs.add(pkg);
4521                    it.remove();
4522                }
4523            }
4524            // Give priority to apps that listen for boot complete.
4525            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
4526            pkgNames = getPackageNamesForIntent(intent);
4527            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4528                PackageParser.Package pkg = it.next();
4529                if (pkgNames.contains(pkg.packageName)) {
4530                    if (DEBUG_DEXOPT) {
4531                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
4532                    }
4533                    sortedPkgs.add(pkg);
4534                    it.remove();
4535                }
4536            }
4537            // Filter out packages that aren't recently used.
4538            filterRecentlyUsedApps(pkgs);
4539            // Add all remaining apps.
4540            for (PackageParser.Package pkg : pkgs) {
4541                sortedPkgs.add(pkg);
4542            }
4543
4544            int i = 0;
4545            int total = sortedPkgs.size();
4546            for (PackageParser.Package pkg : sortedPkgs) {
4547                if (DEBUG_DEXOPT) {
4548                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
4549                }
4550                performBootDexOpt(pkg, ++i, total);
4551            }
4552        }
4553    }
4554
4555    private void filterRecentlyUsedApps(HashSet<PackageParser.Package> pkgs) {
4556        // Filter out packages that aren't recently used.
4557        //
4558        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4559        // should do a full dexopt.
4560        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4561            // TODO: add a property to control this?
4562            long dexOptLRUThresholdInMinutes;
4563            if (mLazyDexOpt) {
4564                dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4565            } else {
4566                dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4567            }
4568            long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4569
4570            int total = pkgs.size();
4571            int skipped = 0;
4572            long now = System.currentTimeMillis();
4573            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4574                PackageParser.Package pkg = i.next();
4575                long then = pkg.mLastPackageUsageTimeInMills;
4576                if (then + dexOptLRUThresholdInMills < now) {
4577                    if (DEBUG_DEXOPT) {
4578                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4579                              ((then == 0) ? "never" : new Date(then)));
4580                    }
4581                    i.remove();
4582                    skipped++;
4583                }
4584            }
4585            if (DEBUG_DEXOPT) {
4586                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4587            }
4588        }
4589    }
4590
4591    private HashSet<String> getPackageNamesForIntent(Intent intent) {
4592        List<ResolveInfo> ris = null;
4593        try {
4594            ris = AppGlobals.getPackageManager().queryIntentReceivers(
4595                    intent, null, 0, UserHandle.USER_OWNER);
4596        } catch (RemoteException e) {
4597        }
4598        HashSet<String> pkgNames = new HashSet<String>();
4599        if (ris != null) {
4600            for (ResolveInfo ri : ris) {
4601                pkgNames.add(ri.activityInfo.packageName);
4602            }
4603        }
4604        return pkgNames;
4605    }
4606
4607    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
4608        if (DEBUG_DEXOPT) {
4609            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
4610        }
4611        if (!isFirstBoot()) {
4612            try {
4613                ActivityManagerNative.getDefault().showBootMessage(
4614                        mContext.getResources().getString(R.string.android_upgrading_apk,
4615                                curr, total), true);
4616            } catch (RemoteException e) {
4617            }
4618        }
4619        PackageParser.Package p = pkg;
4620        synchronized (mInstallLock) {
4621            performDexOptLI(p, null /* instruction sets */, false /* force dex */,
4622                            false /* defer */, true /* include dependencies */);
4623        }
4624    }
4625
4626    @Override
4627    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4628        return performDexOpt(packageName, instructionSet, false);
4629    }
4630
4631    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4632        if (info.primaryCpuAbi == null) {
4633            return getPreferredInstructionSet();
4634        }
4635
4636        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4637    }
4638
4639    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4640        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4641        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4642        if (!dexopt && !updateUsage) {
4643            // We aren't going to dexopt or update usage, so bail early.
4644            return false;
4645        }
4646        PackageParser.Package p;
4647        final String targetInstructionSet;
4648        synchronized (mPackages) {
4649            p = mPackages.get(packageName);
4650            if (p == null) {
4651                return false;
4652            }
4653            if (updateUsage) {
4654                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4655            }
4656            mPackageUsage.write(false);
4657            if (!dexopt) {
4658                // We aren't going to dexopt, so bail early.
4659                return false;
4660            }
4661
4662            targetInstructionSet = instructionSet != null ? instructionSet :
4663                    getPrimaryInstructionSet(p.applicationInfo);
4664            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4665                return false;
4666            }
4667        }
4668
4669        synchronized (mInstallLock) {
4670            final String[] instructionSets = new String[] { targetInstructionSet };
4671            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4672                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4673        }
4674    }
4675
4676    public HashSet<String> getPackagesThatNeedDexOpt() {
4677        HashSet<String> pkgs = null;
4678        synchronized (mPackages) {
4679            for (PackageParser.Package p : mPackages.values()) {
4680                if (DEBUG_DEXOPT) {
4681                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4682                }
4683                if (!p.mDexOptPerformed.isEmpty()) {
4684                    continue;
4685                }
4686                if (pkgs == null) {
4687                    pkgs = new HashSet<String>();
4688                }
4689                pkgs.add(p.packageName);
4690            }
4691        }
4692        return pkgs;
4693    }
4694
4695    public void shutdown() {
4696        mPackageUsage.write(true);
4697    }
4698
4699    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4700             boolean forceDex, boolean defer, HashSet<String> done) {
4701        for (int i=0; i<libs.size(); i++) {
4702            PackageParser.Package libPkg;
4703            String libName;
4704            synchronized (mPackages) {
4705                libName = libs.get(i);
4706                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4707                if (lib != null && lib.apk != null) {
4708                    libPkg = mPackages.get(lib.apk);
4709                } else {
4710                    libPkg = null;
4711                }
4712            }
4713            if (libPkg != null && !done.contains(libName)) {
4714                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4715            }
4716        }
4717    }
4718
4719    static final int DEX_OPT_SKIPPED = 0;
4720    static final int DEX_OPT_PERFORMED = 1;
4721    static final int DEX_OPT_DEFERRED = 2;
4722    static final int DEX_OPT_FAILED = -1;
4723
4724    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4725            boolean forceDex, boolean defer, HashSet<String> done) {
4726        final String[] instructionSets = targetInstructionSets != null ?
4727                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4728
4729        if (done != null) {
4730            done.add(pkg.packageName);
4731            if (pkg.usesLibraries != null) {
4732                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4733            }
4734            if (pkg.usesOptionalLibraries != null) {
4735                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4736            }
4737        }
4738
4739        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4740            return DEX_OPT_SKIPPED;
4741        }
4742
4743        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4744
4745        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4746        boolean performedDexOpt = false;
4747        // There are three basic cases here:
4748        // 1.) we need to dexopt, either because we are forced or it is needed
4749        // 2.) we are defering a needed dexopt
4750        // 3.) we are skipping an unneeded dexopt
4751        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4752        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4753            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4754                continue;
4755            }
4756
4757            for (String path : paths) {
4758                try {
4759                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4760                    // patckage or the one we find does not match the image checksum (i.e. it was
4761                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4762                    // odex file and it matches the checksum of the image but not its base address,
4763                    // meaning we need to move it.
4764                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4765                            pkg.packageName, dexCodeInstructionSet, defer);
4766                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4767                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4768                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4769                                + " vmSafeMode=" + vmSafeMode);
4770                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4771                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4772                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4773
4774                        if (ret < 0) {
4775                            // Don't bother running dexopt again if we failed, it will probably
4776                            // just result in an error again. Also, don't bother dexopting for other
4777                            // paths & ISAs.
4778                            return DEX_OPT_FAILED;
4779                        }
4780
4781                        performedDexOpt = true;
4782                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4783                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4784                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4785                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4786                                pkg.packageName, dexCodeInstructionSet);
4787
4788                        if (ret < 0) {
4789                            // Don't bother running patchoat again if we failed, it will probably
4790                            // just result in an error again. Also, don't bother dexopting for other
4791                            // paths & ISAs.
4792                            return DEX_OPT_FAILED;
4793                        }
4794
4795                        performedDexOpt = true;
4796                    }
4797
4798                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4799                    // paths and instruction sets. We'll deal with them all together when we process
4800                    // our list of deferred dexopts.
4801                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4802                        if (mDeferredDexOpt == null) {
4803                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4804                        }
4805                        mDeferredDexOpt.add(pkg);
4806                        return DEX_OPT_DEFERRED;
4807                    }
4808                } catch (FileNotFoundException e) {
4809                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4810                    return DEX_OPT_FAILED;
4811                } catch (IOException e) {
4812                    Slog.w(TAG, "IOException reading apk: " + path, e);
4813                    return DEX_OPT_FAILED;
4814                } catch (StaleDexCacheError e) {
4815                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4816                    return DEX_OPT_FAILED;
4817                } catch (Exception e) {
4818                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4819                    return DEX_OPT_FAILED;
4820                }
4821            }
4822
4823            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4824            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4825            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4826            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4827            // it.
4828            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4829        }
4830
4831        // If we've gotten here, we're sure that no error occurred and that we haven't
4832        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4833        // we've skipped all of them because they are up to date. In both cases this
4834        // package doesn't need dexopt any longer.
4835        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4836    }
4837
4838    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4839        if (info.primaryCpuAbi != null) {
4840            if (info.secondaryCpuAbi != null) {
4841                return new String[] {
4842                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4843                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4844            } else {
4845                return new String[] {
4846                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4847            }
4848        }
4849
4850        return new String[] { getPreferredInstructionSet() };
4851    }
4852
4853    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4854        if (ps.primaryCpuAbiString != null) {
4855            if (ps.secondaryCpuAbiString != null) {
4856                return new String[] {
4857                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4858                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4859            } else {
4860                return new String[] {
4861                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4862            }
4863        }
4864
4865        return new String[] { getPreferredInstructionSet() };
4866    }
4867
4868    private static String getPreferredInstructionSet() {
4869        if (sPreferredInstructionSet == null) {
4870            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4871        }
4872
4873        return sPreferredInstructionSet;
4874    }
4875
4876    private static List<String> getAllInstructionSets() {
4877        final String[] allAbis = Build.SUPPORTED_ABIS;
4878        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4879
4880        for (String abi : allAbis) {
4881            final String instructionSet = VMRuntime.getInstructionSet(abi);
4882            if (!allInstructionSets.contains(instructionSet)) {
4883                allInstructionSets.add(instructionSet);
4884            }
4885        }
4886
4887        return allInstructionSets;
4888    }
4889
4890    /**
4891     * Returns the instruction set that should be used to compile dex code. In the presence of
4892     * a native bridge this might be different than the one shared libraries use.
4893     */
4894    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4895        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4896        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4897    }
4898
4899    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4900        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4901        for (String instructionSet : instructionSets) {
4902            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4903        }
4904        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4905    }
4906
4907    /**
4908     * Returns deduplicated list of supported instructions for dex code.
4909     */
4910    public static String[] getAllDexCodeInstructionSets() {
4911        String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length];
4912        for (int i = 0; i < supportedInstructionSets.length; i++) {
4913            String abi = Build.SUPPORTED_ABIS[i];
4914            supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi);
4915        }
4916        return getDexCodeInstructionSets(supportedInstructionSets);
4917    }
4918
4919    @Override
4920    public void forceDexOpt(String packageName) {
4921        enforceSystemOrRoot("forceDexOpt");
4922
4923        PackageParser.Package pkg;
4924        synchronized (mPackages) {
4925            pkg = mPackages.get(packageName);
4926            if (pkg == null) {
4927                throw new IllegalArgumentException("Missing package: " + packageName);
4928            }
4929        }
4930
4931        synchronized (mInstallLock) {
4932            final String[] instructionSets = new String[] {
4933                    getPrimaryInstructionSet(pkg.applicationInfo) };
4934            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4935            if (res != DEX_OPT_PERFORMED) {
4936                throw new IllegalStateException("Failed to dexopt: " + res);
4937            }
4938        }
4939    }
4940
4941    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
4942                                boolean forceDex, boolean defer, boolean inclDependencies) {
4943        HashSet<String> done;
4944        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
4945            done = new HashSet<String>();
4946            done.add(pkg.packageName);
4947        } else {
4948            done = null;
4949        }
4950        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
4951    }
4952
4953    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
4954        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
4955            Slog.w(TAG, "Unable to update from " + oldPkg.name
4956                    + " to " + newPkg.packageName
4957                    + ": old package not in system partition");
4958            return false;
4959        } else if (mPackages.get(oldPkg.name) != null) {
4960            Slog.w(TAG, "Unable to update from " + oldPkg.name
4961                    + " to " + newPkg.packageName
4962                    + ": old package still exists");
4963            return false;
4964        }
4965        return true;
4966    }
4967
4968    File getDataPathForUser(int userId) {
4969        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
4970    }
4971
4972    private File getDataPathForPackage(String packageName, int userId) {
4973        /*
4974         * Until we fully support multiple users, return the directory we
4975         * previously would have. The PackageManagerTests will need to be
4976         * revised when this is changed back..
4977         */
4978        if (userId == 0) {
4979            return new File(mAppDataDir, packageName);
4980        } else {
4981            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
4982                + File.separator + packageName);
4983        }
4984    }
4985
4986    private int createDataDirsLI(String packageName, int uid, String seinfo) {
4987        int[] users = sUserManager.getUserIds();
4988        int res = mInstaller.install(packageName, uid, uid, seinfo);
4989        if (res < 0) {
4990            return res;
4991        }
4992        for (int user : users) {
4993            if (user != 0) {
4994                res = mInstaller.createUserData(packageName,
4995                        UserHandle.getUid(user, uid), user, seinfo);
4996                if (res < 0) {
4997                    return res;
4998                }
4999            }
5000        }
5001        return res;
5002    }
5003
5004    private int removeDataDirsLI(String packageName) {
5005        int[] users = sUserManager.getUserIds();
5006        int res = 0;
5007        for (int user : users) {
5008            int resInner = mInstaller.remove(packageName, user);
5009            if (resInner < 0) {
5010                res = resInner;
5011            }
5012        }
5013
5014        return res;
5015    }
5016
5017    private int deleteCodeCacheDirsLI(String packageName) {
5018        int[] users = sUserManager.getUserIds();
5019        int res = 0;
5020        for (int user : users) {
5021            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
5022            if (resInner < 0) {
5023                res = resInner;
5024            }
5025        }
5026        return res;
5027    }
5028
5029    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5030            PackageParser.Package changingLib) {
5031        if (file.path != null) {
5032            usesLibraryFiles.add(file.path);
5033            return;
5034        }
5035        PackageParser.Package p = mPackages.get(file.apk);
5036        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5037            // If we are doing this while in the middle of updating a library apk,
5038            // then we need to make sure to use that new apk for determining the
5039            // dependencies here.  (We haven't yet finished committing the new apk
5040            // to the package manager state.)
5041            if (p == null || p.packageName.equals(changingLib.packageName)) {
5042                p = changingLib;
5043            }
5044        }
5045        if (p != null) {
5046            usesLibraryFiles.addAll(p.getAllCodePaths());
5047        }
5048    }
5049
5050    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5051            PackageParser.Package changingLib) throws PackageManagerException {
5052        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5053            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5054            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5055            for (int i=0; i<N; i++) {
5056                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5057                if (file == null) {
5058                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5059                            "Package " + pkg.packageName + " requires unavailable shared library "
5060                            + pkg.usesLibraries.get(i) + "; failing!");
5061                }
5062                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5063            }
5064            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5065            for (int i=0; i<N; i++) {
5066                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5067                if (file == null) {
5068                    Slog.w(TAG, "Package " + pkg.packageName
5069                            + " desires unavailable shared library "
5070                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5071                } else {
5072                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5073                }
5074            }
5075            N = usesLibraryFiles.size();
5076            if (N > 0) {
5077                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5078            } else {
5079                pkg.usesLibraryFiles = null;
5080            }
5081        }
5082    }
5083
5084    private static boolean hasString(List<String> list, List<String> which) {
5085        if (list == null) {
5086            return false;
5087        }
5088        for (int i=list.size()-1; i>=0; i--) {
5089            for (int j=which.size()-1; j>=0; j--) {
5090                if (which.get(j).equals(list.get(i))) {
5091                    return true;
5092                }
5093            }
5094        }
5095        return false;
5096    }
5097
5098    private void updateAllSharedLibrariesLPw() {
5099        for (PackageParser.Package pkg : mPackages.values()) {
5100            try {
5101                updateSharedLibrariesLPw(pkg, null);
5102            } catch (PackageManagerException e) {
5103                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5104            }
5105        }
5106    }
5107
5108    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5109            PackageParser.Package changingPkg) {
5110        ArrayList<PackageParser.Package> res = null;
5111        for (PackageParser.Package pkg : mPackages.values()) {
5112            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5113                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5114                if (res == null) {
5115                    res = new ArrayList<PackageParser.Package>();
5116                }
5117                res.add(pkg);
5118                try {
5119                    updateSharedLibrariesLPw(pkg, changingPkg);
5120                } catch (PackageManagerException e) {
5121                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5122                }
5123            }
5124        }
5125        return res;
5126    }
5127
5128    /**
5129     * Derive the value of the {@code cpuAbiOverride} based on the provided
5130     * value and an optional stored value from the package settings.
5131     */
5132    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5133        String cpuAbiOverride = null;
5134
5135        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5136            cpuAbiOverride = null;
5137        } else if (abiOverride != null) {
5138            cpuAbiOverride = abiOverride;
5139        } else if (settings != null) {
5140            cpuAbiOverride = settings.cpuAbiOverrideString;
5141        }
5142
5143        return cpuAbiOverride;
5144    }
5145
5146    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5147            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5148        boolean success = false;
5149        try {
5150            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5151                    currentTime, user);
5152            success = true;
5153            return res;
5154        } finally {
5155            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5156                removeDataDirsLI(pkg.packageName);
5157            }
5158        }
5159    }
5160
5161    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5162            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5163        final File scanFile = new File(pkg.codePath);
5164        if (pkg.applicationInfo.getCodePath() == null ||
5165                pkg.applicationInfo.getResourcePath() == null) {
5166            // Bail out. The resource and code paths haven't been set.
5167            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5168                    "Code and resource paths haven't been set correctly");
5169        }
5170
5171        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5172            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5173        } else {
5174            // Only allow system apps to be flagged as core apps.
5175            pkg.coreApp = false;
5176        }
5177
5178        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5179            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5180        }
5181
5182        if (mCustomResolverComponentName != null &&
5183                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5184            setUpCustomResolverActivity(pkg);
5185        }
5186
5187        if (pkg.packageName.equals("android")) {
5188            synchronized (mPackages) {
5189                if (mAndroidApplication != null) {
5190                    Slog.w(TAG, "*************************************************");
5191                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5192                    Slog.w(TAG, " file=" + scanFile);
5193                    Slog.w(TAG, "*************************************************");
5194                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5195                            "Core android package being redefined.  Skipping.");
5196                }
5197
5198                // Set up information for our fall-back user intent resolution activity.
5199                mPlatformPackage = pkg;
5200                pkg.mVersionCode = mSdkVersion;
5201                mAndroidApplication = pkg.applicationInfo;
5202
5203                if (!mResolverReplaced) {
5204                    mResolveActivity.applicationInfo = mAndroidApplication;
5205                    mResolveActivity.name = ResolverActivity.class.getName();
5206                    mResolveActivity.packageName = mAndroidApplication.packageName;
5207                    mResolveActivity.processName = "system:ui";
5208                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5209                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5210                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5211                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5212                    mResolveActivity.exported = true;
5213                    mResolveActivity.enabled = true;
5214                    mResolveInfo.activityInfo = mResolveActivity;
5215                    mResolveInfo.priority = 0;
5216                    mResolveInfo.preferredOrder = 0;
5217                    mResolveInfo.match = 0;
5218                    mResolveComponentName = new ComponentName(
5219                            mAndroidApplication.packageName, mResolveActivity.name);
5220                }
5221            }
5222        }
5223
5224        if (DEBUG_PACKAGE_SCANNING) {
5225            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5226                Log.d(TAG, "Scanning package " + pkg.packageName);
5227        }
5228
5229        if (mPackages.containsKey(pkg.packageName)
5230                || mSharedLibraries.containsKey(pkg.packageName)) {
5231            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5232                    "Application package " + pkg.packageName
5233                    + " already installed.  Skipping duplicate.");
5234        }
5235
5236        // Initialize package source and resource directories
5237        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5238        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5239
5240        SharedUserSetting suid = null;
5241        PackageSetting pkgSetting = null;
5242
5243        if (!isSystemApp(pkg)) {
5244            // Only system apps can use these features.
5245            pkg.mOriginalPackages = null;
5246            pkg.mRealPackage = null;
5247            pkg.mAdoptPermissions = null;
5248        }
5249
5250        // writer
5251        synchronized (mPackages) {
5252            if (pkg.mSharedUserId != null) {
5253                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5254                if (suid == null) {
5255                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5256                            "Creating application package " + pkg.packageName
5257                            + " for shared user failed");
5258                }
5259                if (DEBUG_PACKAGE_SCANNING) {
5260                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5261                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5262                                + "): packages=" + suid.packages);
5263                }
5264            }
5265
5266            // Check if we are renaming from an original package name.
5267            PackageSetting origPackage = null;
5268            String realName = null;
5269            if (pkg.mOriginalPackages != null) {
5270                // This package may need to be renamed to a previously
5271                // installed name.  Let's check on that...
5272                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5273                if (pkg.mOriginalPackages.contains(renamed)) {
5274                    // This package had originally been installed as the
5275                    // original name, and we have already taken care of
5276                    // transitioning to the new one.  Just update the new
5277                    // one to continue using the old name.
5278                    realName = pkg.mRealPackage;
5279                    if (!pkg.packageName.equals(renamed)) {
5280                        // Callers into this function may have already taken
5281                        // care of renaming the package; only do it here if
5282                        // it is not already done.
5283                        pkg.setPackageName(renamed);
5284                    }
5285
5286                } else {
5287                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5288                        if ((origPackage = mSettings.peekPackageLPr(
5289                                pkg.mOriginalPackages.get(i))) != null) {
5290                            // We do have the package already installed under its
5291                            // original name...  should we use it?
5292                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5293                                // New package is not compatible with original.
5294                                origPackage = null;
5295                                continue;
5296                            } else if (origPackage.sharedUser != null) {
5297                                // Make sure uid is compatible between packages.
5298                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5299                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5300                                            + " to " + pkg.packageName + ": old uid "
5301                                            + origPackage.sharedUser.name
5302                                            + " differs from " + pkg.mSharedUserId);
5303                                    origPackage = null;
5304                                    continue;
5305                                }
5306                            } else {
5307                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5308                                        + pkg.packageName + " to old name " + origPackage.name);
5309                            }
5310                            break;
5311                        }
5312                    }
5313                }
5314            }
5315
5316            if (mTransferedPackages.contains(pkg.packageName)) {
5317                Slog.w(TAG, "Package " + pkg.packageName
5318                        + " was transferred to another, but its .apk remains");
5319            }
5320
5321            // Just create the setting, don't add it yet. For already existing packages
5322            // the PkgSetting exists already and doesn't have to be created.
5323            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5324                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5325                    pkg.applicationInfo.primaryCpuAbi,
5326                    pkg.applicationInfo.secondaryCpuAbi,
5327                    pkg.applicationInfo.flags, user, false);
5328            if (pkgSetting == null) {
5329                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5330                        "Creating application package " + pkg.packageName + " failed");
5331            }
5332
5333            if (pkgSetting.origPackage != null) {
5334                // If we are first transitioning from an original package,
5335                // fix up the new package's name now.  We need to do this after
5336                // looking up the package under its new name, so getPackageLP
5337                // can take care of fiddling things correctly.
5338                pkg.setPackageName(origPackage.name);
5339
5340                // File a report about this.
5341                String msg = "New package " + pkgSetting.realName
5342                        + " renamed to replace old package " + pkgSetting.name;
5343                reportSettingsProblem(Log.WARN, msg);
5344
5345                // Make a note of it.
5346                mTransferedPackages.add(origPackage.name);
5347
5348                // No longer need to retain this.
5349                pkgSetting.origPackage = null;
5350            }
5351
5352            if (realName != null) {
5353                // Make a note of it.
5354                mTransferedPackages.add(pkg.packageName);
5355            }
5356
5357            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5358                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5359            }
5360
5361            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5362                // Check all shared libraries and map to their actual file path.
5363                // We only do this here for apps not on a system dir, because those
5364                // are the only ones that can fail an install due to this.  We
5365                // will take care of the system apps by updating all of their
5366                // library paths after the scan is done.
5367                updateSharedLibrariesLPw(pkg, null);
5368            }
5369
5370            if (mFoundPolicyFile) {
5371                SELinuxMMAC.assignSeinfoValue(pkg);
5372            }
5373
5374            pkg.applicationInfo.uid = pkgSetting.appId;
5375            pkg.mExtras = pkgSetting;
5376            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5377                try {
5378                    verifySignaturesLP(pkgSetting, pkg);
5379                } catch (PackageManagerException e) {
5380                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5381                        throw e;
5382                    }
5383                    // The signature has changed, but this package is in the system
5384                    // image...  let's recover!
5385                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5386                    // However...  if this package is part of a shared user, but it
5387                    // doesn't match the signature of the shared user, let's fail.
5388                    // What this means is that you can't change the signatures
5389                    // associated with an overall shared user, which doesn't seem all
5390                    // that unreasonable.
5391                    if (pkgSetting.sharedUser != null) {
5392                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5393                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5394                            throw new PackageManagerException(
5395                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5396                                            "Signature mismatch for shared user : "
5397                                            + pkgSetting.sharedUser);
5398                        }
5399                    }
5400                    // File a report about this.
5401                    String msg = "System package " + pkg.packageName
5402                        + " signature changed; retaining data.";
5403                    reportSettingsProblem(Log.WARN, msg);
5404                }
5405            } else {
5406                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5407                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5408                            + pkg.packageName + " upgrade keys do not match the "
5409                            + "previously installed version");
5410                } else {
5411                    // signatures may have changed as result of upgrade
5412                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5413                }
5414            }
5415            // Verify that this new package doesn't have any content providers
5416            // that conflict with existing packages.  Only do this if the
5417            // package isn't already installed, since we don't want to break
5418            // things that are installed.
5419            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5420                final int N = pkg.providers.size();
5421                int i;
5422                for (i=0; i<N; i++) {
5423                    PackageParser.Provider p = pkg.providers.get(i);
5424                    if (p.info.authority != null) {
5425                        String names[] = p.info.authority.split(";");
5426                        for (int j = 0; j < names.length; j++) {
5427                            if (mProvidersByAuthority.containsKey(names[j])) {
5428                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5429                                final String otherPackageName =
5430                                        ((other != null && other.getComponentName() != null) ?
5431                                                other.getComponentName().getPackageName() : "?");
5432                                throw new PackageManagerException(
5433                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5434                                                "Can't install because provider name " + names[j]
5435                                                + " (in package " + pkg.applicationInfo.packageName
5436                                                + ") is already used by " + otherPackageName);
5437                            }
5438                        }
5439                    }
5440                }
5441            }
5442
5443            if (pkg.mAdoptPermissions != null) {
5444                // This package wants to adopt ownership of permissions from
5445                // another package.
5446                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5447                    final String origName = pkg.mAdoptPermissions.get(i);
5448                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5449                    if (orig != null) {
5450                        if (verifyPackageUpdateLPr(orig, pkg)) {
5451                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5452                                    + pkg.packageName);
5453                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5454                        }
5455                    }
5456                }
5457            }
5458        }
5459
5460        final String pkgName = pkg.packageName;
5461
5462        final long scanFileTime = scanFile.lastModified();
5463        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5464        pkg.applicationInfo.processName = fixProcessName(
5465                pkg.applicationInfo.packageName,
5466                pkg.applicationInfo.processName,
5467                pkg.applicationInfo.uid);
5468
5469        File dataPath;
5470        if (mPlatformPackage == pkg) {
5471            // The system package is special.
5472            dataPath = new File(Environment.getDataDirectory(), "system");
5473
5474            pkg.applicationInfo.dataDir = dataPath.getPath();
5475
5476        } else {
5477            // This is a normal package, need to make its data directory.
5478            dataPath = getDataPathForPackage(pkg.packageName, 0);
5479
5480            boolean uidError = false;
5481            if (dataPath.exists()) {
5482                int currentUid = 0;
5483                try {
5484                    StructStat stat = Os.stat(dataPath.getPath());
5485                    currentUid = stat.st_uid;
5486                } catch (ErrnoException e) {
5487                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5488                }
5489
5490                // If we have mismatched owners for the data path, we have a problem.
5491                if (currentUid != pkg.applicationInfo.uid) {
5492                    boolean recovered = false;
5493                    if (currentUid == 0) {
5494                        // The directory somehow became owned by root.  Wow.
5495                        // This is probably because the system was stopped while
5496                        // installd was in the middle of messing with its libs
5497                        // directory.  Ask installd to fix that.
5498                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5499                                pkg.applicationInfo.uid);
5500                        if (ret >= 0) {
5501                            recovered = true;
5502                            String msg = "Package " + pkg.packageName
5503                                    + " unexpectedly changed to uid 0; recovered to " +
5504                                    + pkg.applicationInfo.uid;
5505                            reportSettingsProblem(Log.WARN, msg);
5506                        }
5507                    }
5508                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5509                            || (scanFlags&SCAN_BOOTING) != 0)) {
5510                        // If this is a system app, we can at least delete its
5511                        // current data so the application will still work.
5512                        int ret = removeDataDirsLI(pkgName);
5513                        if (ret >= 0) {
5514                            // TODO: Kill the processes first
5515                            // Old data gone!
5516                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5517                                    ? "System package " : "Third party package ";
5518                            String msg = prefix + pkg.packageName
5519                                    + " has changed from uid: "
5520                                    + currentUid + " to "
5521                                    + pkg.applicationInfo.uid + "; old data erased";
5522                            reportSettingsProblem(Log.WARN, msg);
5523                            recovered = true;
5524
5525                            // And now re-install the app.
5526                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5527                                                   pkg.applicationInfo.seinfo);
5528                            if (ret == -1) {
5529                                // Ack should not happen!
5530                                msg = prefix + pkg.packageName
5531                                        + " could not have data directory re-created after delete.";
5532                                reportSettingsProblem(Log.WARN, msg);
5533                                throw new PackageManagerException(
5534                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5535                            }
5536                        }
5537                        if (!recovered) {
5538                            mHasSystemUidErrors = true;
5539                        }
5540                    } else if (!recovered) {
5541                        // If we allow this install to proceed, we will be broken.
5542                        // Abort, abort!
5543                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5544                                "scanPackageLI");
5545                    }
5546                    if (!recovered) {
5547                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5548                            + pkg.applicationInfo.uid + "/fs_"
5549                            + currentUid;
5550                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5551                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5552                        String msg = "Package " + pkg.packageName
5553                                + " has mismatched uid: "
5554                                + currentUid + " on disk, "
5555                                + pkg.applicationInfo.uid + " in settings";
5556                        // writer
5557                        synchronized (mPackages) {
5558                            mSettings.mReadMessages.append(msg);
5559                            mSettings.mReadMessages.append('\n');
5560                            uidError = true;
5561                            if (!pkgSetting.uidError) {
5562                                reportSettingsProblem(Log.ERROR, msg);
5563                            }
5564                        }
5565                    }
5566                }
5567                pkg.applicationInfo.dataDir = dataPath.getPath();
5568                if (mShouldRestoreconData) {
5569                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5570                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5571                                pkg.applicationInfo.uid);
5572                }
5573            } else {
5574                if (DEBUG_PACKAGE_SCANNING) {
5575                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5576                        Log.v(TAG, "Want this data dir: " + dataPath);
5577                }
5578                //invoke installer to do the actual installation
5579                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5580                                           pkg.applicationInfo.seinfo);
5581                if (ret < 0) {
5582                    // Error from installer
5583                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5584                            "Unable to create data dirs [errorCode=" + ret + "]");
5585                }
5586
5587                if (dataPath.exists()) {
5588                    pkg.applicationInfo.dataDir = dataPath.getPath();
5589                } else {
5590                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5591                    pkg.applicationInfo.dataDir = null;
5592                }
5593            }
5594
5595            pkgSetting.uidError = uidError;
5596        }
5597
5598        final String path = scanFile.getPath();
5599        final String codePath = pkg.applicationInfo.getCodePath();
5600        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5601        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5602            setBundledAppAbisAndRoots(pkg, pkgSetting);
5603
5604            // If we haven't found any native libraries for the app, check if it has
5605            // renderscript code. We'll need to force the app to 32 bit if it has
5606            // renderscript bitcode.
5607            if (pkg.applicationInfo.primaryCpuAbi == null
5608                    && pkg.applicationInfo.secondaryCpuAbi == null
5609                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5610                NativeLibraryHelper.Handle handle = null;
5611                try {
5612                    handle = NativeLibraryHelper.Handle.create(scanFile);
5613                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5614                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5615                    }
5616                } catch (IOException ioe) {
5617                    Slog.w(TAG, "Error scanning system app : " + ioe);
5618                } finally {
5619                    IoUtils.closeQuietly(handle);
5620                }
5621            }
5622
5623            setNativeLibraryPaths(pkg);
5624        } else {
5625            // TODO: We can probably be smarter about this stuff. For installed apps,
5626            // we can calculate this information at install time once and for all. For
5627            // system apps, we can probably assume that this information doesn't change
5628            // after the first boot scan. As things stand, we do lots of unnecessary work.
5629
5630            // Give ourselves some initial paths; we'll come back for another
5631            // pass once we've determined ABI below.
5632            setNativeLibraryPaths(pkg);
5633
5634            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5635            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5636            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5637
5638            NativeLibraryHelper.Handle handle = null;
5639            try {
5640                handle = NativeLibraryHelper.Handle.create(scanFile);
5641                // TODO(multiArch): This can be null for apps that didn't go through the
5642                // usual installation process. We can calculate it again, like we
5643                // do during install time.
5644                //
5645                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5646                // unnecessary.
5647                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5648
5649                // Null out the abis so that they can be recalculated.
5650                pkg.applicationInfo.primaryCpuAbi = null;
5651                pkg.applicationInfo.secondaryCpuAbi = null;
5652                if (isMultiArch(pkg.applicationInfo)) {
5653                    // Warn if we've set an abiOverride for multi-lib packages..
5654                    // By definition, we need to copy both 32 and 64 bit libraries for
5655                    // such packages.
5656                    if (pkg.cpuAbiOverride != null
5657                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5658                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5659                    }
5660
5661                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5662                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5663                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5664                        if (isAsec) {
5665                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5666                        } else {
5667                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5668                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5669                                    useIsaSpecificSubdirs);
5670                        }
5671                    }
5672
5673                    maybeThrowExceptionForMultiArchCopy(
5674                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5675
5676                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5677                        if (isAsec) {
5678                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5679                        } else {
5680                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5681                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5682                                    useIsaSpecificSubdirs);
5683                        }
5684                    }
5685
5686                    maybeThrowExceptionForMultiArchCopy(
5687                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5688
5689                    if (abi64 >= 0) {
5690                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5691                    }
5692
5693                    if (abi32 >= 0) {
5694                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5695                        if (abi64 >= 0) {
5696                            pkg.applicationInfo.secondaryCpuAbi = abi;
5697                        } else {
5698                            pkg.applicationInfo.primaryCpuAbi = abi;
5699                        }
5700                    }
5701                } else {
5702                    String[] abiList = (cpuAbiOverride != null) ?
5703                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5704
5705                    // Enable gross and lame hacks for apps that are built with old
5706                    // SDK tools. We must scan their APKs for renderscript bitcode and
5707                    // not launch them if it's present. Don't bother checking on devices
5708                    // that don't have 64 bit support.
5709                    boolean needsRenderScriptOverride = false;
5710                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5711                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5712                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5713                        needsRenderScriptOverride = true;
5714                    }
5715
5716                    final int copyRet;
5717                    if (isAsec) {
5718                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5719                    } else {
5720                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5721                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5722                    }
5723
5724                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5725                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5726                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5727                    }
5728
5729                    if (copyRet >= 0) {
5730                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5731                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5732                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5733                    } else if (needsRenderScriptOverride) {
5734                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5735                    }
5736                }
5737            } catch (IOException ioe) {
5738                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5739            } finally {
5740                IoUtils.closeQuietly(handle);
5741            }
5742
5743            // Now that we've calculated the ABIs and determined if it's an internal app,
5744            // we will go ahead and populate the nativeLibraryPath.
5745            setNativeLibraryPaths(pkg);
5746
5747            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5748            final int[] userIds = sUserManager.getUserIds();
5749            synchronized (mInstallLock) {
5750                // Create a native library symlink only if we have native libraries
5751                // and if the native libraries are 32 bit libraries. We do not provide
5752                // this symlink for 64 bit libraries.
5753                if (pkg.applicationInfo.primaryCpuAbi != null &&
5754                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5755                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5756                    for (int userId : userIds) {
5757                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5758                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5759                                    "Failed linking native library dir (user=" + userId + ")");
5760                        }
5761                    }
5762                }
5763            }
5764        }
5765
5766        // This is a special case for the "system" package, where the ABI is
5767        // dictated by the zygote configuration (and init.rc). We should keep track
5768        // of this ABI so that we can deal with "normal" applications that run under
5769        // the same UID correctly.
5770        if (mPlatformPackage == pkg) {
5771            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5772                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5773        }
5774
5775        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5776        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5777        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5778        // Copy the derived override back to the parsed package, so that we can
5779        // update the package settings accordingly.
5780        pkg.cpuAbiOverride = cpuAbiOverride;
5781
5782        if (DEBUG_ABI_SELECTION) {
5783            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5784                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5785                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5786        }
5787
5788        // Push the derived path down into PackageSettings so we know what to
5789        // clean up at uninstall time.
5790        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5791
5792        if (DEBUG_ABI_SELECTION) {
5793            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5794                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5795                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5796        }
5797
5798        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5799            // We don't do this here during boot because we can do it all
5800            // at once after scanning all existing packages.
5801            //
5802            // We also do this *before* we perform dexopt on this package, so that
5803            // we can avoid redundant dexopts, and also to make sure we've got the
5804            // code and package path correct.
5805            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5806                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5807        }
5808
5809        if ((scanFlags & SCAN_NO_DEX) == 0) {
5810            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5811                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5812                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5813            }
5814        }
5815
5816        if (mFactoryTest && pkg.requestedPermissions.contains(
5817                android.Manifest.permission.FACTORY_TEST)) {
5818            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5819        }
5820
5821        ArrayList<PackageParser.Package> clientLibPkgs = null;
5822
5823        // writer
5824        synchronized (mPackages) {
5825            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5826                // Only system apps can add new shared libraries.
5827                if (pkg.libraryNames != null) {
5828                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5829                        String name = pkg.libraryNames.get(i);
5830                        boolean allowed = false;
5831                        if (isUpdatedSystemApp(pkg)) {
5832                            // New library entries can only be added through the
5833                            // system image.  This is important to get rid of a lot
5834                            // of nasty edge cases: for example if we allowed a non-
5835                            // system update of the app to add a library, then uninstalling
5836                            // the update would make the library go away, and assumptions
5837                            // we made such as through app install filtering would now
5838                            // have allowed apps on the device which aren't compatible
5839                            // with it.  Better to just have the restriction here, be
5840                            // conservative, and create many fewer cases that can negatively
5841                            // impact the user experience.
5842                            final PackageSetting sysPs = mSettings
5843                                    .getDisabledSystemPkgLPr(pkg.packageName);
5844                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5845                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5846                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5847                                        allowed = true;
5848                                        allowed = true;
5849                                        break;
5850                                    }
5851                                }
5852                            }
5853                        } else {
5854                            allowed = true;
5855                        }
5856                        if (allowed) {
5857                            if (!mSharedLibraries.containsKey(name)) {
5858                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5859                            } else if (!name.equals(pkg.packageName)) {
5860                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5861                                        + name + " already exists; skipping");
5862                            }
5863                        } else {
5864                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5865                                    + name + " that is not declared on system image; skipping");
5866                        }
5867                    }
5868                    if ((scanFlags&SCAN_BOOTING) == 0) {
5869                        // If we are not booting, we need to update any applications
5870                        // that are clients of our shared library.  If we are booting,
5871                        // this will all be done once the scan is complete.
5872                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5873                    }
5874                }
5875            }
5876        }
5877
5878        // We also need to dexopt any apps that are dependent on this library.  Note that
5879        // if these fail, we should abort the install since installing the library will
5880        // result in some apps being broken.
5881        if (clientLibPkgs != null) {
5882            if ((scanFlags & SCAN_NO_DEX) == 0) {
5883                for (int i = 0; i < clientLibPkgs.size(); i++) {
5884                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5885                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
5886                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5887                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5888                                "scanPackageLI failed to dexopt clientLibPkgs");
5889                    }
5890                }
5891            }
5892        }
5893
5894        // Request the ActivityManager to kill the process(only for existing packages)
5895        // so that we do not end up in a confused state while the user is still using the older
5896        // version of the application while the new one gets installed.
5897        if ((scanFlags & SCAN_REPLACING) != 0) {
5898            killApplication(pkg.applicationInfo.packageName,
5899                        pkg.applicationInfo.uid, "update pkg");
5900        }
5901
5902        // Also need to kill any apps that are dependent on the library.
5903        if (clientLibPkgs != null) {
5904            for (int i=0; i<clientLibPkgs.size(); i++) {
5905                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5906                killApplication(clientPkg.applicationInfo.packageName,
5907                        clientPkg.applicationInfo.uid, "update lib");
5908            }
5909        }
5910
5911        // writer
5912        synchronized (mPackages) {
5913            // We don't expect installation to fail beyond this point
5914
5915            // Add the new setting to mSettings
5916            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5917            // Add the new setting to mPackages
5918            mPackages.put(pkg.applicationInfo.packageName, pkg);
5919            // Make sure we don't accidentally delete its data.
5920            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5921            while (iter.hasNext()) {
5922                PackageCleanItem item = iter.next();
5923                if (pkgName.equals(item.packageName)) {
5924                    iter.remove();
5925                }
5926            }
5927
5928            // Take care of first install / last update times.
5929            if (currentTime != 0) {
5930                if (pkgSetting.firstInstallTime == 0) {
5931                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5932                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5933                    pkgSetting.lastUpdateTime = currentTime;
5934                }
5935            } else if (pkgSetting.firstInstallTime == 0) {
5936                // We need *something*.  Take time time stamp of the file.
5937                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
5938            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
5939                if (scanFileTime != pkgSetting.timeStamp) {
5940                    // A package on the system image has changed; consider this
5941                    // to be an update.
5942                    pkgSetting.lastUpdateTime = scanFileTime;
5943                }
5944            }
5945
5946            // Add the package's KeySets to the global KeySetManagerService
5947            KeySetManagerService ksms = mSettings.mKeySetManagerService;
5948            try {
5949                // Old KeySetData no longer valid.
5950                ksms.removeAppKeySetDataLPw(pkg.packageName);
5951                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
5952                if (pkg.mKeySetMapping != null) {
5953                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
5954                            pkg.mKeySetMapping.entrySet()) {
5955                        if (entry.getValue() != null) {
5956                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
5957                                                          entry.getValue(), entry.getKey());
5958                        }
5959                    }
5960                    if (pkg.mUpgradeKeySets != null) {
5961                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
5962                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
5963                        }
5964                    }
5965                }
5966            } catch (NullPointerException e) {
5967                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
5968            } catch (IllegalArgumentException e) {
5969                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
5970            }
5971
5972            int N = pkg.providers.size();
5973            StringBuilder r = null;
5974            int i;
5975            for (i=0; i<N; i++) {
5976                PackageParser.Provider p = pkg.providers.get(i);
5977                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
5978                        p.info.processName, pkg.applicationInfo.uid);
5979                mProviders.addProvider(p);
5980                p.syncable = p.info.isSyncable;
5981                if (p.info.authority != null) {
5982                    String names[] = p.info.authority.split(";");
5983                    p.info.authority = null;
5984                    for (int j = 0; j < names.length; j++) {
5985                        if (j == 1 && p.syncable) {
5986                            // We only want the first authority for a provider to possibly be
5987                            // syncable, so if we already added this provider using a different
5988                            // authority clear the syncable flag. We copy the provider before
5989                            // changing it because the mProviders object contains a reference
5990                            // to a provider that we don't want to change.
5991                            // Only do this for the second authority since the resulting provider
5992                            // object can be the same for all future authorities for this provider.
5993                            p = new PackageParser.Provider(p);
5994                            p.syncable = false;
5995                        }
5996                        if (!mProvidersByAuthority.containsKey(names[j])) {
5997                            mProvidersByAuthority.put(names[j], p);
5998                            if (p.info.authority == null) {
5999                                p.info.authority = names[j];
6000                            } else {
6001                                p.info.authority = p.info.authority + ";" + names[j];
6002                            }
6003                            if (DEBUG_PACKAGE_SCANNING) {
6004                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6005                                    Log.d(TAG, "Registered content provider: " + names[j]
6006                                            + ", className = " + p.info.name + ", isSyncable = "
6007                                            + p.info.isSyncable);
6008                            }
6009                        } else {
6010                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6011                            Slog.w(TAG, "Skipping provider name " + names[j] +
6012                                    " (in package " + pkg.applicationInfo.packageName +
6013                                    "): name already used by "
6014                                    + ((other != null && other.getComponentName() != null)
6015                                            ? other.getComponentName().getPackageName() : "?"));
6016                        }
6017                    }
6018                }
6019                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6020                    if (r == null) {
6021                        r = new StringBuilder(256);
6022                    } else {
6023                        r.append(' ');
6024                    }
6025                    r.append(p.info.name);
6026                }
6027            }
6028            if (r != null) {
6029                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6030            }
6031
6032            N = pkg.services.size();
6033            r = null;
6034            for (i=0; i<N; i++) {
6035                PackageParser.Service s = pkg.services.get(i);
6036                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6037                        s.info.processName, pkg.applicationInfo.uid);
6038                mServices.addService(s);
6039                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6040                    if (r == null) {
6041                        r = new StringBuilder(256);
6042                    } else {
6043                        r.append(' ');
6044                    }
6045                    r.append(s.info.name);
6046                }
6047            }
6048            if (r != null) {
6049                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6050            }
6051
6052            N = pkg.receivers.size();
6053            r = null;
6054            for (i=0; i<N; i++) {
6055                PackageParser.Activity a = pkg.receivers.get(i);
6056                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6057                        a.info.processName, pkg.applicationInfo.uid);
6058                mReceivers.addActivity(a, "receiver");
6059                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6060                    if (r == null) {
6061                        r = new StringBuilder(256);
6062                    } else {
6063                        r.append(' ');
6064                    }
6065                    r.append(a.info.name);
6066                }
6067            }
6068            if (r != null) {
6069                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6070            }
6071
6072            N = pkg.activities.size();
6073            r = null;
6074            for (i=0; i<N; i++) {
6075                PackageParser.Activity a = pkg.activities.get(i);
6076                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6077                        a.info.processName, pkg.applicationInfo.uid);
6078                mActivities.addActivity(a, "activity");
6079                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6080                    if (r == null) {
6081                        r = new StringBuilder(256);
6082                    } else {
6083                        r.append(' ');
6084                    }
6085                    r.append(a.info.name);
6086                }
6087            }
6088            if (r != null) {
6089                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6090            }
6091
6092            N = pkg.permissionGroups.size();
6093            r = null;
6094            for (i=0; i<N; i++) {
6095                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6096                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6097                if (cur == null) {
6098                    mPermissionGroups.put(pg.info.name, pg);
6099                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6100                        if (r == null) {
6101                            r = new StringBuilder(256);
6102                        } else {
6103                            r.append(' ');
6104                        }
6105                        r.append(pg.info.name);
6106                    }
6107                } else {
6108                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6109                            + pg.info.packageName + " ignored: original from "
6110                            + cur.info.packageName);
6111                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6112                        if (r == null) {
6113                            r = new StringBuilder(256);
6114                        } else {
6115                            r.append(' ');
6116                        }
6117                        r.append("DUP:");
6118                        r.append(pg.info.name);
6119                    }
6120                }
6121            }
6122            if (r != null) {
6123                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6124            }
6125
6126            N = pkg.permissions.size();
6127            r = null;
6128            for (i=0; i<N; i++) {
6129                PackageParser.Permission p = pkg.permissions.get(i);
6130                HashMap<String, BasePermission> permissionMap =
6131                        p.tree ? mSettings.mPermissionTrees
6132                        : mSettings.mPermissions;
6133                p.group = mPermissionGroups.get(p.info.group);
6134                if (p.info.group == null || p.group != null) {
6135                    BasePermission bp = permissionMap.get(p.info.name);
6136
6137                    // Allow system apps to redefine non-system permissions
6138                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6139                        final boolean currentOwnerIsSystem = (bp.perm != null
6140                                && isSystemApp(bp.perm.owner));
6141                        if (isSystemApp(p.owner)) {
6142                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6143                                // It's a built-in permission and no owner, take ownership now
6144                                bp.packageSetting = pkgSetting;
6145                                bp.perm = p;
6146                                bp.uid = pkg.applicationInfo.uid;
6147                                bp.sourcePackage = p.info.packageName;
6148                            } else if (!currentOwnerIsSystem) {
6149                                String msg = "New decl " + p.owner + " of permission  "
6150                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6151                                reportSettingsProblem(Log.WARN, msg);
6152                                bp = null;
6153                            }
6154                        }
6155                    }
6156
6157                    if (bp == null) {
6158                        bp = new BasePermission(p.info.name, p.info.packageName,
6159                                BasePermission.TYPE_NORMAL);
6160                        permissionMap.put(p.info.name, bp);
6161                    }
6162
6163                    if (bp.perm == null) {
6164                        if (bp.sourcePackage == null
6165                                || bp.sourcePackage.equals(p.info.packageName)) {
6166                            BasePermission tree = findPermissionTreeLP(p.info.name);
6167                            if (tree == null
6168                                    || tree.sourcePackage.equals(p.info.packageName)) {
6169                                bp.packageSetting = pkgSetting;
6170                                bp.perm = p;
6171                                bp.uid = pkg.applicationInfo.uid;
6172                                bp.sourcePackage = p.info.packageName;
6173                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6174                                    if (r == null) {
6175                                        r = new StringBuilder(256);
6176                                    } else {
6177                                        r.append(' ');
6178                                    }
6179                                    r.append(p.info.name);
6180                                }
6181                            } else {
6182                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6183                                        + p.info.packageName + " ignored: base tree "
6184                                        + tree.name + " is from package "
6185                                        + tree.sourcePackage);
6186                            }
6187                        } else {
6188                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6189                                    + p.info.packageName + " ignored: original from "
6190                                    + bp.sourcePackage);
6191                        }
6192                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6193                        if (r == null) {
6194                            r = new StringBuilder(256);
6195                        } else {
6196                            r.append(' ');
6197                        }
6198                        r.append("DUP:");
6199                        r.append(p.info.name);
6200                    }
6201                    if (bp.perm == p) {
6202                        bp.protectionLevel = p.info.protectionLevel;
6203                    }
6204                } else {
6205                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6206                            + p.info.packageName + " ignored: no group "
6207                            + p.group);
6208                }
6209            }
6210            if (r != null) {
6211                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6212            }
6213
6214            N = pkg.instrumentation.size();
6215            r = null;
6216            for (i=0; i<N; i++) {
6217                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6218                a.info.packageName = pkg.applicationInfo.packageName;
6219                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6220                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6221                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6222                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6223                a.info.dataDir = pkg.applicationInfo.dataDir;
6224
6225                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6226                // need other information about the application, like the ABI and what not ?
6227                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6228                mInstrumentation.put(a.getComponentName(), a);
6229                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6230                    if (r == null) {
6231                        r = new StringBuilder(256);
6232                    } else {
6233                        r.append(' ');
6234                    }
6235                    r.append(a.info.name);
6236                }
6237            }
6238            if (r != null) {
6239                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6240            }
6241
6242            if (pkg.protectedBroadcasts != null) {
6243                N = pkg.protectedBroadcasts.size();
6244                for (i=0; i<N; i++) {
6245                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6246                }
6247            }
6248
6249            pkgSetting.setTimeStamp(scanFileTime);
6250
6251            // Create idmap files for pairs of (packages, overlay packages).
6252            // Note: "android", ie framework-res.apk, is handled by native layers.
6253            if (pkg.mOverlayTarget != null) {
6254                // This is an overlay package.
6255                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6256                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6257                        mOverlays.put(pkg.mOverlayTarget,
6258                                new HashMap<String, PackageParser.Package>());
6259                    }
6260                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6261                    map.put(pkg.packageName, pkg);
6262                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6263                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6264                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6265                                "scanPackageLI failed to createIdmap");
6266                    }
6267                }
6268            } else if (mOverlays.containsKey(pkg.packageName) &&
6269                    !pkg.packageName.equals("android")) {
6270                // This is a regular package, with one or more known overlay packages.
6271                createIdmapsForPackageLI(pkg);
6272            }
6273        }
6274
6275        return pkg;
6276    }
6277
6278    /**
6279     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6280     * i.e, so that all packages can be run inside a single process if required.
6281     *
6282     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6283     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6284     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6285     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6286     * updating a package that belongs to a shared user.
6287     *
6288     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6289     * adds unnecessary complexity.
6290     */
6291    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6292            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6293        String requiredInstructionSet = null;
6294        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6295            requiredInstructionSet = VMRuntime.getInstructionSet(
6296                     scannedPackage.applicationInfo.primaryCpuAbi);
6297        }
6298
6299        PackageSetting requirer = null;
6300        for (PackageSetting ps : packagesForUser) {
6301            // If packagesForUser contains scannedPackage, we skip it. This will happen
6302            // when scannedPackage is an update of an existing package. Without this check,
6303            // we will never be able to change the ABI of any package belonging to a shared
6304            // user, even if it's compatible with other packages.
6305            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6306                if (ps.primaryCpuAbiString == null) {
6307                    continue;
6308                }
6309
6310                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6311                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6312                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6313                    // this but there's not much we can do.
6314                    String errorMessage = "Instruction set mismatch, "
6315                            + ((requirer == null) ? "[caller]" : requirer)
6316                            + " requires " + requiredInstructionSet + " whereas " + ps
6317                            + " requires " + instructionSet;
6318                    Slog.w(TAG, errorMessage);
6319                }
6320
6321                if (requiredInstructionSet == null) {
6322                    requiredInstructionSet = instructionSet;
6323                    requirer = ps;
6324                }
6325            }
6326        }
6327
6328        if (requiredInstructionSet != null) {
6329            String adjustedAbi;
6330            if (requirer != null) {
6331                // requirer != null implies that either scannedPackage was null or that scannedPackage
6332                // did not require an ABI, in which case we have to adjust scannedPackage to match
6333                // the ABI of the set (which is the same as requirer's ABI)
6334                adjustedAbi = requirer.primaryCpuAbiString;
6335                if (scannedPackage != null) {
6336                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6337                }
6338            } else {
6339                // requirer == null implies that we're updating all ABIs in the set to
6340                // match scannedPackage.
6341                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6342            }
6343
6344            for (PackageSetting ps : packagesForUser) {
6345                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6346                    if (ps.primaryCpuAbiString != null) {
6347                        continue;
6348                    }
6349
6350                    ps.primaryCpuAbiString = adjustedAbi;
6351                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6352                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6353                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6354
6355                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6356                                deferDexOpt, true) == DEX_OPT_FAILED) {
6357                            ps.primaryCpuAbiString = null;
6358                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6359                            return;
6360                        } else {
6361                            mInstaller.rmdex(ps.codePathString,
6362                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6363                        }
6364                    }
6365                }
6366            }
6367        }
6368    }
6369
6370    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6371        synchronized (mPackages) {
6372            mResolverReplaced = true;
6373            // Set up information for custom user intent resolution activity.
6374            mResolveActivity.applicationInfo = pkg.applicationInfo;
6375            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6376            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6377            mResolveActivity.processName = null;
6378            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6379            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6380                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6381            mResolveActivity.theme = 0;
6382            mResolveActivity.exported = true;
6383            mResolveActivity.enabled = true;
6384            mResolveInfo.activityInfo = mResolveActivity;
6385            mResolveInfo.priority = 0;
6386            mResolveInfo.preferredOrder = 0;
6387            mResolveInfo.match = 0;
6388            mResolveComponentName = mCustomResolverComponentName;
6389            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6390                    mResolveComponentName);
6391        }
6392    }
6393
6394    private static String calculateBundledApkRoot(final String codePathString) {
6395        final File codePath = new File(codePathString);
6396        final File codeRoot;
6397        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6398            codeRoot = Environment.getRootDirectory();
6399        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6400            codeRoot = Environment.getOemDirectory();
6401        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6402            codeRoot = Environment.getVendorDirectory();
6403        } else {
6404            // Unrecognized code path; take its top real segment as the apk root:
6405            // e.g. /something/app/blah.apk => /something
6406            try {
6407                File f = codePath.getCanonicalFile();
6408                File parent = f.getParentFile();    // non-null because codePath is a file
6409                File tmp;
6410                while ((tmp = parent.getParentFile()) != null) {
6411                    f = parent;
6412                    parent = tmp;
6413                }
6414                codeRoot = f;
6415                Slog.w(TAG, "Unrecognized code path "
6416                        + codePath + " - using " + codeRoot);
6417            } catch (IOException e) {
6418                // Can't canonicalize the code path -- shenanigans?
6419                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6420                return Environment.getRootDirectory().getPath();
6421            }
6422        }
6423        return codeRoot.getPath();
6424    }
6425
6426    /**
6427     * Derive and set the location of native libraries for the given package,
6428     * which varies depending on where and how the package was installed.
6429     */
6430    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6431        final ApplicationInfo info = pkg.applicationInfo;
6432        final String codePath = pkg.codePath;
6433        final File codeFile = new File(codePath);
6434        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6435        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6436
6437        info.nativeLibraryRootDir = null;
6438        info.nativeLibraryRootRequiresIsa = false;
6439        info.nativeLibraryDir = null;
6440        info.secondaryNativeLibraryDir = null;
6441
6442        if (isApkFile(codeFile)) {
6443            // Monolithic install
6444            if (bundledApp) {
6445                // If "/system/lib64/apkname" exists, assume that is the per-package
6446                // native library directory to use; otherwise use "/system/lib/apkname".
6447                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6448                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6449                        getPrimaryInstructionSet(info));
6450
6451                // This is a bundled system app so choose the path based on the ABI.
6452                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6453                // is just the default path.
6454                final String apkName = deriveCodePathName(codePath);
6455                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6456                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6457                        apkName).getAbsolutePath();
6458
6459                if (info.secondaryCpuAbi != null) {
6460                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6461                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6462                            secondaryLibDir, apkName).getAbsolutePath();
6463                }
6464            } else if (asecApp) {
6465                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6466                        .getAbsolutePath();
6467            } else {
6468                final String apkName = deriveCodePathName(codePath);
6469                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6470                        .getAbsolutePath();
6471            }
6472
6473            info.nativeLibraryRootRequiresIsa = false;
6474            info.nativeLibraryDir = info.nativeLibraryRootDir;
6475        } else {
6476            // Cluster install
6477            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6478            info.nativeLibraryRootRequiresIsa = true;
6479
6480            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6481                    getPrimaryInstructionSet(info)).getAbsolutePath();
6482
6483            if (info.secondaryCpuAbi != null) {
6484                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6485                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6486            }
6487        }
6488    }
6489
6490    /**
6491     * Calculate the abis and roots for a bundled app. These can uniquely
6492     * be determined from the contents of the system partition, i.e whether
6493     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6494     * of this information, and instead assume that the system was built
6495     * sensibly.
6496     */
6497    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6498                                           PackageSetting pkgSetting) {
6499        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6500
6501        // If "/system/lib64/apkname" exists, assume that is the per-package
6502        // native library directory to use; otherwise use "/system/lib/apkname".
6503        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6504        setBundledAppAbi(pkg, apkRoot, apkName);
6505        // pkgSetting might be null during rescan following uninstall of updates
6506        // to a bundled app, so accommodate that possibility.  The settings in
6507        // that case will be established later from the parsed package.
6508        //
6509        // If the settings aren't null, sync them up with what we've just derived.
6510        // note that apkRoot isn't stored in the package settings.
6511        if (pkgSetting != null) {
6512            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6513            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6514        }
6515    }
6516
6517    /**
6518     * Deduces the ABI of a bundled app and sets the relevant fields on the
6519     * parsed pkg object.
6520     *
6521     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6522     *        under which system libraries are installed.
6523     * @param apkName the name of the installed package.
6524     */
6525    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6526        final File codeFile = new File(pkg.codePath);
6527
6528        final boolean has64BitLibs;
6529        final boolean has32BitLibs;
6530        if (isApkFile(codeFile)) {
6531            // Monolithic install
6532            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6533            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6534        } else {
6535            // Cluster install
6536            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6537            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6538                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6539                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6540                has64BitLibs = (new File(rootDir, isa)).exists();
6541            } else {
6542                has64BitLibs = false;
6543            }
6544            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6545                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6546                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6547                has32BitLibs = (new File(rootDir, isa)).exists();
6548            } else {
6549                has32BitLibs = false;
6550            }
6551        }
6552
6553        if (has64BitLibs && !has32BitLibs) {
6554            // The package has 64 bit libs, but not 32 bit libs. Its primary
6555            // ABI should be 64 bit. We can safely assume here that the bundled
6556            // native libraries correspond to the most preferred ABI in the list.
6557
6558            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6559            pkg.applicationInfo.secondaryCpuAbi = null;
6560        } else if (has32BitLibs && !has64BitLibs) {
6561            // The package has 32 bit libs but not 64 bit libs. Its primary
6562            // ABI should be 32 bit.
6563
6564            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6565            pkg.applicationInfo.secondaryCpuAbi = null;
6566        } else if (has32BitLibs && has64BitLibs) {
6567            // The application has both 64 and 32 bit bundled libraries. We check
6568            // here that the app declares multiArch support, and warn if it doesn't.
6569            //
6570            // We will be lenient here and record both ABIs. The primary will be the
6571            // ABI that's higher on the list, i.e, a device that's configured to prefer
6572            // 64 bit apps will see a 64 bit primary ABI,
6573
6574            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6575                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6576            }
6577
6578            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6579                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6580                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6581            } else {
6582                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6583                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6584            }
6585        } else {
6586            pkg.applicationInfo.primaryCpuAbi = null;
6587            pkg.applicationInfo.secondaryCpuAbi = null;
6588        }
6589    }
6590
6591    private void killApplication(String pkgName, int appId, String reason) {
6592        // Request the ActivityManager to kill the process(only for existing packages)
6593        // so that we do not end up in a confused state while the user is still using the older
6594        // version of the application while the new one gets installed.
6595        IActivityManager am = ActivityManagerNative.getDefault();
6596        if (am != null) {
6597            try {
6598                am.killApplicationWithAppId(pkgName, appId, reason);
6599            } catch (RemoteException e) {
6600            }
6601        }
6602    }
6603
6604    void removePackageLI(PackageSetting ps, boolean chatty) {
6605        if (DEBUG_INSTALL) {
6606            if (chatty)
6607                Log.d(TAG, "Removing package " + ps.name);
6608        }
6609
6610        // writer
6611        synchronized (mPackages) {
6612            mPackages.remove(ps.name);
6613            final PackageParser.Package pkg = ps.pkg;
6614            if (pkg != null) {
6615                cleanPackageDataStructuresLILPw(pkg, chatty);
6616            }
6617        }
6618    }
6619
6620    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6621        if (DEBUG_INSTALL) {
6622            if (chatty)
6623                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6624        }
6625
6626        // writer
6627        synchronized (mPackages) {
6628            mPackages.remove(pkg.applicationInfo.packageName);
6629            cleanPackageDataStructuresLILPw(pkg, chatty);
6630        }
6631    }
6632
6633    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6634        int N = pkg.providers.size();
6635        StringBuilder r = null;
6636        int i;
6637        for (i=0; i<N; i++) {
6638            PackageParser.Provider p = pkg.providers.get(i);
6639            mProviders.removeProvider(p);
6640            if (p.info.authority == null) {
6641
6642                /* There was another ContentProvider with this authority when
6643                 * this app was installed so this authority is null,
6644                 * Ignore it as we don't have to unregister the provider.
6645                 */
6646                continue;
6647            }
6648            String names[] = p.info.authority.split(";");
6649            for (int j = 0; j < names.length; j++) {
6650                if (mProvidersByAuthority.get(names[j]) == p) {
6651                    mProvidersByAuthority.remove(names[j]);
6652                    if (DEBUG_REMOVE) {
6653                        if (chatty)
6654                            Log.d(TAG, "Unregistered content provider: " + names[j]
6655                                    + ", className = " + p.info.name + ", isSyncable = "
6656                                    + p.info.isSyncable);
6657                    }
6658                }
6659            }
6660            if (DEBUG_REMOVE && chatty) {
6661                if (r == null) {
6662                    r = new StringBuilder(256);
6663                } else {
6664                    r.append(' ');
6665                }
6666                r.append(p.info.name);
6667            }
6668        }
6669        if (r != null) {
6670            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6671        }
6672
6673        N = pkg.services.size();
6674        r = null;
6675        for (i=0; i<N; i++) {
6676            PackageParser.Service s = pkg.services.get(i);
6677            mServices.removeService(s);
6678            if (chatty) {
6679                if (r == null) {
6680                    r = new StringBuilder(256);
6681                } else {
6682                    r.append(' ');
6683                }
6684                r.append(s.info.name);
6685            }
6686        }
6687        if (r != null) {
6688            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6689        }
6690
6691        N = pkg.receivers.size();
6692        r = null;
6693        for (i=0; i<N; i++) {
6694            PackageParser.Activity a = pkg.receivers.get(i);
6695            mReceivers.removeActivity(a, "receiver");
6696            if (DEBUG_REMOVE && chatty) {
6697                if (r == null) {
6698                    r = new StringBuilder(256);
6699                } else {
6700                    r.append(' ');
6701                }
6702                r.append(a.info.name);
6703            }
6704        }
6705        if (r != null) {
6706            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6707        }
6708
6709        N = pkg.activities.size();
6710        r = null;
6711        for (i=0; i<N; i++) {
6712            PackageParser.Activity a = pkg.activities.get(i);
6713            mActivities.removeActivity(a, "activity");
6714            if (DEBUG_REMOVE && chatty) {
6715                if (r == null) {
6716                    r = new StringBuilder(256);
6717                } else {
6718                    r.append(' ');
6719                }
6720                r.append(a.info.name);
6721            }
6722        }
6723        if (r != null) {
6724            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6725        }
6726
6727        N = pkg.permissions.size();
6728        r = null;
6729        for (i=0; i<N; i++) {
6730            PackageParser.Permission p = pkg.permissions.get(i);
6731            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6732            if (bp == null) {
6733                bp = mSettings.mPermissionTrees.get(p.info.name);
6734            }
6735            if (bp != null && bp.perm == p) {
6736                bp.perm = null;
6737                if (DEBUG_REMOVE && chatty) {
6738                    if (r == null) {
6739                        r = new StringBuilder(256);
6740                    } else {
6741                        r.append(' ');
6742                    }
6743                    r.append(p.info.name);
6744                }
6745            }
6746            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6747                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6748                if (appOpPerms != null) {
6749                    appOpPerms.remove(pkg.packageName);
6750                }
6751            }
6752        }
6753        if (r != null) {
6754            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6755        }
6756
6757        N = pkg.requestedPermissions.size();
6758        r = null;
6759        for (i=0; i<N; i++) {
6760            String perm = pkg.requestedPermissions.get(i);
6761            BasePermission bp = mSettings.mPermissions.get(perm);
6762            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6763                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6764                if (appOpPerms != null) {
6765                    appOpPerms.remove(pkg.packageName);
6766                    if (appOpPerms.isEmpty()) {
6767                        mAppOpPermissionPackages.remove(perm);
6768                    }
6769                }
6770            }
6771        }
6772        if (r != null) {
6773            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6774        }
6775
6776        N = pkg.instrumentation.size();
6777        r = null;
6778        for (i=0; i<N; i++) {
6779            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6780            mInstrumentation.remove(a.getComponentName());
6781            if (DEBUG_REMOVE && chatty) {
6782                if (r == null) {
6783                    r = new StringBuilder(256);
6784                } else {
6785                    r.append(' ');
6786                }
6787                r.append(a.info.name);
6788            }
6789        }
6790        if (r != null) {
6791            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6792        }
6793
6794        r = null;
6795        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6796            // Only system apps can hold shared libraries.
6797            if (pkg.libraryNames != null) {
6798                for (i=0; i<pkg.libraryNames.size(); i++) {
6799                    String name = pkg.libraryNames.get(i);
6800                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6801                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6802                        mSharedLibraries.remove(name);
6803                        if (DEBUG_REMOVE && chatty) {
6804                            if (r == null) {
6805                                r = new StringBuilder(256);
6806                            } else {
6807                                r.append(' ');
6808                            }
6809                            r.append(name);
6810                        }
6811                    }
6812                }
6813            }
6814        }
6815        if (r != null) {
6816            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6817        }
6818    }
6819
6820    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6821        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6822            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6823                return true;
6824            }
6825        }
6826        return false;
6827    }
6828
6829    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6830    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6831    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6832
6833    private void updatePermissionsLPw(String changingPkg,
6834            PackageParser.Package pkgInfo, int flags) {
6835        // Make sure there are no dangling permission trees.
6836        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6837        while (it.hasNext()) {
6838            final BasePermission bp = it.next();
6839            if (bp.packageSetting == null) {
6840                // We may not yet have parsed the package, so just see if
6841                // we still know about its settings.
6842                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6843            }
6844            if (bp.packageSetting == null) {
6845                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6846                        + " from package " + bp.sourcePackage);
6847                it.remove();
6848            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6849                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6850                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6851                            + " from package " + bp.sourcePackage);
6852                    flags |= UPDATE_PERMISSIONS_ALL;
6853                    it.remove();
6854                }
6855            }
6856        }
6857
6858        // Make sure all dynamic permissions have been assigned to a package,
6859        // and make sure there are no dangling permissions.
6860        it = mSettings.mPermissions.values().iterator();
6861        while (it.hasNext()) {
6862            final BasePermission bp = it.next();
6863            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6864                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6865                        + bp.name + " pkg=" + bp.sourcePackage
6866                        + " info=" + bp.pendingInfo);
6867                if (bp.packageSetting == null && bp.pendingInfo != null) {
6868                    final BasePermission tree = findPermissionTreeLP(bp.name);
6869                    if (tree != null && tree.perm != null) {
6870                        bp.packageSetting = tree.packageSetting;
6871                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6872                                new PermissionInfo(bp.pendingInfo));
6873                        bp.perm.info.packageName = tree.perm.info.packageName;
6874                        bp.perm.info.name = bp.name;
6875                        bp.uid = tree.uid;
6876                    }
6877                }
6878            }
6879            if (bp.packageSetting == null) {
6880                // We may not yet have parsed the package, so just see if
6881                // we still know about its settings.
6882                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6883            }
6884            if (bp.packageSetting == null) {
6885                Slog.w(TAG, "Removing dangling permission: " + bp.name
6886                        + " from package " + bp.sourcePackage);
6887                it.remove();
6888            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6889                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6890                    Slog.i(TAG, "Removing old permission: " + bp.name
6891                            + " from package " + bp.sourcePackage);
6892                    flags |= UPDATE_PERMISSIONS_ALL;
6893                    it.remove();
6894                }
6895            }
6896        }
6897
6898        // Now update the permissions for all packages, in particular
6899        // replace the granted permissions of the system packages.
6900        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6901            for (PackageParser.Package pkg : mPackages.values()) {
6902                if (pkg != pkgInfo) {
6903                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6904                            changingPkg);
6905                }
6906            }
6907        }
6908
6909        if (pkgInfo != null) {
6910            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6911        }
6912    }
6913
6914    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6915            String packageOfInterest) {
6916        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6917        if (ps == null) {
6918            return;
6919        }
6920        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6921        HashSet<String> origPermissions = gp.grantedPermissions;
6922        boolean changedPermission = false;
6923
6924        if (replace) {
6925            ps.permissionsFixed = false;
6926            if (gp == ps) {
6927                origPermissions = new HashSet<String>(gp.grantedPermissions);
6928                gp.grantedPermissions.clear();
6929                gp.gids = mGlobalGids;
6930            }
6931        }
6932
6933        if (gp.gids == null) {
6934            gp.gids = mGlobalGids;
6935        }
6936
6937        final int N = pkg.requestedPermissions.size();
6938        for (int i=0; i<N; i++) {
6939            final String name = pkg.requestedPermissions.get(i);
6940            final boolean required = pkg.requestedPermissionsRequired.get(i);
6941            final BasePermission bp = mSettings.mPermissions.get(name);
6942            if (DEBUG_INSTALL) {
6943                if (gp != ps) {
6944                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
6945                }
6946            }
6947
6948            if (bp == null || bp.packageSetting == null) {
6949                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
6950                    Slog.w(TAG, "Unknown permission " + name
6951                            + " in package " + pkg.packageName);
6952                }
6953                continue;
6954            }
6955
6956            final String perm = bp.name;
6957            boolean allowed;
6958            boolean allowedSig = false;
6959            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6960                // Keep track of app op permissions.
6961                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
6962                if (pkgs == null) {
6963                    pkgs = new ArraySet<>();
6964                    mAppOpPermissionPackages.put(bp.name, pkgs);
6965                }
6966                pkgs.add(pkg.packageName);
6967            }
6968            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
6969            if (level == PermissionInfo.PROTECTION_NORMAL
6970                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
6971                // We grant a normal or dangerous permission if any of the following
6972                // are true:
6973                // 1) The permission is required
6974                // 2) The permission is optional, but was granted in the past
6975                // 3) The permission is optional, but was requested by an
6976                //    app in /system (not /data)
6977                //
6978                // Otherwise, reject the permission.
6979                allowed = (required || origPermissions.contains(perm)
6980                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
6981            } else if (bp.packageSetting == null) {
6982                // This permission is invalid; skip it.
6983                allowed = false;
6984            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
6985                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
6986                if (allowed) {
6987                    allowedSig = true;
6988                }
6989            } else {
6990                allowed = false;
6991            }
6992            if (DEBUG_INSTALL) {
6993                if (gp != ps) {
6994                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
6995                }
6996            }
6997            if (allowed) {
6998                if (!isSystemApp(ps) && ps.permissionsFixed) {
6999                    // If this is an existing, non-system package, then
7000                    // we can't add any new permissions to it.
7001                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
7002                        // Except...  if this is a permission that was added
7003                        // to the platform (note: need to only do this when
7004                        // updating the platform).
7005                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
7006                    }
7007                }
7008                if (allowed) {
7009                    if (!gp.grantedPermissions.contains(perm)) {
7010                        changedPermission = true;
7011                        gp.grantedPermissions.add(perm);
7012                        gp.gids = appendInts(gp.gids, bp.gids);
7013                    } else if (!ps.haveGids) {
7014                        gp.gids = appendInts(gp.gids, bp.gids);
7015                    }
7016                } else {
7017                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7018                        Slog.w(TAG, "Not granting permission " + perm
7019                                + " to package " + pkg.packageName
7020                                + " because it was previously installed without");
7021                    }
7022                }
7023            } else {
7024                if (gp.grantedPermissions.remove(perm)) {
7025                    changedPermission = true;
7026                    gp.gids = removeInts(gp.gids, bp.gids);
7027                    Slog.i(TAG, "Un-granting permission " + perm
7028                            + " from package " + pkg.packageName
7029                            + " (protectionLevel=" + bp.protectionLevel
7030                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7031                            + ")");
7032                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7033                    // Don't print warning for app op permissions, since it is fine for them
7034                    // not to be granted, there is a UI for the user to decide.
7035                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7036                        Slog.w(TAG, "Not granting permission " + perm
7037                                + " to package " + pkg.packageName
7038                                + " (protectionLevel=" + bp.protectionLevel
7039                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7040                                + ")");
7041                    }
7042                }
7043            }
7044        }
7045
7046        if ((changedPermission || replace) && !ps.permissionsFixed &&
7047                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7048            // This is the first that we have heard about this package, so the
7049            // permissions we have now selected are fixed until explicitly
7050            // changed.
7051            ps.permissionsFixed = true;
7052        }
7053        ps.haveGids = true;
7054    }
7055
7056    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7057        boolean allowed = false;
7058        final int NP = PackageParser.NEW_PERMISSIONS.length;
7059        for (int ip=0; ip<NP; ip++) {
7060            final PackageParser.NewPermissionInfo npi
7061                    = PackageParser.NEW_PERMISSIONS[ip];
7062            if (npi.name.equals(perm)
7063                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7064                allowed = true;
7065                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7066                        + pkg.packageName);
7067                break;
7068            }
7069        }
7070        return allowed;
7071    }
7072
7073    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7074                                          BasePermission bp, HashSet<String> origPermissions) {
7075        boolean allowed;
7076        allowed = (compareSignatures(
7077                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7078                        == PackageManager.SIGNATURE_MATCH)
7079                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7080                        == PackageManager.SIGNATURE_MATCH);
7081        if (!allowed && (bp.protectionLevel
7082                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7083            if (isSystemApp(pkg)) {
7084                // For updated system applications, a system permission
7085                // is granted only if it had been defined by the original application.
7086                if (isUpdatedSystemApp(pkg)) {
7087                    final PackageSetting sysPs = mSettings
7088                            .getDisabledSystemPkgLPr(pkg.packageName);
7089                    final GrantedPermissions origGp = sysPs.sharedUser != null
7090                            ? sysPs.sharedUser : sysPs;
7091
7092                    if (origGp.grantedPermissions.contains(perm)) {
7093                        // If the original was granted this permission, we take
7094                        // that grant decision as read and propagate it to the
7095                        // update.
7096                        allowed = true;
7097                    } else {
7098                        // The system apk may have been updated with an older
7099                        // version of the one on the data partition, but which
7100                        // granted a new system permission that it didn't have
7101                        // before.  In this case we do want to allow the app to
7102                        // now get the new permission if the ancestral apk is
7103                        // privileged to get it.
7104                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7105                            for (int j=0;
7106                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7107                                if (perm.equals(
7108                                        sysPs.pkg.requestedPermissions.get(j))) {
7109                                    allowed = true;
7110                                    break;
7111                                }
7112                            }
7113                        }
7114                    }
7115                } else {
7116                    allowed = isPrivilegedApp(pkg);
7117                }
7118            }
7119        }
7120        if (!allowed && (bp.protectionLevel
7121                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7122            // For development permissions, a development permission
7123            // is granted only if it was already granted.
7124            allowed = origPermissions.contains(perm);
7125        }
7126        return allowed;
7127    }
7128
7129    final class ActivityIntentResolver
7130            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7131        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7132                boolean defaultOnly, int userId) {
7133            if (!sUserManager.exists(userId)) return null;
7134            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7135            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7136        }
7137
7138        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7139                int userId) {
7140            if (!sUserManager.exists(userId)) return null;
7141            mFlags = flags;
7142            return super.queryIntent(intent, resolvedType,
7143                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7144        }
7145
7146        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7147                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7148            if (!sUserManager.exists(userId)) return null;
7149            if (packageActivities == null) {
7150                return null;
7151            }
7152            mFlags = flags;
7153            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7154            final int N = packageActivities.size();
7155            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7156                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7157
7158            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7159            for (int i = 0; i < N; ++i) {
7160                intentFilters = packageActivities.get(i).intents;
7161                if (intentFilters != null && intentFilters.size() > 0) {
7162                    PackageParser.ActivityIntentInfo[] array =
7163                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7164                    intentFilters.toArray(array);
7165                    listCut.add(array);
7166                }
7167            }
7168            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7169        }
7170
7171        public final void addActivity(PackageParser.Activity a, String type) {
7172            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7173            mActivities.put(a.getComponentName(), a);
7174            if (DEBUG_SHOW_INFO)
7175                Log.v(
7176                TAG, "  " + type + " " +
7177                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7178            if (DEBUG_SHOW_INFO)
7179                Log.v(TAG, "    Class=" + a.info.name);
7180            final int NI = a.intents.size();
7181            for (int j=0; j<NI; j++) {
7182                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7183                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7184                    intent.setPriority(0);
7185                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7186                            + a.className + " with priority > 0, forcing to 0");
7187                }
7188                if (DEBUG_SHOW_INFO) {
7189                    Log.v(TAG, "    IntentFilter:");
7190                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7191                }
7192                if (!intent.debugCheck()) {
7193                    Log.w(TAG, "==> For Activity " + a.info.name);
7194                }
7195                addFilter(intent);
7196            }
7197        }
7198
7199        public final void removeActivity(PackageParser.Activity a, String type) {
7200            mActivities.remove(a.getComponentName());
7201            if (DEBUG_SHOW_INFO) {
7202                Log.v(TAG, "  " + type + " "
7203                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7204                                : a.info.name) + ":");
7205                Log.v(TAG, "    Class=" + a.info.name);
7206            }
7207            final int NI = a.intents.size();
7208            for (int j=0; j<NI; j++) {
7209                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7210                if (DEBUG_SHOW_INFO) {
7211                    Log.v(TAG, "    IntentFilter:");
7212                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7213                }
7214                removeFilter(intent);
7215            }
7216        }
7217
7218        @Override
7219        protected boolean allowFilterResult(
7220                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7221            ActivityInfo filterAi = filter.activity.info;
7222            for (int i=dest.size()-1; i>=0; i--) {
7223                ActivityInfo destAi = dest.get(i).activityInfo;
7224                if (destAi.name == filterAi.name
7225                        && destAi.packageName == filterAi.packageName) {
7226                    return false;
7227                }
7228            }
7229            return true;
7230        }
7231
7232        @Override
7233        protected ActivityIntentInfo[] newArray(int size) {
7234            return new ActivityIntentInfo[size];
7235        }
7236
7237        @Override
7238        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7239            if (!sUserManager.exists(userId)) return true;
7240            PackageParser.Package p = filter.activity.owner;
7241            if (p != null) {
7242                PackageSetting ps = (PackageSetting)p.mExtras;
7243                if (ps != null) {
7244                    // System apps are never considered stopped for purposes of
7245                    // filtering, because there may be no way for the user to
7246                    // actually re-launch them.
7247                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7248                            && ps.getStopped(userId);
7249                }
7250            }
7251            return false;
7252        }
7253
7254        @Override
7255        protected boolean isPackageForFilter(String packageName,
7256                PackageParser.ActivityIntentInfo info) {
7257            return packageName.equals(info.activity.owner.packageName);
7258        }
7259
7260        @Override
7261        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7262                int match, int userId) {
7263            if (!sUserManager.exists(userId)) return null;
7264            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7265                return null;
7266            }
7267            final PackageParser.Activity activity = info.activity;
7268            if (mSafeMode && (activity.info.applicationInfo.flags
7269                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7270                return null;
7271            }
7272            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7273            if (ps == null) {
7274                return null;
7275            }
7276            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7277                    ps.readUserState(userId), userId);
7278            if (ai == null) {
7279                return null;
7280            }
7281            final ResolveInfo res = new ResolveInfo();
7282            res.activityInfo = ai;
7283            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7284                res.filter = info;
7285            }
7286            res.priority = info.getPriority();
7287            res.preferredOrder = activity.owner.mPreferredOrder;
7288            //System.out.println("Result: " + res.activityInfo.className +
7289            //                   " = " + res.priority);
7290            res.match = match;
7291            res.isDefault = info.hasDefault;
7292            res.labelRes = info.labelRes;
7293            res.nonLocalizedLabel = info.nonLocalizedLabel;
7294            if (userNeedsBadging(userId)) {
7295                res.noResourceId = true;
7296            } else {
7297                res.icon = info.icon;
7298            }
7299            res.system = isSystemApp(res.activityInfo.applicationInfo);
7300            return res;
7301        }
7302
7303        @Override
7304        protected void sortResults(List<ResolveInfo> results) {
7305            Collections.sort(results, mResolvePrioritySorter);
7306        }
7307
7308        @Override
7309        protected void dumpFilter(PrintWriter out, String prefix,
7310                PackageParser.ActivityIntentInfo filter) {
7311            out.print(prefix); out.print(
7312                    Integer.toHexString(System.identityHashCode(filter.activity)));
7313                    out.print(' ');
7314                    filter.activity.printComponentShortName(out);
7315                    out.print(" filter ");
7316                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7317        }
7318
7319//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7320//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7321//            final List<ResolveInfo> retList = Lists.newArrayList();
7322//            while (i.hasNext()) {
7323//                final ResolveInfo resolveInfo = i.next();
7324//                if (isEnabledLP(resolveInfo.activityInfo)) {
7325//                    retList.add(resolveInfo);
7326//                }
7327//            }
7328//            return retList;
7329//        }
7330
7331        // Keys are String (activity class name), values are Activity.
7332        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7333                = new HashMap<ComponentName, PackageParser.Activity>();
7334        private int mFlags;
7335    }
7336
7337    private final class ServiceIntentResolver
7338            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7339        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7340                boolean defaultOnly, int userId) {
7341            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7342            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7343        }
7344
7345        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7346                int userId) {
7347            if (!sUserManager.exists(userId)) return null;
7348            mFlags = flags;
7349            return super.queryIntent(intent, resolvedType,
7350                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7351        }
7352
7353        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7354                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7355            if (!sUserManager.exists(userId)) return null;
7356            if (packageServices == null) {
7357                return null;
7358            }
7359            mFlags = flags;
7360            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7361            final int N = packageServices.size();
7362            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7363                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7364
7365            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7366            for (int i = 0; i < N; ++i) {
7367                intentFilters = packageServices.get(i).intents;
7368                if (intentFilters != null && intentFilters.size() > 0) {
7369                    PackageParser.ServiceIntentInfo[] array =
7370                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7371                    intentFilters.toArray(array);
7372                    listCut.add(array);
7373                }
7374            }
7375            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7376        }
7377
7378        public final void addService(PackageParser.Service s) {
7379            mServices.put(s.getComponentName(), s);
7380            if (DEBUG_SHOW_INFO) {
7381                Log.v(TAG, "  "
7382                        + (s.info.nonLocalizedLabel != null
7383                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7384                Log.v(TAG, "    Class=" + s.info.name);
7385            }
7386            final int NI = s.intents.size();
7387            int j;
7388            for (j=0; j<NI; j++) {
7389                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7390                if (DEBUG_SHOW_INFO) {
7391                    Log.v(TAG, "    IntentFilter:");
7392                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7393                }
7394                if (!intent.debugCheck()) {
7395                    Log.w(TAG, "==> For Service " + s.info.name);
7396                }
7397                addFilter(intent);
7398            }
7399        }
7400
7401        public final void removeService(PackageParser.Service s) {
7402            mServices.remove(s.getComponentName());
7403            if (DEBUG_SHOW_INFO) {
7404                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7405                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7406                Log.v(TAG, "    Class=" + s.info.name);
7407            }
7408            final int NI = s.intents.size();
7409            int j;
7410            for (j=0; j<NI; j++) {
7411                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7412                if (DEBUG_SHOW_INFO) {
7413                    Log.v(TAG, "    IntentFilter:");
7414                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7415                }
7416                removeFilter(intent);
7417            }
7418        }
7419
7420        @Override
7421        protected boolean allowFilterResult(
7422                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7423            ServiceInfo filterSi = filter.service.info;
7424            for (int i=dest.size()-1; i>=0; i--) {
7425                ServiceInfo destAi = dest.get(i).serviceInfo;
7426                if (destAi.name == filterSi.name
7427                        && destAi.packageName == filterSi.packageName) {
7428                    return false;
7429                }
7430            }
7431            return true;
7432        }
7433
7434        @Override
7435        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7436            return new PackageParser.ServiceIntentInfo[size];
7437        }
7438
7439        @Override
7440        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7441            if (!sUserManager.exists(userId)) return true;
7442            PackageParser.Package p = filter.service.owner;
7443            if (p != null) {
7444                PackageSetting ps = (PackageSetting)p.mExtras;
7445                if (ps != null) {
7446                    // System apps are never considered stopped for purposes of
7447                    // filtering, because there may be no way for the user to
7448                    // actually re-launch them.
7449                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7450                            && ps.getStopped(userId);
7451                }
7452            }
7453            return false;
7454        }
7455
7456        @Override
7457        protected boolean isPackageForFilter(String packageName,
7458                PackageParser.ServiceIntentInfo info) {
7459            return packageName.equals(info.service.owner.packageName);
7460        }
7461
7462        @Override
7463        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7464                int match, int userId) {
7465            if (!sUserManager.exists(userId)) return null;
7466            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7467            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7468                return null;
7469            }
7470            final PackageParser.Service service = info.service;
7471            if (mSafeMode && (service.info.applicationInfo.flags
7472                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7473                return null;
7474            }
7475            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7476            if (ps == null) {
7477                return null;
7478            }
7479            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7480                    ps.readUserState(userId), userId);
7481            if (si == null) {
7482                return null;
7483            }
7484            final ResolveInfo res = new ResolveInfo();
7485            res.serviceInfo = si;
7486            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7487                res.filter = filter;
7488            }
7489            res.priority = info.getPriority();
7490            res.preferredOrder = service.owner.mPreferredOrder;
7491            //System.out.println("Result: " + res.activityInfo.className +
7492            //                   " = " + res.priority);
7493            res.match = match;
7494            res.isDefault = info.hasDefault;
7495            res.labelRes = info.labelRes;
7496            res.nonLocalizedLabel = info.nonLocalizedLabel;
7497            res.icon = info.icon;
7498            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7499            return res;
7500        }
7501
7502        @Override
7503        protected void sortResults(List<ResolveInfo> results) {
7504            Collections.sort(results, mResolvePrioritySorter);
7505        }
7506
7507        @Override
7508        protected void dumpFilter(PrintWriter out, String prefix,
7509                PackageParser.ServiceIntentInfo filter) {
7510            out.print(prefix); out.print(
7511                    Integer.toHexString(System.identityHashCode(filter.service)));
7512                    out.print(' ');
7513                    filter.service.printComponentShortName(out);
7514                    out.print(" filter ");
7515                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7516        }
7517
7518//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7519//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7520//            final List<ResolveInfo> retList = Lists.newArrayList();
7521//            while (i.hasNext()) {
7522//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7523//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7524//                    retList.add(resolveInfo);
7525//                }
7526//            }
7527//            return retList;
7528//        }
7529
7530        // Keys are String (activity class name), values are Activity.
7531        private final HashMap<ComponentName, PackageParser.Service> mServices
7532                = new HashMap<ComponentName, PackageParser.Service>();
7533        private int mFlags;
7534    };
7535
7536    private final class ProviderIntentResolver
7537            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7538        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7539                boolean defaultOnly, int userId) {
7540            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7541            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7542        }
7543
7544        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7545                int userId) {
7546            if (!sUserManager.exists(userId))
7547                return null;
7548            mFlags = flags;
7549            return super.queryIntent(intent, resolvedType,
7550                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7551        }
7552
7553        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7554                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7555            if (!sUserManager.exists(userId))
7556                return null;
7557            if (packageProviders == null) {
7558                return null;
7559            }
7560            mFlags = flags;
7561            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7562            final int N = packageProviders.size();
7563            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7564                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7565
7566            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7567            for (int i = 0; i < N; ++i) {
7568                intentFilters = packageProviders.get(i).intents;
7569                if (intentFilters != null && intentFilters.size() > 0) {
7570                    PackageParser.ProviderIntentInfo[] array =
7571                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7572                    intentFilters.toArray(array);
7573                    listCut.add(array);
7574                }
7575            }
7576            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7577        }
7578
7579        public final void addProvider(PackageParser.Provider p) {
7580            if (mProviders.containsKey(p.getComponentName())) {
7581                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7582                return;
7583            }
7584
7585            mProviders.put(p.getComponentName(), p);
7586            if (DEBUG_SHOW_INFO) {
7587                Log.v(TAG, "  "
7588                        + (p.info.nonLocalizedLabel != null
7589                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7590                Log.v(TAG, "    Class=" + p.info.name);
7591            }
7592            final int NI = p.intents.size();
7593            int j;
7594            for (j = 0; j < NI; j++) {
7595                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7596                if (DEBUG_SHOW_INFO) {
7597                    Log.v(TAG, "    IntentFilter:");
7598                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7599                }
7600                if (!intent.debugCheck()) {
7601                    Log.w(TAG, "==> For Provider " + p.info.name);
7602                }
7603                addFilter(intent);
7604            }
7605        }
7606
7607        public final void removeProvider(PackageParser.Provider p) {
7608            mProviders.remove(p.getComponentName());
7609            if (DEBUG_SHOW_INFO) {
7610                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7611                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7612                Log.v(TAG, "    Class=" + p.info.name);
7613            }
7614            final int NI = p.intents.size();
7615            int j;
7616            for (j = 0; j < NI; j++) {
7617                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7618                if (DEBUG_SHOW_INFO) {
7619                    Log.v(TAG, "    IntentFilter:");
7620                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7621                }
7622                removeFilter(intent);
7623            }
7624        }
7625
7626        @Override
7627        protected boolean allowFilterResult(
7628                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7629            ProviderInfo filterPi = filter.provider.info;
7630            for (int i = dest.size() - 1; i >= 0; i--) {
7631                ProviderInfo destPi = dest.get(i).providerInfo;
7632                if (destPi.name == filterPi.name
7633                        && destPi.packageName == filterPi.packageName) {
7634                    return false;
7635                }
7636            }
7637            return true;
7638        }
7639
7640        @Override
7641        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7642            return new PackageParser.ProviderIntentInfo[size];
7643        }
7644
7645        @Override
7646        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7647            if (!sUserManager.exists(userId))
7648                return true;
7649            PackageParser.Package p = filter.provider.owner;
7650            if (p != null) {
7651                PackageSetting ps = (PackageSetting) p.mExtras;
7652                if (ps != null) {
7653                    // System apps are never considered stopped for purposes of
7654                    // filtering, because there may be no way for the user to
7655                    // actually re-launch them.
7656                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7657                            && ps.getStopped(userId);
7658                }
7659            }
7660            return false;
7661        }
7662
7663        @Override
7664        protected boolean isPackageForFilter(String packageName,
7665                PackageParser.ProviderIntentInfo info) {
7666            return packageName.equals(info.provider.owner.packageName);
7667        }
7668
7669        @Override
7670        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7671                int match, int userId) {
7672            if (!sUserManager.exists(userId))
7673                return null;
7674            final PackageParser.ProviderIntentInfo info = filter;
7675            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7676                return null;
7677            }
7678            final PackageParser.Provider provider = info.provider;
7679            if (mSafeMode && (provider.info.applicationInfo.flags
7680                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7681                return null;
7682            }
7683            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7684            if (ps == null) {
7685                return null;
7686            }
7687            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7688                    ps.readUserState(userId), userId);
7689            if (pi == null) {
7690                return null;
7691            }
7692            final ResolveInfo res = new ResolveInfo();
7693            res.providerInfo = pi;
7694            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7695                res.filter = filter;
7696            }
7697            res.priority = info.getPriority();
7698            res.preferredOrder = provider.owner.mPreferredOrder;
7699            res.match = match;
7700            res.isDefault = info.hasDefault;
7701            res.labelRes = info.labelRes;
7702            res.nonLocalizedLabel = info.nonLocalizedLabel;
7703            res.icon = info.icon;
7704            res.system = isSystemApp(res.providerInfo.applicationInfo);
7705            return res;
7706        }
7707
7708        @Override
7709        protected void sortResults(List<ResolveInfo> results) {
7710            Collections.sort(results, mResolvePrioritySorter);
7711        }
7712
7713        @Override
7714        protected void dumpFilter(PrintWriter out, String prefix,
7715                PackageParser.ProviderIntentInfo filter) {
7716            out.print(prefix);
7717            out.print(
7718                    Integer.toHexString(System.identityHashCode(filter.provider)));
7719            out.print(' ');
7720            filter.provider.printComponentShortName(out);
7721            out.print(" filter ");
7722            out.println(Integer.toHexString(System.identityHashCode(filter)));
7723        }
7724
7725        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7726                = new HashMap<ComponentName, PackageParser.Provider>();
7727        private int mFlags;
7728    };
7729
7730    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7731            new Comparator<ResolveInfo>() {
7732        public int compare(ResolveInfo r1, ResolveInfo r2) {
7733            int v1 = r1.priority;
7734            int v2 = r2.priority;
7735            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7736            if (v1 != v2) {
7737                return (v1 > v2) ? -1 : 1;
7738            }
7739            v1 = r1.preferredOrder;
7740            v2 = r2.preferredOrder;
7741            if (v1 != v2) {
7742                return (v1 > v2) ? -1 : 1;
7743            }
7744            if (r1.isDefault != r2.isDefault) {
7745                return r1.isDefault ? -1 : 1;
7746            }
7747            v1 = r1.match;
7748            v2 = r2.match;
7749            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7750            if (v1 != v2) {
7751                return (v1 > v2) ? -1 : 1;
7752            }
7753            if (r1.system != r2.system) {
7754                return r1.system ? -1 : 1;
7755            }
7756            return 0;
7757        }
7758    };
7759
7760    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7761            new Comparator<ProviderInfo>() {
7762        public int compare(ProviderInfo p1, ProviderInfo p2) {
7763            final int v1 = p1.initOrder;
7764            final int v2 = p2.initOrder;
7765            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7766        }
7767    };
7768
7769    static final void sendPackageBroadcast(String action, String pkg,
7770            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7771            int[] userIds) {
7772        IActivityManager am = ActivityManagerNative.getDefault();
7773        if (am != null) {
7774            try {
7775                if (userIds == null) {
7776                    userIds = am.getRunningUserIds();
7777                }
7778                for (int id : userIds) {
7779                    final Intent intent = new Intent(action,
7780                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7781                    if (extras != null) {
7782                        intent.putExtras(extras);
7783                    }
7784                    if (targetPkg != null) {
7785                        intent.setPackage(targetPkg);
7786                    }
7787                    // Modify the UID when posting to other users
7788                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7789                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7790                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7791                        intent.putExtra(Intent.EXTRA_UID, uid);
7792                    }
7793                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7794                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7795                    if (DEBUG_BROADCASTS) {
7796                        RuntimeException here = new RuntimeException("here");
7797                        here.fillInStackTrace();
7798                        Slog.d(TAG, "Sending to user " + id + ": "
7799                                + intent.toShortString(false, true, false, false)
7800                                + " " + intent.getExtras(), here);
7801                    }
7802                    am.broadcastIntent(null, intent, null, finishedReceiver,
7803                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7804                            finishedReceiver != null, false, id);
7805                }
7806            } catch (RemoteException ex) {
7807            }
7808        }
7809    }
7810
7811    /**
7812     * Check if the external storage media is available. This is true if there
7813     * is a mounted external storage medium or if the external storage is
7814     * emulated.
7815     */
7816    private boolean isExternalMediaAvailable() {
7817        return mMediaMounted || Environment.isExternalStorageEmulated();
7818    }
7819
7820    @Override
7821    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7822        // writer
7823        synchronized (mPackages) {
7824            if (!isExternalMediaAvailable()) {
7825                // If the external storage is no longer mounted at this point,
7826                // the caller may not have been able to delete all of this
7827                // packages files and can not delete any more.  Bail.
7828                return null;
7829            }
7830            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7831            if (lastPackage != null) {
7832                pkgs.remove(lastPackage);
7833            }
7834            if (pkgs.size() > 0) {
7835                return pkgs.get(0);
7836            }
7837        }
7838        return null;
7839    }
7840
7841    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7842        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7843                userId, andCode ? 1 : 0, packageName);
7844        if (mSystemReady) {
7845            msg.sendToTarget();
7846        } else {
7847            if (mPostSystemReadyMessages == null) {
7848                mPostSystemReadyMessages = new ArrayList<>();
7849            }
7850            mPostSystemReadyMessages.add(msg);
7851        }
7852    }
7853
7854    void startCleaningPackages() {
7855        // reader
7856        synchronized (mPackages) {
7857            if (!isExternalMediaAvailable()) {
7858                return;
7859            }
7860            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7861                return;
7862            }
7863        }
7864        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7865        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7866        IActivityManager am = ActivityManagerNative.getDefault();
7867        if (am != null) {
7868            try {
7869                am.startService(null, intent, null, UserHandle.USER_OWNER);
7870            } catch (RemoteException e) {
7871            }
7872        }
7873    }
7874
7875    @Override
7876    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7877            int installFlags, String installerPackageName, VerificationParams verificationParams,
7878            String packageAbiOverride) {
7879        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7880                packageAbiOverride, UserHandle.getCallingUserId());
7881    }
7882
7883    @Override
7884    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7885            int installFlags, String installerPackageName, VerificationParams verificationParams,
7886            String packageAbiOverride, int userId) {
7887        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
7888
7889        final int callingUid = Binder.getCallingUid();
7890        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
7891
7892        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7893            try {
7894                if (observer != null) {
7895                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7896                }
7897            } catch (RemoteException re) {
7898            }
7899            return;
7900        }
7901
7902        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
7903            installFlags |= PackageManager.INSTALL_FROM_ADB;
7904
7905        } else {
7906            // Caller holds INSTALL_PACKAGES permission, so we're less strict
7907            // about installerPackageName.
7908
7909            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
7910            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
7911        }
7912
7913        UserHandle user;
7914        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7915            user = UserHandle.ALL;
7916        } else {
7917            user = new UserHandle(userId);
7918        }
7919
7920        verificationParams.setInstallerUid(callingUid);
7921
7922        final File originFile = new File(originPath);
7923        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7924
7925        final Message msg = mHandler.obtainMessage(INIT_COPY);
7926        msg.obj = new InstallParams(origin, observer, installFlags,
7927                installerPackageName, verificationParams, user, packageAbiOverride);
7928        mHandler.sendMessage(msg);
7929    }
7930
7931    void installStage(String packageName, File stagedDir, String stagedCid,
7932            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7933            String installerPackageName, int installerUid, UserHandle user) {
7934        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7935                params.referrerUri, installerUid, null);
7936
7937        final OriginInfo origin;
7938        if (stagedDir != null) {
7939            origin = OriginInfo.fromStagedFile(stagedDir);
7940        } else {
7941            origin = OriginInfo.fromStagedContainer(stagedCid);
7942        }
7943
7944        final Message msg = mHandler.obtainMessage(INIT_COPY);
7945        msg.obj = new InstallParams(origin, observer, params.installFlags,
7946                installerPackageName, verifParams, user, params.abiOverride);
7947        mHandler.sendMessage(msg);
7948    }
7949
7950    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
7951        Bundle extras = new Bundle(1);
7952        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
7953
7954        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
7955                packageName, extras, null, null, new int[] {userId});
7956        try {
7957            IActivityManager am = ActivityManagerNative.getDefault();
7958            final boolean isSystem =
7959                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
7960            if (isSystem && am.isUserRunning(userId, false)) {
7961                // The just-installed/enabled app is bundled on the system, so presumed
7962                // to be able to run automatically without needing an explicit launch.
7963                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
7964                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
7965                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
7966                        .setPackage(packageName);
7967                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
7968                        android.app.AppOpsManager.OP_NONE, false, false, userId);
7969            }
7970        } catch (RemoteException e) {
7971            // shouldn't happen
7972            Slog.w(TAG, "Unable to bootstrap installed package", e);
7973        }
7974    }
7975
7976    @Override
7977    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
7978            int userId) {
7979        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
7980        PackageSetting pkgSetting;
7981        final int uid = Binder.getCallingUid();
7982        enforceCrossUserPermission(uid, userId, true, true,
7983                "setApplicationHiddenSetting for user " + userId);
7984
7985        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
7986            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
7987            return false;
7988        }
7989
7990        long callingId = Binder.clearCallingIdentity();
7991        try {
7992            boolean sendAdded = false;
7993            boolean sendRemoved = false;
7994            // writer
7995            synchronized (mPackages) {
7996                pkgSetting = mSettings.mPackages.get(packageName);
7997                if (pkgSetting == null) {
7998                    return false;
7999                }
8000                if (pkgSetting.getHidden(userId) != hidden) {
8001                    pkgSetting.setHidden(hidden, userId);
8002                    mSettings.writePackageRestrictionsLPr(userId);
8003                    if (hidden) {
8004                        sendRemoved = true;
8005                    } else {
8006                        sendAdded = true;
8007                    }
8008                }
8009            }
8010            if (sendAdded) {
8011                sendPackageAddedForUser(packageName, pkgSetting, userId);
8012                return true;
8013            }
8014            if (sendRemoved) {
8015                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8016                        "hiding pkg");
8017                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8018            }
8019        } finally {
8020            Binder.restoreCallingIdentity(callingId);
8021        }
8022        return false;
8023    }
8024
8025    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8026            int userId) {
8027        final PackageRemovedInfo info = new PackageRemovedInfo();
8028        info.removedPackage = packageName;
8029        info.removedUsers = new int[] {userId};
8030        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8031        info.sendBroadcast(false, false, false);
8032    }
8033
8034    /**
8035     * Returns true if application is not found or there was an error. Otherwise it returns
8036     * the hidden state of the package for the given user.
8037     */
8038    @Override
8039    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8040        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8041        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8042                false, "getApplicationHidden for user " + userId);
8043        PackageSetting pkgSetting;
8044        long callingId = Binder.clearCallingIdentity();
8045        try {
8046            // writer
8047            synchronized (mPackages) {
8048                pkgSetting = mSettings.mPackages.get(packageName);
8049                if (pkgSetting == null) {
8050                    return true;
8051                }
8052                return pkgSetting.getHidden(userId);
8053            }
8054        } finally {
8055            Binder.restoreCallingIdentity(callingId);
8056        }
8057    }
8058
8059    /**
8060     * @hide
8061     */
8062    @Override
8063    public int installExistingPackageAsUser(String packageName, int userId) {
8064        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8065                null);
8066        PackageSetting pkgSetting;
8067        final int uid = Binder.getCallingUid();
8068        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8069                + userId);
8070        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8071            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8072        }
8073
8074        long callingId = Binder.clearCallingIdentity();
8075        try {
8076            boolean sendAdded = false;
8077            Bundle extras = new Bundle(1);
8078
8079            // writer
8080            synchronized (mPackages) {
8081                pkgSetting = mSettings.mPackages.get(packageName);
8082                if (pkgSetting == null) {
8083                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8084                }
8085                if (!pkgSetting.getInstalled(userId)) {
8086                    pkgSetting.setInstalled(true, userId);
8087                    pkgSetting.setHidden(false, userId);
8088                    mSettings.writePackageRestrictionsLPr(userId);
8089                    sendAdded = true;
8090                }
8091            }
8092
8093            if (sendAdded) {
8094                sendPackageAddedForUser(packageName, pkgSetting, userId);
8095            }
8096        } finally {
8097            Binder.restoreCallingIdentity(callingId);
8098        }
8099
8100        return PackageManager.INSTALL_SUCCEEDED;
8101    }
8102
8103    boolean isUserRestricted(int userId, String restrictionKey) {
8104        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8105        if (restrictions.getBoolean(restrictionKey, false)) {
8106            Log.w(TAG, "User is restricted: " + restrictionKey);
8107            return true;
8108        }
8109        return false;
8110    }
8111
8112    @Override
8113    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8114        mContext.enforceCallingOrSelfPermission(
8115                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8116                "Only package verification agents can verify applications");
8117
8118        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8119        final PackageVerificationResponse response = new PackageVerificationResponse(
8120                verificationCode, Binder.getCallingUid());
8121        msg.arg1 = id;
8122        msg.obj = response;
8123        mHandler.sendMessage(msg);
8124    }
8125
8126    @Override
8127    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8128            long millisecondsToDelay) {
8129        mContext.enforceCallingOrSelfPermission(
8130                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8131                "Only package verification agents can extend verification timeouts");
8132
8133        final PackageVerificationState state = mPendingVerification.get(id);
8134        final PackageVerificationResponse response = new PackageVerificationResponse(
8135                verificationCodeAtTimeout, Binder.getCallingUid());
8136
8137        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8138            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8139        }
8140        if (millisecondsToDelay < 0) {
8141            millisecondsToDelay = 0;
8142        }
8143        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8144                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8145            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8146        }
8147
8148        if ((state != null) && !state.timeoutExtended()) {
8149            state.extendTimeout();
8150
8151            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8152            msg.arg1 = id;
8153            msg.obj = response;
8154            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8155        }
8156    }
8157
8158    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8159            int verificationCode, UserHandle user) {
8160        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8161        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8162        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8163        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8164        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8165
8166        mContext.sendBroadcastAsUser(intent, user,
8167                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8168    }
8169
8170    private ComponentName matchComponentForVerifier(String packageName,
8171            List<ResolveInfo> receivers) {
8172        ActivityInfo targetReceiver = null;
8173
8174        final int NR = receivers.size();
8175        for (int i = 0; i < NR; i++) {
8176            final ResolveInfo info = receivers.get(i);
8177            if (info.activityInfo == null) {
8178                continue;
8179            }
8180
8181            if (packageName.equals(info.activityInfo.packageName)) {
8182                targetReceiver = info.activityInfo;
8183                break;
8184            }
8185        }
8186
8187        if (targetReceiver == null) {
8188            return null;
8189        }
8190
8191        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8192    }
8193
8194    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8195            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8196        if (pkgInfo.verifiers.length == 0) {
8197            return null;
8198        }
8199
8200        final int N = pkgInfo.verifiers.length;
8201        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8202        for (int i = 0; i < N; i++) {
8203            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8204
8205            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8206                    receivers);
8207            if (comp == null) {
8208                continue;
8209            }
8210
8211            final int verifierUid = getUidForVerifier(verifierInfo);
8212            if (verifierUid == -1) {
8213                continue;
8214            }
8215
8216            if (DEBUG_VERIFY) {
8217                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8218                        + " with the correct signature");
8219            }
8220            sufficientVerifiers.add(comp);
8221            verificationState.addSufficientVerifier(verifierUid);
8222        }
8223
8224        return sufficientVerifiers;
8225    }
8226
8227    private int getUidForVerifier(VerifierInfo verifierInfo) {
8228        synchronized (mPackages) {
8229            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8230            if (pkg == null) {
8231                return -1;
8232            } else if (pkg.mSignatures.length != 1) {
8233                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8234                        + " has more than one signature; ignoring");
8235                return -1;
8236            }
8237
8238            /*
8239             * If the public key of the package's signature does not match
8240             * our expected public key, then this is a different package and
8241             * we should skip.
8242             */
8243
8244            final byte[] expectedPublicKey;
8245            try {
8246                final Signature verifierSig = pkg.mSignatures[0];
8247                final PublicKey publicKey = verifierSig.getPublicKey();
8248                expectedPublicKey = publicKey.getEncoded();
8249            } catch (CertificateException e) {
8250                return -1;
8251            }
8252
8253            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8254
8255            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8256                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8257                        + " does not have the expected public key; ignoring");
8258                return -1;
8259            }
8260
8261            return pkg.applicationInfo.uid;
8262        }
8263    }
8264
8265    @Override
8266    public void finishPackageInstall(int token) {
8267        enforceSystemOrRoot("Only the system is allowed to finish installs");
8268
8269        if (DEBUG_INSTALL) {
8270            Slog.v(TAG, "BM finishing package install for " + token);
8271        }
8272
8273        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8274        mHandler.sendMessage(msg);
8275    }
8276
8277    /**
8278     * Get the verification agent timeout.
8279     *
8280     * @return verification timeout in milliseconds
8281     */
8282    private long getVerificationTimeout() {
8283        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8284                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8285                DEFAULT_VERIFICATION_TIMEOUT);
8286    }
8287
8288    /**
8289     * Get the default verification agent response code.
8290     *
8291     * @return default verification response code
8292     */
8293    private int getDefaultVerificationResponse() {
8294        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8295                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8296                DEFAULT_VERIFICATION_RESPONSE);
8297    }
8298
8299    /**
8300     * Check whether or not package verification has been enabled.
8301     *
8302     * @return true if verification should be performed
8303     */
8304    private boolean isVerificationEnabled(int userId, int installFlags) {
8305        if (!DEFAULT_VERIFY_ENABLE) {
8306            return false;
8307        }
8308
8309        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8310
8311        // Check if installing from ADB
8312        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8313            // Do not run verification in a test harness environment
8314            if (ActivityManager.isRunningInTestHarness()) {
8315                return false;
8316            }
8317            if (ensureVerifyAppsEnabled) {
8318                return true;
8319            }
8320            // Check if the developer does not want package verification for ADB installs
8321            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8322                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8323                return false;
8324            }
8325        }
8326
8327        if (ensureVerifyAppsEnabled) {
8328            return true;
8329        }
8330
8331        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8332                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8333    }
8334
8335    /**
8336     * Get the "allow unknown sources" setting.
8337     *
8338     * @return the current "allow unknown sources" setting
8339     */
8340    private int getUnknownSourcesSettings() {
8341        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8342                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8343                -1);
8344    }
8345
8346    @Override
8347    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8348        final int uid = Binder.getCallingUid();
8349        // writer
8350        synchronized (mPackages) {
8351            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8352            if (targetPackageSetting == null) {
8353                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8354            }
8355
8356            PackageSetting installerPackageSetting;
8357            if (installerPackageName != null) {
8358                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8359                if (installerPackageSetting == null) {
8360                    throw new IllegalArgumentException("Unknown installer package: "
8361                            + installerPackageName);
8362                }
8363            } else {
8364                installerPackageSetting = null;
8365            }
8366
8367            Signature[] callerSignature;
8368            Object obj = mSettings.getUserIdLPr(uid);
8369            if (obj != null) {
8370                if (obj instanceof SharedUserSetting) {
8371                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8372                } else if (obj instanceof PackageSetting) {
8373                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8374                } else {
8375                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8376                }
8377            } else {
8378                throw new SecurityException("Unknown calling uid " + uid);
8379            }
8380
8381            // Verify: can't set installerPackageName to a package that is
8382            // not signed with the same cert as the caller.
8383            if (installerPackageSetting != null) {
8384                if (compareSignatures(callerSignature,
8385                        installerPackageSetting.signatures.mSignatures)
8386                        != PackageManager.SIGNATURE_MATCH) {
8387                    throw new SecurityException(
8388                            "Caller does not have same cert as new installer package "
8389                            + installerPackageName);
8390                }
8391            }
8392
8393            // Verify: if target already has an installer package, it must
8394            // be signed with the same cert as the caller.
8395            if (targetPackageSetting.installerPackageName != null) {
8396                PackageSetting setting = mSettings.mPackages.get(
8397                        targetPackageSetting.installerPackageName);
8398                // If the currently set package isn't valid, then it's always
8399                // okay to change it.
8400                if (setting != null) {
8401                    if (compareSignatures(callerSignature,
8402                            setting.signatures.mSignatures)
8403                            != PackageManager.SIGNATURE_MATCH) {
8404                        throw new SecurityException(
8405                                "Caller does not have same cert as old installer package "
8406                                + targetPackageSetting.installerPackageName);
8407                    }
8408                }
8409            }
8410
8411            // Okay!
8412            targetPackageSetting.installerPackageName = installerPackageName;
8413            scheduleWriteSettingsLocked();
8414        }
8415    }
8416
8417    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8418        // Queue up an async operation since the package installation may take a little while.
8419        mHandler.post(new Runnable() {
8420            public void run() {
8421                mHandler.removeCallbacks(this);
8422                 // Result object to be returned
8423                PackageInstalledInfo res = new PackageInstalledInfo();
8424                res.returnCode = currentStatus;
8425                res.uid = -1;
8426                res.pkg = null;
8427                res.removedInfo = new PackageRemovedInfo();
8428                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8429                    args.doPreInstall(res.returnCode);
8430                    synchronized (mInstallLock) {
8431                        installPackageLI(args, res);
8432                    }
8433                    args.doPostInstall(res.returnCode, res.uid);
8434                }
8435
8436                // A restore should be performed at this point if (a) the install
8437                // succeeded, (b) the operation is not an update, and (c) the new
8438                // package has not opted out of backup participation.
8439                final boolean update = res.removedInfo.removedPackage != null;
8440                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8441                boolean doRestore = !update
8442                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8443
8444                // Set up the post-install work request bookkeeping.  This will be used
8445                // and cleaned up by the post-install event handling regardless of whether
8446                // there's a restore pass performed.  Token values are >= 1.
8447                int token;
8448                if (mNextInstallToken < 0) mNextInstallToken = 1;
8449                token = mNextInstallToken++;
8450
8451                PostInstallData data = new PostInstallData(args, res);
8452                mRunningInstalls.put(token, data);
8453                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8454
8455                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8456                    // Pass responsibility to the Backup Manager.  It will perform a
8457                    // restore if appropriate, then pass responsibility back to the
8458                    // Package Manager to run the post-install observer callbacks
8459                    // and broadcasts.
8460                    IBackupManager bm = IBackupManager.Stub.asInterface(
8461                            ServiceManager.getService(Context.BACKUP_SERVICE));
8462                    if (bm != null) {
8463                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8464                                + " to BM for possible restore");
8465                        try {
8466                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8467                        } catch (RemoteException e) {
8468                            // can't happen; the backup manager is local
8469                        } catch (Exception e) {
8470                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8471                            doRestore = false;
8472                        }
8473                    } else {
8474                        Slog.e(TAG, "Backup Manager not found!");
8475                        doRestore = false;
8476                    }
8477                }
8478
8479                if (!doRestore) {
8480                    // No restore possible, or the Backup Manager was mysteriously not
8481                    // available -- just fire the post-install work request directly.
8482                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8483                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8484                    mHandler.sendMessage(msg);
8485                }
8486            }
8487        });
8488    }
8489
8490    private abstract class HandlerParams {
8491        private static final int MAX_RETRIES = 4;
8492
8493        /**
8494         * Number of times startCopy() has been attempted and had a non-fatal
8495         * error.
8496         */
8497        private int mRetries = 0;
8498
8499        /** User handle for the user requesting the information or installation. */
8500        private final UserHandle mUser;
8501
8502        HandlerParams(UserHandle user) {
8503            mUser = user;
8504        }
8505
8506        UserHandle getUser() {
8507            return mUser;
8508        }
8509
8510        final boolean startCopy() {
8511            boolean res;
8512            try {
8513                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8514
8515                if (++mRetries > MAX_RETRIES) {
8516                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8517                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8518                    handleServiceError();
8519                    return false;
8520                } else {
8521                    handleStartCopy();
8522                    res = true;
8523                }
8524            } catch (RemoteException e) {
8525                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8526                mHandler.sendEmptyMessage(MCS_RECONNECT);
8527                res = false;
8528            }
8529            handleReturnCode();
8530            return res;
8531        }
8532
8533        final void serviceError() {
8534            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8535            handleServiceError();
8536            handleReturnCode();
8537        }
8538
8539        abstract void handleStartCopy() throws RemoteException;
8540        abstract void handleServiceError();
8541        abstract void handleReturnCode();
8542    }
8543
8544    class MeasureParams extends HandlerParams {
8545        private final PackageStats mStats;
8546        private boolean mSuccess;
8547
8548        private final IPackageStatsObserver mObserver;
8549
8550        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8551            super(new UserHandle(stats.userHandle));
8552            mObserver = observer;
8553            mStats = stats;
8554        }
8555
8556        @Override
8557        public String toString() {
8558            return "MeasureParams{"
8559                + Integer.toHexString(System.identityHashCode(this))
8560                + " " + mStats.packageName + "}";
8561        }
8562
8563        @Override
8564        void handleStartCopy() throws RemoteException {
8565            synchronized (mInstallLock) {
8566                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8567            }
8568
8569            if (mSuccess) {
8570                final boolean mounted;
8571                if (Environment.isExternalStorageEmulated()) {
8572                    mounted = true;
8573                } else {
8574                    final String status = Environment.getExternalStorageState();
8575                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8576                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8577                }
8578
8579                if (mounted) {
8580                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8581
8582                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8583                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8584
8585                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8586                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8587
8588                    // Always subtract cache size, since it's a subdirectory
8589                    mStats.externalDataSize -= mStats.externalCacheSize;
8590
8591                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8592                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8593
8594                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8595                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8596                }
8597            }
8598        }
8599
8600        @Override
8601        void handleReturnCode() {
8602            if (mObserver != null) {
8603                try {
8604                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8605                } catch (RemoteException e) {
8606                    Slog.i(TAG, "Observer no longer exists.");
8607                }
8608            }
8609        }
8610
8611        @Override
8612        void handleServiceError() {
8613            Slog.e(TAG, "Could not measure application " + mStats.packageName
8614                            + " external storage");
8615        }
8616    }
8617
8618    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8619            throws RemoteException {
8620        long result = 0;
8621        for (File path : paths) {
8622            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8623        }
8624        return result;
8625    }
8626
8627    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8628        for (File path : paths) {
8629            try {
8630                mcs.clearDirectory(path.getAbsolutePath());
8631            } catch (RemoteException e) {
8632            }
8633        }
8634    }
8635
8636    static class OriginInfo {
8637        /**
8638         * Location where install is coming from, before it has been
8639         * copied/renamed into place. This could be a single monolithic APK
8640         * file, or a cluster directory. This location may be untrusted.
8641         */
8642        final File file;
8643        final String cid;
8644
8645        /**
8646         * Flag indicating that {@link #file} or {@link #cid} has already been
8647         * staged, meaning downstream users don't need to defensively copy the
8648         * contents.
8649         */
8650        final boolean staged;
8651
8652        /**
8653         * Flag indicating that {@link #file} or {@link #cid} is an already
8654         * installed app that is being moved.
8655         */
8656        final boolean existing;
8657
8658        final String resolvedPath;
8659        final File resolvedFile;
8660
8661        static OriginInfo fromNothing() {
8662            return new OriginInfo(null, null, false, false);
8663        }
8664
8665        static OriginInfo fromUntrustedFile(File file) {
8666            return new OriginInfo(file, null, false, false);
8667        }
8668
8669        static OriginInfo fromExistingFile(File file) {
8670            return new OriginInfo(file, null, false, true);
8671        }
8672
8673        static OriginInfo fromStagedFile(File file) {
8674            return new OriginInfo(file, null, true, false);
8675        }
8676
8677        static OriginInfo fromStagedContainer(String cid) {
8678            return new OriginInfo(null, cid, true, false);
8679        }
8680
8681        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8682            this.file = file;
8683            this.cid = cid;
8684            this.staged = staged;
8685            this.existing = existing;
8686
8687            if (cid != null) {
8688                resolvedPath = PackageHelper.getSdDir(cid);
8689                resolvedFile = new File(resolvedPath);
8690            } else if (file != null) {
8691                resolvedPath = file.getAbsolutePath();
8692                resolvedFile = file;
8693            } else {
8694                resolvedPath = null;
8695                resolvedFile = null;
8696            }
8697        }
8698    }
8699
8700    class InstallParams extends HandlerParams {
8701        final OriginInfo origin;
8702        final IPackageInstallObserver2 observer;
8703        int installFlags;
8704        final String installerPackageName;
8705        final VerificationParams verificationParams;
8706        private InstallArgs mArgs;
8707        private int mRet;
8708        final String packageAbiOverride;
8709
8710        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8711                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8712                String packageAbiOverride) {
8713            super(user);
8714            this.origin = origin;
8715            this.observer = observer;
8716            this.installFlags = installFlags;
8717            this.installerPackageName = installerPackageName;
8718            this.verificationParams = verificationParams;
8719            this.packageAbiOverride = packageAbiOverride;
8720        }
8721
8722        @Override
8723        public String toString() {
8724            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8725                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8726        }
8727
8728        public ManifestDigest getManifestDigest() {
8729            if (verificationParams == null) {
8730                return null;
8731            }
8732            return verificationParams.getManifestDigest();
8733        }
8734
8735        private int installLocationPolicy(PackageInfoLite pkgLite) {
8736            String packageName = pkgLite.packageName;
8737            int installLocation = pkgLite.installLocation;
8738            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8739            // reader
8740            synchronized (mPackages) {
8741                PackageParser.Package pkg = mPackages.get(packageName);
8742                if (pkg != null) {
8743                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8744                        // Check for downgrading.
8745                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8746                            if (pkgLite.versionCode < pkg.mVersionCode) {
8747                                Slog.w(TAG, "Can't install update of " + packageName
8748                                        + " update version " + pkgLite.versionCode
8749                                        + " is older than installed version "
8750                                        + pkg.mVersionCode);
8751                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8752                            }
8753                        }
8754                        // Check for updated system application.
8755                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8756                            if (onSd) {
8757                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8758                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8759                            }
8760                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8761                        } else {
8762                            if (onSd) {
8763                                // Install flag overrides everything.
8764                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8765                            }
8766                            // If current upgrade specifies particular preference
8767                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8768                                // Application explicitly specified internal.
8769                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8770                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8771                                // App explictly prefers external. Let policy decide
8772                            } else {
8773                                // Prefer previous location
8774                                if (isExternal(pkg)) {
8775                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8776                                }
8777                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8778                            }
8779                        }
8780                    } else {
8781                        // Invalid install. Return error code
8782                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8783                    }
8784                }
8785            }
8786            // All the special cases have been taken care of.
8787            // Return result based on recommended install location.
8788            if (onSd) {
8789                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8790            }
8791            return pkgLite.recommendedInstallLocation;
8792        }
8793
8794        /*
8795         * Invoke remote method to get package information and install
8796         * location values. Override install location based on default
8797         * policy if needed and then create install arguments based
8798         * on the install location.
8799         */
8800        public void handleStartCopy() throws RemoteException {
8801            int ret = PackageManager.INSTALL_SUCCEEDED;
8802
8803            // If we're already staged, we've firmly committed to an install location
8804            if (origin.staged) {
8805                if (origin.file != null) {
8806                    installFlags |= PackageManager.INSTALL_INTERNAL;
8807                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8808                } else if (origin.cid != null) {
8809                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8810                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8811                } else {
8812                    throw new IllegalStateException("Invalid stage location");
8813                }
8814            }
8815
8816            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8817            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8818
8819            PackageInfoLite pkgLite = null;
8820
8821            if (onInt && onSd) {
8822                // Check if both bits are set.
8823                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8824                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8825            } else {
8826                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8827                        packageAbiOverride);
8828
8829                /*
8830                 * If we have too little free space, try to free cache
8831                 * before giving up.
8832                 */
8833                if (!origin.staged && pkgLite.recommendedInstallLocation
8834                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8835                    // TODO: focus freeing disk space on the target device
8836                    final StorageManager storage = StorageManager.from(mContext);
8837                    final long lowThreshold = storage.getStorageLowBytes(
8838                            Environment.getDataDirectory());
8839
8840                    final long sizeBytes = mContainerService.calculateInstalledSize(
8841                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8842
8843                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8844                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8845                                installFlags, packageAbiOverride);
8846                    }
8847
8848                    /*
8849                     * The cache free must have deleted the file we
8850                     * downloaded to install.
8851                     *
8852                     * TODO: fix the "freeCache" call to not delete
8853                     *       the file we care about.
8854                     */
8855                    if (pkgLite.recommendedInstallLocation
8856                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8857                        pkgLite.recommendedInstallLocation
8858                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8859                    }
8860                }
8861            }
8862
8863            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8864                int loc = pkgLite.recommendedInstallLocation;
8865                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8866                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8867                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8868                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8869                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8870                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8871                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8872                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8873                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8874                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8875                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8876                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8877                } else {
8878                    // Override with defaults if needed.
8879                    loc = installLocationPolicy(pkgLite);
8880                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8881                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8882                    } else if (!onSd && !onInt) {
8883                        // Override install location with flags
8884                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8885                            // Set the flag to install on external media.
8886                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8887                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8888                        } else {
8889                            // Make sure the flag for installing on external
8890                            // media is unset
8891                            installFlags |= PackageManager.INSTALL_INTERNAL;
8892                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8893                        }
8894                    }
8895                }
8896            }
8897
8898            final InstallArgs args = createInstallArgs(this);
8899            mArgs = args;
8900
8901            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8902                 /*
8903                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8904                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8905                 */
8906                int userIdentifier = getUser().getIdentifier();
8907                if (userIdentifier == UserHandle.USER_ALL
8908                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8909                    userIdentifier = UserHandle.USER_OWNER;
8910                }
8911
8912                /*
8913                 * Determine if we have any installed package verifiers. If we
8914                 * do, then we'll defer to them to verify the packages.
8915                 */
8916                final int requiredUid = mRequiredVerifierPackage == null ? -1
8917                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8918                if (!origin.existing && requiredUid != -1
8919                        && isVerificationEnabled(userIdentifier, installFlags)) {
8920                    final Intent verification = new Intent(
8921                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8922                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8923                            PACKAGE_MIME_TYPE);
8924                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8925
8926                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8927                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8928                            0 /* TODO: Which userId? */);
8929
8930                    if (DEBUG_VERIFY) {
8931                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8932                                + verification.toString() + " with " + pkgLite.verifiers.length
8933                                + " optional verifiers");
8934                    }
8935
8936                    final int verificationId = mPendingVerificationToken++;
8937
8938                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8939
8940                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
8941                            installerPackageName);
8942
8943                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
8944                            installFlags);
8945
8946                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
8947                            pkgLite.packageName);
8948
8949                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
8950                            pkgLite.versionCode);
8951
8952                    if (verificationParams != null) {
8953                        if (verificationParams.getVerificationURI() != null) {
8954                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
8955                                 verificationParams.getVerificationURI());
8956                        }
8957                        if (verificationParams.getOriginatingURI() != null) {
8958                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
8959                                  verificationParams.getOriginatingURI());
8960                        }
8961                        if (verificationParams.getReferrer() != null) {
8962                            verification.putExtra(Intent.EXTRA_REFERRER,
8963                                  verificationParams.getReferrer());
8964                        }
8965                        if (verificationParams.getOriginatingUid() >= 0) {
8966                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
8967                                  verificationParams.getOriginatingUid());
8968                        }
8969                        if (verificationParams.getInstallerUid() >= 0) {
8970                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
8971                                  verificationParams.getInstallerUid());
8972                        }
8973                    }
8974
8975                    final PackageVerificationState verificationState = new PackageVerificationState(
8976                            requiredUid, args);
8977
8978                    mPendingVerification.append(verificationId, verificationState);
8979
8980                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
8981                            receivers, verificationState);
8982
8983                    /*
8984                     * If any sufficient verifiers were listed in the package
8985                     * manifest, attempt to ask them.
8986                     */
8987                    if (sufficientVerifiers != null) {
8988                        final int N = sufficientVerifiers.size();
8989                        if (N == 0) {
8990                            Slog.i(TAG, "Additional verifiers required, but none installed.");
8991                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
8992                        } else {
8993                            for (int i = 0; i < N; i++) {
8994                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
8995
8996                                final Intent sufficientIntent = new Intent(verification);
8997                                sufficientIntent.setComponent(verifierComponent);
8998
8999                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9000                            }
9001                        }
9002                    }
9003
9004                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9005                            mRequiredVerifierPackage, receivers);
9006                    if (ret == PackageManager.INSTALL_SUCCEEDED
9007                            && mRequiredVerifierPackage != null) {
9008                        /*
9009                         * Send the intent to the required verification agent,
9010                         * but only start the verification timeout after the
9011                         * target BroadcastReceivers have run.
9012                         */
9013                        verification.setComponent(requiredVerifierComponent);
9014                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9015                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9016                                new BroadcastReceiver() {
9017                                    @Override
9018                                    public void onReceive(Context context, Intent intent) {
9019                                        final Message msg = mHandler
9020                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9021                                        msg.arg1 = verificationId;
9022                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9023                                    }
9024                                }, null, 0, null, null);
9025
9026                        /*
9027                         * We don't want the copy to proceed until verification
9028                         * succeeds, so null out this field.
9029                         */
9030                        mArgs = null;
9031                    }
9032                } else {
9033                    /*
9034                     * No package verification is enabled, so immediately start
9035                     * the remote call to initiate copy using temporary file.
9036                     */
9037                    ret = args.copyApk(mContainerService, true);
9038                }
9039            }
9040
9041            mRet = ret;
9042        }
9043
9044        @Override
9045        void handleReturnCode() {
9046            // If mArgs is null, then MCS couldn't be reached. When it
9047            // reconnects, it will try again to install. At that point, this
9048            // will succeed.
9049            if (mArgs != null) {
9050                processPendingInstall(mArgs, mRet);
9051            }
9052        }
9053
9054        @Override
9055        void handleServiceError() {
9056            mArgs = createInstallArgs(this);
9057            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9058        }
9059
9060        public boolean isForwardLocked() {
9061            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9062        }
9063    }
9064
9065    /**
9066     * Used during creation of InstallArgs
9067     *
9068     * @param installFlags package installation flags
9069     * @return true if should be installed on external storage
9070     */
9071    private static boolean installOnSd(int installFlags) {
9072        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9073            return false;
9074        }
9075        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9076            return true;
9077        }
9078        return false;
9079    }
9080
9081    /**
9082     * Used during creation of InstallArgs
9083     *
9084     * @param installFlags package installation flags
9085     * @return true if should be installed as forward locked
9086     */
9087    private static boolean installForwardLocked(int installFlags) {
9088        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9089    }
9090
9091    private InstallArgs createInstallArgs(InstallParams params) {
9092        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
9093            return new AsecInstallArgs(params);
9094        } else {
9095            return new FileInstallArgs(params);
9096        }
9097    }
9098
9099    /**
9100     * Create args that describe an existing installed package. Typically used
9101     * when cleaning up old installs, or used as a move source.
9102     */
9103    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9104            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9105        final boolean isInAsec;
9106        if (installOnSd(installFlags)) {
9107            /* Apps on SD card are always in ASEC containers. */
9108            isInAsec = true;
9109        } else if (installForwardLocked(installFlags)
9110                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9111            /*
9112             * Forward-locked apps are only in ASEC containers if they're the
9113             * new style
9114             */
9115            isInAsec = true;
9116        } else {
9117            isInAsec = false;
9118        }
9119
9120        if (isInAsec) {
9121            return new AsecInstallArgs(codePath, instructionSets,
9122                    installOnSd(installFlags), installForwardLocked(installFlags));
9123        } else {
9124            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9125                    instructionSets);
9126        }
9127    }
9128
9129    static abstract class InstallArgs {
9130        /** @see InstallParams#origin */
9131        final OriginInfo origin;
9132
9133        final IPackageInstallObserver2 observer;
9134        // Always refers to PackageManager flags only
9135        final int installFlags;
9136        final String installerPackageName;
9137        final ManifestDigest manifestDigest;
9138        final UserHandle user;
9139        final String abiOverride;
9140
9141        // The list of instruction sets supported by this app. This is currently
9142        // only used during the rmdex() phase to clean up resources. We can get rid of this
9143        // if we move dex files under the common app path.
9144        /* nullable */ String[] instructionSets;
9145
9146        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9147                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9148                String[] instructionSets, String abiOverride) {
9149            this.origin = origin;
9150            this.installFlags = installFlags;
9151            this.observer = observer;
9152            this.installerPackageName = installerPackageName;
9153            this.manifestDigest = manifestDigest;
9154            this.user = user;
9155            this.instructionSets = instructionSets;
9156            this.abiOverride = abiOverride;
9157        }
9158
9159        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9160        abstract int doPreInstall(int status);
9161
9162        /**
9163         * Rename package into final resting place. All paths on the given
9164         * scanned package should be updated to reflect the rename.
9165         */
9166        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9167        abstract int doPostInstall(int status, int uid);
9168
9169        /** @see PackageSettingBase#codePathString */
9170        abstract String getCodePath();
9171        /** @see PackageSettingBase#resourcePathString */
9172        abstract String getResourcePath();
9173        abstract String getLegacyNativeLibraryPath();
9174
9175        // Need installer lock especially for dex file removal.
9176        abstract void cleanUpResourcesLI();
9177        abstract boolean doPostDeleteLI(boolean delete);
9178        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9179
9180        /**
9181         * Called before the source arguments are copied. This is used mostly
9182         * for MoveParams when it needs to read the source file to put it in the
9183         * destination.
9184         */
9185        int doPreCopy() {
9186            return PackageManager.INSTALL_SUCCEEDED;
9187        }
9188
9189        /**
9190         * Called after the source arguments are copied. This is used mostly for
9191         * MoveParams when it needs to read the source file to put it in the
9192         * destination.
9193         *
9194         * @return
9195         */
9196        int doPostCopy(int uid) {
9197            return PackageManager.INSTALL_SUCCEEDED;
9198        }
9199
9200        protected boolean isFwdLocked() {
9201            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9202        }
9203
9204        protected boolean isExternal() {
9205            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9206        }
9207
9208        UserHandle getUser() {
9209            return user;
9210        }
9211    }
9212
9213    /**
9214     * Logic to handle installation of non-ASEC applications, including copying
9215     * and renaming logic.
9216     */
9217    class FileInstallArgs extends InstallArgs {
9218        private File codeFile;
9219        private File resourceFile;
9220        private File legacyNativeLibraryPath;
9221
9222        // Example topology:
9223        // /data/app/com.example/base.apk
9224        // /data/app/com.example/split_foo.apk
9225        // /data/app/com.example/lib/arm/libfoo.so
9226        // /data/app/com.example/lib/arm64/libfoo.so
9227        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9228
9229        /** New install */
9230        FileInstallArgs(InstallParams params) {
9231            super(params.origin, params.observer, params.installFlags,
9232                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9233                    null /* instruction sets */, params.packageAbiOverride);
9234            if (isFwdLocked()) {
9235                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9236            }
9237        }
9238
9239        /** Existing install */
9240        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9241                String[] instructionSets) {
9242            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9243            this.codeFile = (codePath != null) ? new File(codePath) : null;
9244            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9245            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9246                    new File(legacyNativeLibraryPath) : null;
9247        }
9248
9249        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9250            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9251                    isFwdLocked(), abiOverride);
9252
9253            final StorageManager storage = StorageManager.from(mContext);
9254            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9255        }
9256
9257        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9258            if (origin.staged) {
9259                Slog.d(TAG, origin.file + " already staged; skipping copy");
9260                codeFile = origin.file;
9261                resourceFile = origin.file;
9262                return PackageManager.INSTALL_SUCCEEDED;
9263            }
9264
9265            try {
9266                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9267                codeFile = tempDir;
9268                resourceFile = tempDir;
9269            } catch (IOException e) {
9270                Slog.w(TAG, "Failed to create copy file: " + e);
9271                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9272            }
9273
9274            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9275                @Override
9276                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9277                    if (!FileUtils.isValidExtFilename(name)) {
9278                        throw new IllegalArgumentException("Invalid filename: " + name);
9279                    }
9280                    try {
9281                        final File file = new File(codeFile, name);
9282                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9283                                O_RDWR | O_CREAT, 0644);
9284                        Os.chmod(file.getAbsolutePath(), 0644);
9285                        return new ParcelFileDescriptor(fd);
9286                    } catch (ErrnoException e) {
9287                        throw new RemoteException("Failed to open: " + e.getMessage());
9288                    }
9289                }
9290            };
9291
9292            int ret = PackageManager.INSTALL_SUCCEEDED;
9293            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9294            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9295                Slog.e(TAG, "Failed to copy package");
9296                return ret;
9297            }
9298
9299            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9300            NativeLibraryHelper.Handle handle = null;
9301            try {
9302                handle = NativeLibraryHelper.Handle.create(codeFile);
9303                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9304                        abiOverride);
9305            } catch (IOException e) {
9306                Slog.e(TAG, "Copying native libraries failed", e);
9307                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9308            } finally {
9309                IoUtils.closeQuietly(handle);
9310            }
9311
9312            return ret;
9313        }
9314
9315        int doPreInstall(int status) {
9316            if (status != PackageManager.INSTALL_SUCCEEDED) {
9317                cleanUp();
9318            }
9319            return status;
9320        }
9321
9322        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9323            if (status != PackageManager.INSTALL_SUCCEEDED) {
9324                cleanUp();
9325                return false;
9326            } else {
9327                final File beforeCodeFile = codeFile;
9328                final File afterCodeFile = getNextCodePath(pkg.packageName);
9329
9330                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9331                try {
9332                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9333                } catch (ErrnoException e) {
9334                    Slog.d(TAG, "Failed to rename", e);
9335                    return false;
9336                }
9337
9338                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9339                    Slog.d(TAG, "Failed to restorecon");
9340                    return false;
9341                }
9342
9343                // Reflect the rename internally
9344                codeFile = afterCodeFile;
9345                resourceFile = afterCodeFile;
9346
9347                // Reflect the rename in scanned details
9348                pkg.codePath = afterCodeFile.getAbsolutePath();
9349                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9350                        pkg.baseCodePath);
9351                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9352                        pkg.splitCodePaths);
9353
9354                // Reflect the rename in app info
9355                pkg.applicationInfo.setCodePath(pkg.codePath);
9356                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9357                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9358                pkg.applicationInfo.setResourcePath(pkg.codePath);
9359                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9360                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9361
9362                return true;
9363            }
9364        }
9365
9366        int doPostInstall(int status, int uid) {
9367            if (status != PackageManager.INSTALL_SUCCEEDED) {
9368                cleanUp();
9369            }
9370            return status;
9371        }
9372
9373        @Override
9374        String getCodePath() {
9375            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9376        }
9377
9378        @Override
9379        String getResourcePath() {
9380            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9381        }
9382
9383        @Override
9384        String getLegacyNativeLibraryPath() {
9385            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9386        }
9387
9388        private boolean cleanUp() {
9389            if (codeFile == null || !codeFile.exists()) {
9390                return false;
9391            }
9392
9393            if (codeFile.isDirectory()) {
9394                FileUtils.deleteContents(codeFile);
9395            }
9396            codeFile.delete();
9397
9398            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9399                resourceFile.delete();
9400            }
9401
9402            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9403                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9404                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9405                }
9406                legacyNativeLibraryPath.delete();
9407            }
9408
9409            return true;
9410        }
9411
9412        void cleanUpResourcesLI() {
9413            // Try enumerating all code paths before deleting
9414            List<String> allCodePaths = Collections.EMPTY_LIST;
9415            if (codeFile != null && codeFile.exists()) {
9416                try {
9417                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9418                    allCodePaths = pkg.getAllCodePaths();
9419                } catch (PackageParserException e) {
9420                    // Ignored; we tried our best
9421                }
9422            }
9423
9424            cleanUp();
9425
9426            if (!allCodePaths.isEmpty()) {
9427                if (instructionSets == null) {
9428                    throw new IllegalStateException("instructionSet == null");
9429                }
9430                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9431                for (String codePath : allCodePaths) {
9432                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9433                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9434                        if (retCode < 0) {
9435                            Slog.w(TAG, "Couldn't remove dex file for package: "
9436                                    + " at location " + codePath + ", retcode=" + retCode);
9437                            // we don't consider this to be a failure of the core package deletion
9438                        }
9439                    }
9440                }
9441            }
9442        }
9443
9444        boolean doPostDeleteLI(boolean delete) {
9445            // XXX err, shouldn't we respect the delete flag?
9446            cleanUpResourcesLI();
9447            return true;
9448        }
9449    }
9450
9451    private boolean isAsecExternal(String cid) {
9452        final String asecPath = PackageHelper.getSdFilesystem(cid);
9453        return !asecPath.startsWith(mAsecInternalPath);
9454    }
9455
9456    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9457            PackageManagerException {
9458        if (copyRet < 0) {
9459            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9460                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9461                throw new PackageManagerException(copyRet, message);
9462            }
9463        }
9464    }
9465
9466    /**
9467     * Extract the MountService "container ID" from the full code path of an
9468     * .apk.
9469     */
9470    static String cidFromCodePath(String fullCodePath) {
9471        int eidx = fullCodePath.lastIndexOf("/");
9472        String subStr1 = fullCodePath.substring(0, eidx);
9473        int sidx = subStr1.lastIndexOf("/");
9474        return subStr1.substring(sidx+1, eidx);
9475    }
9476
9477    /**
9478     * Logic to handle installation of ASEC applications, including copying and
9479     * renaming logic.
9480     */
9481    class AsecInstallArgs extends InstallArgs {
9482        static final String RES_FILE_NAME = "pkg.apk";
9483        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9484
9485        String cid;
9486        String packagePath;
9487        String resourcePath;
9488        String legacyNativeLibraryDir;
9489
9490        /** New install */
9491        AsecInstallArgs(InstallParams params) {
9492            super(params.origin, params.observer, params.installFlags,
9493                    params.installerPackageName, params.getManifestDigest(),
9494                    params.getUser(), null /* instruction sets */,
9495                    params.packageAbiOverride);
9496        }
9497
9498        /** Existing install */
9499        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9500                        boolean isExternal, boolean isForwardLocked) {
9501            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9502                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9503                    instructionSets, null);
9504            // Hackily pretend we're still looking at a full code path
9505            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9506                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9507            }
9508
9509            // Extract cid from fullCodePath
9510            int eidx = fullCodePath.lastIndexOf("/");
9511            String subStr1 = fullCodePath.substring(0, eidx);
9512            int sidx = subStr1.lastIndexOf("/");
9513            cid = subStr1.substring(sidx+1, eidx);
9514            setMountPath(subStr1);
9515        }
9516
9517        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9518            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9519                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9520                    instructionSets, null);
9521            this.cid = cid;
9522            setMountPath(PackageHelper.getSdDir(cid));
9523        }
9524
9525        void createCopyFile() {
9526            cid = mInstallerService.allocateExternalStageCidLegacy();
9527        }
9528
9529        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9530            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9531                    abiOverride);
9532
9533            final File target;
9534            if (isExternal()) {
9535                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9536            } else {
9537                target = Environment.getDataDirectory();
9538            }
9539
9540            final StorageManager storage = StorageManager.from(mContext);
9541            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9542        }
9543
9544        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9545            if (origin.staged) {
9546                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9547                cid = origin.cid;
9548                setMountPath(PackageHelper.getSdDir(cid));
9549                return PackageManager.INSTALL_SUCCEEDED;
9550            }
9551
9552            if (temp) {
9553                createCopyFile();
9554            } else {
9555                /*
9556                 * Pre-emptively destroy the container since it's destroyed if
9557                 * copying fails due to it existing anyway.
9558                 */
9559                PackageHelper.destroySdDir(cid);
9560            }
9561
9562            final String newMountPath = imcs.copyPackageToContainer(
9563                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9564                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9565
9566            if (newMountPath != null) {
9567                setMountPath(newMountPath);
9568                return PackageManager.INSTALL_SUCCEEDED;
9569            } else {
9570                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9571            }
9572        }
9573
9574        @Override
9575        String getCodePath() {
9576            return packagePath;
9577        }
9578
9579        @Override
9580        String getResourcePath() {
9581            return resourcePath;
9582        }
9583
9584        @Override
9585        String getLegacyNativeLibraryPath() {
9586            return legacyNativeLibraryDir;
9587        }
9588
9589        int doPreInstall(int status) {
9590            if (status != PackageManager.INSTALL_SUCCEEDED) {
9591                // Destroy container
9592                PackageHelper.destroySdDir(cid);
9593            } else {
9594                boolean mounted = PackageHelper.isContainerMounted(cid);
9595                if (!mounted) {
9596                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9597                            Process.SYSTEM_UID);
9598                    if (newMountPath != null) {
9599                        setMountPath(newMountPath);
9600                    } else {
9601                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9602                    }
9603                }
9604            }
9605            return status;
9606        }
9607
9608        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9609            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9610            String newMountPath = null;
9611            if (PackageHelper.isContainerMounted(cid)) {
9612                // Unmount the container
9613                if (!PackageHelper.unMountSdDir(cid)) {
9614                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9615                    return false;
9616                }
9617            }
9618            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9619                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9620                        " which might be stale. Will try to clean up.");
9621                // Clean up the stale container and proceed to recreate.
9622                if (!PackageHelper.destroySdDir(newCacheId)) {
9623                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9624                    return false;
9625                }
9626                // Successfully cleaned up stale container. Try to rename again.
9627                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9628                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9629                            + " inspite of cleaning it up.");
9630                    return false;
9631                }
9632            }
9633            if (!PackageHelper.isContainerMounted(newCacheId)) {
9634                Slog.w(TAG, "Mounting container " + newCacheId);
9635                newMountPath = PackageHelper.mountSdDir(newCacheId,
9636                        getEncryptKey(), Process.SYSTEM_UID);
9637            } else {
9638                newMountPath = PackageHelper.getSdDir(newCacheId);
9639            }
9640            if (newMountPath == null) {
9641                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9642                return false;
9643            }
9644            Log.i(TAG, "Succesfully renamed " + cid +
9645                    " to " + newCacheId +
9646                    " at new path: " + newMountPath);
9647            cid = newCacheId;
9648
9649            final File beforeCodeFile = new File(packagePath);
9650            setMountPath(newMountPath);
9651            final File afterCodeFile = new File(packagePath);
9652
9653            // Reflect the rename in scanned details
9654            pkg.codePath = afterCodeFile.getAbsolutePath();
9655            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9656                    pkg.baseCodePath);
9657            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9658                    pkg.splitCodePaths);
9659
9660            // Reflect the rename in app info
9661            pkg.applicationInfo.setCodePath(pkg.codePath);
9662            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9663            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9664            pkg.applicationInfo.setResourcePath(pkg.codePath);
9665            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9666            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9667
9668            return true;
9669        }
9670
9671        private void setMountPath(String mountPath) {
9672            final File mountFile = new File(mountPath);
9673
9674            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9675            if (monolithicFile.exists()) {
9676                packagePath = monolithicFile.getAbsolutePath();
9677                if (isFwdLocked()) {
9678                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9679                } else {
9680                    resourcePath = packagePath;
9681                }
9682            } else {
9683                packagePath = mountFile.getAbsolutePath();
9684                resourcePath = packagePath;
9685            }
9686
9687            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9688        }
9689
9690        int doPostInstall(int status, int uid) {
9691            if (status != PackageManager.INSTALL_SUCCEEDED) {
9692                cleanUp();
9693            } else {
9694                final int groupOwner;
9695                final String protectedFile;
9696                if (isFwdLocked()) {
9697                    groupOwner = UserHandle.getSharedAppGid(uid);
9698                    protectedFile = RES_FILE_NAME;
9699                } else {
9700                    groupOwner = -1;
9701                    protectedFile = null;
9702                }
9703
9704                if (uid < Process.FIRST_APPLICATION_UID
9705                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9706                    Slog.e(TAG, "Failed to finalize " + cid);
9707                    PackageHelper.destroySdDir(cid);
9708                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9709                }
9710
9711                boolean mounted = PackageHelper.isContainerMounted(cid);
9712                if (!mounted) {
9713                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9714                }
9715            }
9716            return status;
9717        }
9718
9719        private void cleanUp() {
9720            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9721
9722            // Destroy secure container
9723            PackageHelper.destroySdDir(cid);
9724        }
9725
9726        private List<String> getAllCodePaths() {
9727            final File codeFile = new File(getCodePath());
9728            if (codeFile != null && codeFile.exists()) {
9729                try {
9730                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9731                    return pkg.getAllCodePaths();
9732                } catch (PackageParserException e) {
9733                    // Ignored; we tried our best
9734                }
9735            }
9736            return Collections.EMPTY_LIST;
9737        }
9738
9739        void cleanUpResourcesLI() {
9740            // Enumerate all code paths before deleting
9741            cleanUpResourcesLI(getAllCodePaths());
9742        }
9743
9744        private void cleanUpResourcesLI(List<String> allCodePaths) {
9745            cleanUp();
9746
9747            if (!allCodePaths.isEmpty()) {
9748                if (instructionSets == null) {
9749                    throw new IllegalStateException("instructionSet == null");
9750                }
9751                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9752                for (String codePath : allCodePaths) {
9753                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9754                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9755                        if (retCode < 0) {
9756                            Slog.w(TAG, "Couldn't remove dex file for package: "
9757                                    + " at location " + codePath + ", retcode=" + retCode);
9758                            // we don't consider this to be a failure of the core package deletion
9759                        }
9760                    }
9761                }
9762            }
9763        }
9764
9765        boolean matchContainer(String app) {
9766            if (cid.startsWith(app)) {
9767                return true;
9768            }
9769            return false;
9770        }
9771
9772        String getPackageName() {
9773            return getAsecPackageName(cid);
9774        }
9775
9776        boolean doPostDeleteLI(boolean delete) {
9777            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9778            final List<String> allCodePaths = getAllCodePaths();
9779            boolean mounted = PackageHelper.isContainerMounted(cid);
9780            if (mounted) {
9781                // Unmount first
9782                if (PackageHelper.unMountSdDir(cid)) {
9783                    mounted = false;
9784                }
9785            }
9786            if (!mounted && delete) {
9787                cleanUpResourcesLI(allCodePaths);
9788            }
9789            return !mounted;
9790        }
9791
9792        @Override
9793        int doPreCopy() {
9794            if (isFwdLocked()) {
9795                if (!PackageHelper.fixSdPermissions(cid,
9796                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9797                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9798                }
9799            }
9800
9801            return PackageManager.INSTALL_SUCCEEDED;
9802        }
9803
9804        @Override
9805        int doPostCopy(int uid) {
9806            if (isFwdLocked()) {
9807                if (uid < Process.FIRST_APPLICATION_UID
9808                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9809                                RES_FILE_NAME)) {
9810                    Slog.e(TAG, "Failed to finalize " + cid);
9811                    PackageHelper.destroySdDir(cid);
9812                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9813                }
9814            }
9815
9816            return PackageManager.INSTALL_SUCCEEDED;
9817        }
9818    }
9819
9820    static String getAsecPackageName(String packageCid) {
9821        int idx = packageCid.lastIndexOf("-");
9822        if (idx == -1) {
9823            return packageCid;
9824        }
9825        return packageCid.substring(0, idx);
9826    }
9827
9828    // Utility method used to create code paths based on package name and available index.
9829    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9830        String idxStr = "";
9831        int idx = 1;
9832        // Fall back to default value of idx=1 if prefix is not
9833        // part of oldCodePath
9834        if (oldCodePath != null) {
9835            String subStr = oldCodePath;
9836            // Drop the suffix right away
9837            if (suffix != null && subStr.endsWith(suffix)) {
9838                subStr = subStr.substring(0, subStr.length() - suffix.length());
9839            }
9840            // If oldCodePath already contains prefix find out the
9841            // ending index to either increment or decrement.
9842            int sidx = subStr.lastIndexOf(prefix);
9843            if (sidx != -1) {
9844                subStr = subStr.substring(sidx + prefix.length());
9845                if (subStr != null) {
9846                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9847                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9848                    }
9849                    try {
9850                        idx = Integer.parseInt(subStr);
9851                        if (idx <= 1) {
9852                            idx++;
9853                        } else {
9854                            idx--;
9855                        }
9856                    } catch(NumberFormatException e) {
9857                    }
9858                }
9859            }
9860        }
9861        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9862        return prefix + idxStr;
9863    }
9864
9865    private File getNextCodePath(String packageName) {
9866        int suffix = 1;
9867        File result;
9868        do {
9869            result = new File(mAppInstallDir, packageName + "-" + suffix);
9870            suffix++;
9871        } while (result.exists());
9872        return result;
9873    }
9874
9875    // Utility method used to ignore ADD/REMOVE events
9876    // by directory observer.
9877    private static boolean ignoreCodePath(String fullPathStr) {
9878        String apkName = deriveCodePathName(fullPathStr);
9879        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9880        if (idx != -1 && ((idx+1) < apkName.length())) {
9881            // Make sure the package ends with a numeral
9882            String version = apkName.substring(idx+1);
9883            try {
9884                Integer.parseInt(version);
9885                return true;
9886            } catch (NumberFormatException e) {}
9887        }
9888        return false;
9889    }
9890
9891    // Utility method that returns the relative package path with respect
9892    // to the installation directory. Like say for /data/data/com.test-1.apk
9893    // string com.test-1 is returned.
9894    static String deriveCodePathName(String codePath) {
9895        if (codePath == null) {
9896            return null;
9897        }
9898        final File codeFile = new File(codePath);
9899        final String name = codeFile.getName();
9900        if (codeFile.isDirectory()) {
9901            return name;
9902        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9903            final int lastDot = name.lastIndexOf('.');
9904            return name.substring(0, lastDot);
9905        } else {
9906            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9907            return null;
9908        }
9909    }
9910
9911    class PackageInstalledInfo {
9912        String name;
9913        int uid;
9914        // The set of users that originally had this package installed.
9915        int[] origUsers;
9916        // The set of users that now have this package installed.
9917        int[] newUsers;
9918        PackageParser.Package pkg;
9919        int returnCode;
9920        String returnMsg;
9921        PackageRemovedInfo removedInfo;
9922
9923        public void setError(int code, String msg) {
9924            returnCode = code;
9925            returnMsg = msg;
9926            Slog.w(TAG, msg);
9927        }
9928
9929        public void setError(String msg, PackageParserException e) {
9930            returnCode = e.error;
9931            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9932            Slog.w(TAG, msg, e);
9933        }
9934
9935        public void setError(String msg, PackageManagerException e) {
9936            returnCode = e.error;
9937            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9938            Slog.w(TAG, msg, e);
9939        }
9940
9941        // In some error cases we want to convey more info back to the observer
9942        String origPackage;
9943        String origPermission;
9944    }
9945
9946    /*
9947     * Install a non-existing package.
9948     */
9949    private void installNewPackageLI(PackageParser.Package pkg,
9950            int parseFlags, int scanFlags, UserHandle user,
9951            String installerPackageName, PackageInstalledInfo res) {
9952        // Remember this for later, in case we need to rollback this install
9953        String pkgName = pkg.packageName;
9954
9955        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
9956        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
9957        synchronized(mPackages) {
9958            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
9959                // A package with the same name is already installed, though
9960                // it has been renamed to an older name.  The package we
9961                // are trying to install should be installed as an update to
9962                // the existing one, but that has not been requested, so bail.
9963                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9964                        + " without first uninstalling package running as "
9965                        + mSettings.mRenamedPackages.get(pkgName));
9966                return;
9967            }
9968            if (mPackages.containsKey(pkgName)) {
9969                // Don't allow installation over an existing package with the same name.
9970                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
9971                        + " without first uninstalling.");
9972                return;
9973            }
9974        }
9975
9976        try {
9977            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
9978                    System.currentTimeMillis(), user);
9979
9980            updateSettingsLI(newPackage, installerPackageName, null, null, res);
9981            // delete the partially installed application. the data directory will have to be
9982            // restored if it was already existing
9983            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
9984                // remove package from internal structures.  Note that we want deletePackageX to
9985                // delete the package data and cache directories that it created in
9986                // scanPackageLocked, unless those directories existed before we even tried to
9987                // install.
9988                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
9989                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
9990                                res.removedInfo, true);
9991            }
9992
9993        } catch (PackageManagerException e) {
9994            res.setError("Package couldn't be installed in " + pkg.codePath, e);
9995        }
9996    }
9997
9998    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
9999        // Upgrade keysets are being used.  Determine if new package has a superset of the
10000        // required keys.
10001        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10002        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10003        for (int i = 0; i < upgradeKeySets.length; i++) {
10004            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10005            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10006                return true;
10007            }
10008        }
10009        return false;
10010    }
10011
10012    private void replacePackageLI(PackageParser.Package pkg,
10013            int parseFlags, int scanFlags, UserHandle user,
10014            String installerPackageName, PackageInstalledInfo res) {
10015        PackageParser.Package oldPackage;
10016        String pkgName = pkg.packageName;
10017        int[] allUsers;
10018        boolean[] perUserInstalled;
10019
10020        // First find the old package info and check signatures
10021        synchronized(mPackages) {
10022            oldPackage = mPackages.get(pkgName);
10023            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10024            PackageSetting ps = mSettings.mPackages.get(pkgName);
10025            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10026                // default to original signature matching
10027                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10028                    != PackageManager.SIGNATURE_MATCH) {
10029                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10030                            "New package has a different signature: " + pkgName);
10031                    return;
10032                }
10033            } else {
10034                if(!checkUpgradeKeySetLP(ps, pkg)) {
10035                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10036                            "New package not signed by keys specified by upgrade-keysets: "
10037                            + pkgName);
10038                    return;
10039                }
10040            }
10041
10042            // In case of rollback, remember per-user/profile install state
10043            allUsers = sUserManager.getUserIds();
10044            perUserInstalled = new boolean[allUsers.length];
10045            for (int i = 0; i < allUsers.length; i++) {
10046                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10047            }
10048        }
10049
10050        boolean sysPkg = (isSystemApp(oldPackage));
10051        if (sysPkg) {
10052            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10053                    user, allUsers, perUserInstalled, installerPackageName, res);
10054        } else {
10055            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10056                    user, allUsers, perUserInstalled, installerPackageName, res);
10057        }
10058    }
10059
10060    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10061            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10062            int[] allUsers, boolean[] perUserInstalled,
10063            String installerPackageName, PackageInstalledInfo res) {
10064        String pkgName = deletedPackage.packageName;
10065        boolean deletedPkg = true;
10066        boolean updatedSettings = false;
10067
10068        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10069                + deletedPackage);
10070        long origUpdateTime;
10071        if (pkg.mExtras != null) {
10072            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10073        } else {
10074            origUpdateTime = 0;
10075        }
10076
10077        // First delete the existing package while retaining the data directory
10078        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10079                res.removedInfo, true)) {
10080            // If the existing package wasn't successfully deleted
10081            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10082            deletedPkg = false;
10083        } else {
10084            // Successfully deleted the old package; proceed with replace.
10085
10086            // If deleted package lived in a container, give users a chance to
10087            // relinquish resources before killing.
10088            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
10089                if (DEBUG_INSTALL) {
10090                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10091                }
10092                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10093                final ArrayList<String> pkgList = new ArrayList<String>(1);
10094                pkgList.add(deletedPackage.applicationInfo.packageName);
10095                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10096            }
10097
10098            deleteCodeCacheDirsLI(pkgName);
10099            try {
10100                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10101                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10102                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10103                updatedSettings = true;
10104            } catch (PackageManagerException e) {
10105                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10106            }
10107        }
10108
10109        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10110            // remove package from internal structures.  Note that we want deletePackageX to
10111            // delete the package data and cache directories that it created in
10112            // scanPackageLocked, unless those directories existed before we even tried to
10113            // install.
10114            if(updatedSettings) {
10115                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10116                deletePackageLI(
10117                        pkgName, null, true, allUsers, perUserInstalled,
10118                        PackageManager.DELETE_KEEP_DATA,
10119                                res.removedInfo, true);
10120            }
10121            // Since we failed to install the new package we need to restore the old
10122            // package that we deleted.
10123            if (deletedPkg) {
10124                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10125                File restoreFile = new File(deletedPackage.codePath);
10126                // Parse old package
10127                boolean oldOnSd = isExternal(deletedPackage);
10128                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10129                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10130                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10131                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10132                try {
10133                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10134                } catch (PackageManagerException e) {
10135                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10136                            + e.getMessage());
10137                    return;
10138                }
10139                // Restore of old package succeeded. Update permissions.
10140                // writer
10141                synchronized (mPackages) {
10142                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10143                            UPDATE_PERMISSIONS_ALL);
10144                    // can downgrade to reader
10145                    mSettings.writeLPr();
10146                }
10147                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10148            }
10149        }
10150    }
10151
10152    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10153            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10154            int[] allUsers, boolean[] perUserInstalled,
10155            String installerPackageName, PackageInstalledInfo res) {
10156        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10157                + ", old=" + deletedPackage);
10158        boolean disabledSystem = false;
10159        boolean updatedSettings = false;
10160        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10161        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10162            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10163        }
10164        String packageName = deletedPackage.packageName;
10165        if (packageName == null) {
10166            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10167                    "Attempt to delete null packageName.");
10168            return;
10169        }
10170        PackageParser.Package oldPkg;
10171        PackageSetting oldPkgSetting;
10172        // reader
10173        synchronized (mPackages) {
10174            oldPkg = mPackages.get(packageName);
10175            oldPkgSetting = mSettings.mPackages.get(packageName);
10176            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10177                    (oldPkgSetting == null)) {
10178                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10179                        "Couldn't find package:" + packageName + " information");
10180                return;
10181            }
10182        }
10183
10184        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10185
10186        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10187        res.removedInfo.removedPackage = packageName;
10188        // Remove existing system package
10189        removePackageLI(oldPkgSetting, true);
10190        // writer
10191        synchronized (mPackages) {
10192            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10193            if (!disabledSystem && deletedPackage != null) {
10194                // We didn't need to disable the .apk as a current system package,
10195                // which means we are replacing another update that is already
10196                // installed.  We need to make sure to delete the older one's .apk.
10197                res.removedInfo.args = createInstallArgsForExisting(0,
10198                        deletedPackage.applicationInfo.getCodePath(),
10199                        deletedPackage.applicationInfo.getResourcePath(),
10200                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10201                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10202            } else {
10203                res.removedInfo.args = null;
10204            }
10205        }
10206
10207        // Successfully disabled the old package. Now proceed with re-installation
10208        deleteCodeCacheDirsLI(packageName);
10209
10210        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10211        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10212
10213        PackageParser.Package newPackage = null;
10214        try {
10215            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10216            if (newPackage.mExtras != null) {
10217                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10218                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10219                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10220
10221                // is the update attempting to change shared user? that isn't going to work...
10222                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10223                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10224                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10225                            + " to " + newPkgSetting.sharedUser);
10226                    updatedSettings = true;
10227                }
10228            }
10229
10230            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10231                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10232                updatedSettings = true;
10233            }
10234
10235        } catch (PackageManagerException e) {
10236            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10237        }
10238
10239        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10240            // Re installation failed. Restore old information
10241            // Remove new pkg information
10242            if (newPackage != null) {
10243                removeInstalledPackageLI(newPackage, true);
10244            }
10245            // Add back the old system package
10246            try {
10247                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10248            } catch (PackageManagerException e) {
10249                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10250            }
10251            // Restore the old system information in Settings
10252            synchronized (mPackages) {
10253                if (disabledSystem) {
10254                    mSettings.enableSystemPackageLPw(packageName);
10255                }
10256                if (updatedSettings) {
10257                    mSettings.setInstallerPackageName(packageName,
10258                            oldPkgSetting.installerPackageName);
10259                }
10260                mSettings.writeLPr();
10261            }
10262        }
10263    }
10264
10265    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10266            int[] allUsers, boolean[] perUserInstalled,
10267            PackageInstalledInfo res) {
10268        String pkgName = newPackage.packageName;
10269        synchronized (mPackages) {
10270            //write settings. the installStatus will be incomplete at this stage.
10271            //note that the new package setting would have already been
10272            //added to mPackages. It hasn't been persisted yet.
10273            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10274            mSettings.writeLPr();
10275        }
10276
10277        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10278
10279        synchronized (mPackages) {
10280            updatePermissionsLPw(newPackage.packageName, newPackage,
10281                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10282                            ? UPDATE_PERMISSIONS_ALL : 0));
10283            // For system-bundled packages, we assume that installing an upgraded version
10284            // of the package implies that the user actually wants to run that new code,
10285            // so we enable the package.
10286            if (isSystemApp(newPackage)) {
10287                // NB: implicit assumption that system package upgrades apply to all users
10288                if (DEBUG_INSTALL) {
10289                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10290                }
10291                PackageSetting ps = mSettings.mPackages.get(pkgName);
10292                if (ps != null) {
10293                    if (res.origUsers != null) {
10294                        for (int userHandle : res.origUsers) {
10295                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10296                                    userHandle, installerPackageName);
10297                        }
10298                    }
10299                    // Also convey the prior install/uninstall state
10300                    if (allUsers != null && perUserInstalled != null) {
10301                        for (int i = 0; i < allUsers.length; i++) {
10302                            if (DEBUG_INSTALL) {
10303                                Slog.d(TAG, "    user " + allUsers[i]
10304                                        + " => " + perUserInstalled[i]);
10305                            }
10306                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10307                        }
10308                        // these install state changes will be persisted in the
10309                        // upcoming call to mSettings.writeLPr().
10310                    }
10311                }
10312            }
10313            res.name = pkgName;
10314            res.uid = newPackage.applicationInfo.uid;
10315            res.pkg = newPackage;
10316            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10317            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10318            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10319            //to update install status
10320            mSettings.writeLPr();
10321        }
10322    }
10323
10324    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10325        final int installFlags = args.installFlags;
10326        String installerPackageName = args.installerPackageName;
10327        File tmpPackageFile = new File(args.getCodePath());
10328        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10329        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10330        boolean replace = false;
10331        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10332        // Result object to be returned
10333        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10334
10335        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10336        // Retrieve PackageSettings and parse package
10337        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10338                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10339                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10340        PackageParser pp = new PackageParser();
10341        pp.setSeparateProcesses(mSeparateProcesses);
10342        pp.setDisplayMetrics(mMetrics);
10343
10344        final PackageParser.Package pkg;
10345        try {
10346            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10347        } catch (PackageParserException e) {
10348            res.setError("Failed parse during installPackageLI", e);
10349            return;
10350        }
10351
10352        // Mark that we have an install time CPU ABI override.
10353        pkg.cpuAbiOverride = args.abiOverride;
10354
10355        String pkgName = res.name = pkg.packageName;
10356        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10357            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10358                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10359                return;
10360            }
10361        }
10362
10363        try {
10364            pp.collectCertificates(pkg, parseFlags);
10365            pp.collectManifestDigest(pkg);
10366        } catch (PackageParserException e) {
10367            res.setError("Failed collect during installPackageLI", e);
10368            return;
10369        }
10370
10371        /* If the installer passed in a manifest digest, compare it now. */
10372        if (args.manifestDigest != null) {
10373            if (DEBUG_INSTALL) {
10374                final String parsedManifest = pkg.manifestDigest == null ? "null"
10375                        : pkg.manifestDigest.toString();
10376                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10377                        + parsedManifest);
10378            }
10379
10380            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10381                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10382                return;
10383            }
10384        } else if (DEBUG_INSTALL) {
10385            final String parsedManifest = pkg.manifestDigest == null
10386                    ? "null" : pkg.manifestDigest.toString();
10387            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10388        }
10389
10390        // Get rid of all references to package scan path via parser.
10391        pp = null;
10392        String oldCodePath = null;
10393        boolean systemApp = false;
10394        synchronized (mPackages) {
10395            // Check whether the newly-scanned package wants to define an already-defined perm
10396            int N = pkg.permissions.size();
10397            for (int i = N-1; i >= 0; i--) {
10398                PackageParser.Permission perm = pkg.permissions.get(i);
10399                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10400                if (bp != null) {
10401                    // If the defining package is signed with our cert, it's okay.  This
10402                    // also includes the "updating the same package" case, of course.
10403                    // "updating same package" could also involve key-rotation.
10404                    final boolean sigsOk;
10405                    if (!bp.sourcePackage.equals(pkg.packageName)
10406                            || !(bp.packageSetting instanceof PackageSetting)
10407                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10408                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10409                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10410                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10411                    } else {
10412                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10413                    }
10414                    if (!sigsOk) {
10415                        // If the owning package is the system itself, we log but allow
10416                        // install to proceed; we fail the install on all other permission
10417                        // redefinitions.
10418                        if (!bp.sourcePackage.equals("android")) {
10419                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10420                                    + pkg.packageName + " attempting to redeclare permission "
10421                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10422                            res.origPermission = perm.info.name;
10423                            res.origPackage = bp.sourcePackage;
10424                            return;
10425                        } else {
10426                            Slog.w(TAG, "Package " + pkg.packageName
10427                                    + " attempting to redeclare system permission "
10428                                    + perm.info.name + "; ignoring new declaration");
10429                            pkg.permissions.remove(i);
10430                        }
10431                    }
10432                }
10433            }
10434
10435            // Check if installing already existing package
10436            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10437                String oldName = mSettings.mRenamedPackages.get(pkgName);
10438                if (pkg.mOriginalPackages != null
10439                        && pkg.mOriginalPackages.contains(oldName)
10440                        && mPackages.containsKey(oldName)) {
10441                    // This package is derived from an original package,
10442                    // and this device has been updating from that original
10443                    // name.  We must continue using the original name, so
10444                    // rename the new package here.
10445                    pkg.setPackageName(oldName);
10446                    pkgName = pkg.packageName;
10447                    replace = true;
10448                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10449                            + oldName + " pkgName=" + pkgName);
10450                } else if (mPackages.containsKey(pkgName)) {
10451                    // This package, under its official name, already exists
10452                    // on the device; we should replace it.
10453                    replace = true;
10454                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10455                }
10456            }
10457            PackageSetting ps = mSettings.mPackages.get(pkgName);
10458            if (ps != null) {
10459                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10460                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10461                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10462                    systemApp = (ps.pkg.applicationInfo.flags &
10463                            ApplicationInfo.FLAG_SYSTEM) != 0;
10464                }
10465                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10466            }
10467        }
10468
10469        if (systemApp && onSd) {
10470            // Disable updates to system apps on sdcard
10471            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10472                    "Cannot install updates to system apps on sdcard");
10473            return;
10474        }
10475
10476        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10477            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10478            return;
10479        }
10480
10481        if (replace) {
10482            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10483                    installerPackageName, res);
10484        } else {
10485            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10486                    args.user, installerPackageName, res);
10487        }
10488        synchronized (mPackages) {
10489            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10490            if (ps != null) {
10491                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10492            }
10493        }
10494    }
10495
10496    private static boolean isForwardLocked(PackageParser.Package pkg) {
10497        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10498    }
10499
10500    private static boolean isForwardLocked(ApplicationInfo info) {
10501        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10502    }
10503
10504    private boolean isForwardLocked(PackageSetting ps) {
10505        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10506    }
10507
10508    private static boolean isMultiArch(PackageSetting ps) {
10509        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10510    }
10511
10512    private static boolean isMultiArch(ApplicationInfo info) {
10513        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10514    }
10515
10516    private static boolean isExternal(PackageParser.Package pkg) {
10517        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10518    }
10519
10520    private static boolean isExternal(PackageSetting ps) {
10521        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10522    }
10523
10524    private static boolean isExternal(ApplicationInfo info) {
10525        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10526    }
10527
10528    private static boolean isSystemApp(PackageParser.Package pkg) {
10529        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10530    }
10531
10532    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10533        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10534    }
10535
10536    private static boolean isSystemApp(ApplicationInfo info) {
10537        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10538    }
10539
10540    private static boolean isSystemApp(PackageSetting ps) {
10541        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10542    }
10543
10544    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10545        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10546    }
10547
10548    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10549        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10550    }
10551
10552    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10553        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10554    }
10555
10556    private int packageFlagsToInstallFlags(PackageSetting ps) {
10557        int installFlags = 0;
10558        if (isExternal(ps)) {
10559            installFlags |= PackageManager.INSTALL_EXTERNAL;
10560        }
10561        if (isForwardLocked(ps)) {
10562            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10563        }
10564        return installFlags;
10565    }
10566
10567    private void deleteTempPackageFiles() {
10568        final FilenameFilter filter = new FilenameFilter() {
10569            public boolean accept(File dir, String name) {
10570                return name.startsWith("vmdl") && name.endsWith(".tmp");
10571            }
10572        };
10573        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10574            file.delete();
10575        }
10576    }
10577
10578    @Override
10579    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10580            int flags) {
10581        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10582                flags);
10583    }
10584
10585    @Override
10586    public void deletePackage(final String packageName,
10587            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10588        mContext.enforceCallingOrSelfPermission(
10589                android.Manifest.permission.DELETE_PACKAGES, null);
10590        final int uid = Binder.getCallingUid();
10591        if (UserHandle.getUserId(uid) != userId) {
10592            mContext.enforceCallingPermission(
10593                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10594                    "deletePackage for user " + userId);
10595        }
10596        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10597            try {
10598                observer.onPackageDeleted(packageName,
10599                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10600            } catch (RemoteException re) {
10601            }
10602            return;
10603        }
10604
10605        boolean uninstallBlocked = false;
10606        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10607            int[] users = sUserManager.getUserIds();
10608            for (int i = 0; i < users.length; ++i) {
10609                if (getBlockUninstallForUser(packageName, users[i])) {
10610                    uninstallBlocked = true;
10611                    break;
10612                }
10613            }
10614        } else {
10615            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10616        }
10617        if (uninstallBlocked) {
10618            try {
10619                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10620                        null);
10621            } catch (RemoteException re) {
10622            }
10623            return;
10624        }
10625
10626        if (DEBUG_REMOVE) {
10627            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10628        }
10629        // Queue up an async operation since the package deletion may take a little while.
10630        mHandler.post(new Runnable() {
10631            public void run() {
10632                mHandler.removeCallbacks(this);
10633                final int returnCode = deletePackageX(packageName, userId, flags);
10634                if (observer != null) {
10635                    try {
10636                        observer.onPackageDeleted(packageName, returnCode, null);
10637                    } catch (RemoteException e) {
10638                        Log.i(TAG, "Observer no longer exists.");
10639                    } //end catch
10640                } //end if
10641            } //end run
10642        });
10643    }
10644
10645    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10646        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10647                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10648        try {
10649            if (dpm != null) {
10650                if (dpm.isDeviceOwner(packageName)) {
10651                    return true;
10652                }
10653                int[] users;
10654                if (userId == UserHandle.USER_ALL) {
10655                    users = sUserManager.getUserIds();
10656                } else {
10657                    users = new int[]{userId};
10658                }
10659                for (int i = 0; i < users.length; ++i) {
10660                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10661                        return true;
10662                    }
10663                }
10664            }
10665        } catch (RemoteException e) {
10666        }
10667        return false;
10668    }
10669
10670    /**
10671     *  This method is an internal method that could be get invoked either
10672     *  to delete an installed package or to clean up a failed installation.
10673     *  After deleting an installed package, a broadcast is sent to notify any
10674     *  listeners that the package has been installed. For cleaning up a failed
10675     *  installation, the broadcast is not necessary since the package's
10676     *  installation wouldn't have sent the initial broadcast either
10677     *  The key steps in deleting a package are
10678     *  deleting the package information in internal structures like mPackages,
10679     *  deleting the packages base directories through installd
10680     *  updating mSettings to reflect current status
10681     *  persisting settings for later use
10682     *  sending a broadcast if necessary
10683     */
10684    private int deletePackageX(String packageName, int userId, int flags) {
10685        final PackageRemovedInfo info = new PackageRemovedInfo();
10686        final boolean res;
10687
10688        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10689                ? UserHandle.ALL : new UserHandle(userId);
10690
10691        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10692            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10693            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10694        }
10695
10696        boolean removedForAllUsers = false;
10697        boolean systemUpdate = false;
10698
10699        // for the uninstall-updates case and restricted profiles, remember the per-
10700        // userhandle installed state
10701        int[] allUsers;
10702        boolean[] perUserInstalled;
10703        synchronized (mPackages) {
10704            PackageSetting ps = mSettings.mPackages.get(packageName);
10705            allUsers = sUserManager.getUserIds();
10706            perUserInstalled = new boolean[allUsers.length];
10707            for (int i = 0; i < allUsers.length; i++) {
10708                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10709            }
10710        }
10711
10712        synchronized (mInstallLock) {
10713            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10714            res = deletePackageLI(packageName, removeForUser,
10715                    true, allUsers, perUserInstalled,
10716                    flags | REMOVE_CHATTY, info, true);
10717            systemUpdate = info.isRemovedPackageSystemUpdate;
10718            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10719                removedForAllUsers = true;
10720            }
10721            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10722                    + " removedForAllUsers=" + removedForAllUsers);
10723        }
10724
10725        if (res) {
10726            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10727
10728            // If the removed package was a system update, the old system package
10729            // was re-enabled; we need to broadcast this information
10730            if (systemUpdate) {
10731                Bundle extras = new Bundle(1);
10732                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10733                        ? info.removedAppId : info.uid);
10734                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10735
10736                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10737                        extras, null, null, null);
10738                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10739                        extras, null, null, null);
10740                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10741                        null, packageName, null, null);
10742            }
10743        }
10744        // Force a gc here.
10745        Runtime.getRuntime().gc();
10746        // Delete the resources here after sending the broadcast to let
10747        // other processes clean up before deleting resources.
10748        if (info.args != null) {
10749            synchronized (mInstallLock) {
10750                info.args.doPostDeleteLI(true);
10751            }
10752        }
10753
10754        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10755    }
10756
10757    static class PackageRemovedInfo {
10758        String removedPackage;
10759        int uid = -1;
10760        int removedAppId = -1;
10761        int[] removedUsers = null;
10762        boolean isRemovedPackageSystemUpdate = false;
10763        // Clean up resources deleted packages.
10764        InstallArgs args = null;
10765
10766        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10767            Bundle extras = new Bundle(1);
10768            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10769            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10770            if (replacing) {
10771                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10772            }
10773            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10774            if (removedPackage != null) {
10775                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10776                        extras, null, null, removedUsers);
10777                if (fullRemove && !replacing) {
10778                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10779                            extras, null, null, removedUsers);
10780                }
10781            }
10782            if (removedAppId >= 0) {
10783                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10784                        removedUsers);
10785            }
10786        }
10787    }
10788
10789    /*
10790     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10791     * flag is not set, the data directory is removed as well.
10792     * make sure this flag is set for partially installed apps. If not its meaningless to
10793     * delete a partially installed application.
10794     */
10795    private void removePackageDataLI(PackageSetting ps,
10796            int[] allUserHandles, boolean[] perUserInstalled,
10797            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10798        String packageName = ps.name;
10799        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10800        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10801        // Retrieve object to delete permissions for shared user later on
10802        final PackageSetting deletedPs;
10803        // reader
10804        synchronized (mPackages) {
10805            deletedPs = mSettings.mPackages.get(packageName);
10806            if (outInfo != null) {
10807                outInfo.removedPackage = packageName;
10808                outInfo.removedUsers = deletedPs != null
10809                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10810                        : null;
10811            }
10812        }
10813        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10814            removeDataDirsLI(packageName);
10815            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10816        }
10817        // writer
10818        synchronized (mPackages) {
10819            if (deletedPs != null) {
10820                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10821                    if (outInfo != null) {
10822                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10823                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10824                    }
10825                    if (deletedPs != null) {
10826                        updatePermissionsLPw(deletedPs.name, null, 0);
10827                        if (deletedPs.sharedUser != null) {
10828                            // remove permissions associated with package
10829                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10830                        }
10831                    }
10832                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10833                }
10834                // make sure to preserve per-user disabled state if this removal was just
10835                // a downgrade of a system app to the factory package
10836                if (allUserHandles != null && perUserInstalled != null) {
10837                    if (DEBUG_REMOVE) {
10838                        Slog.d(TAG, "Propagating install state across downgrade");
10839                    }
10840                    for (int i = 0; i < allUserHandles.length; i++) {
10841                        if (DEBUG_REMOVE) {
10842                            Slog.d(TAG, "    user " + allUserHandles[i]
10843                                    + " => " + perUserInstalled[i]);
10844                        }
10845                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10846                    }
10847                }
10848            }
10849            // can downgrade to reader
10850            if (writeSettings) {
10851                // Save settings now
10852                mSettings.writeLPr();
10853            }
10854        }
10855        if (outInfo != null) {
10856            // A user ID was deleted here. Go through all users and remove it
10857            // from KeyStore.
10858            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10859        }
10860    }
10861
10862    static boolean locationIsPrivileged(File path) {
10863        try {
10864            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10865                    .getCanonicalPath();
10866            return path.getCanonicalPath().startsWith(privilegedAppDir);
10867        } catch (IOException e) {
10868            Slog.e(TAG, "Unable to access code path " + path);
10869        }
10870        return false;
10871    }
10872
10873    /*
10874     * Tries to delete system package.
10875     */
10876    private boolean deleteSystemPackageLI(PackageSetting newPs,
10877            int[] allUserHandles, boolean[] perUserInstalled,
10878            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10879        final boolean applyUserRestrictions
10880                = (allUserHandles != null) && (perUserInstalled != null);
10881        PackageSetting disabledPs = null;
10882        // Confirm if the system package has been updated
10883        // An updated system app can be deleted. This will also have to restore
10884        // the system pkg from system partition
10885        // reader
10886        synchronized (mPackages) {
10887            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10888        }
10889        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10890                + " disabledPs=" + disabledPs);
10891        if (disabledPs == null) {
10892            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10893            return false;
10894        } else if (DEBUG_REMOVE) {
10895            Slog.d(TAG, "Deleting system pkg from data partition");
10896        }
10897        if (DEBUG_REMOVE) {
10898            if (applyUserRestrictions) {
10899                Slog.d(TAG, "Remembering install states:");
10900                for (int i = 0; i < allUserHandles.length; i++) {
10901                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10902                }
10903            }
10904        }
10905        // Delete the updated package
10906        outInfo.isRemovedPackageSystemUpdate = true;
10907        if (disabledPs.versionCode < newPs.versionCode) {
10908            // Delete data for downgrades
10909            flags &= ~PackageManager.DELETE_KEEP_DATA;
10910        } else {
10911            // Preserve data by setting flag
10912            flags |= PackageManager.DELETE_KEEP_DATA;
10913        }
10914        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10915                allUserHandles, perUserInstalled, outInfo, writeSettings);
10916        if (!ret) {
10917            return false;
10918        }
10919        // writer
10920        synchronized (mPackages) {
10921            // Reinstate the old system package
10922            mSettings.enableSystemPackageLPw(newPs.name);
10923            // Remove any native libraries from the upgraded package.
10924            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10925        }
10926        // Install the system package
10927        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10928        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10929        if (locationIsPrivileged(disabledPs.codePath)) {
10930            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10931        }
10932
10933        final PackageParser.Package newPkg;
10934        try {
10935            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10936        } catch (PackageManagerException e) {
10937            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
10938            return false;
10939        }
10940
10941        // writer
10942        synchronized (mPackages) {
10943            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
10944            updatePermissionsLPw(newPkg.packageName, newPkg,
10945                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
10946            if (applyUserRestrictions) {
10947                if (DEBUG_REMOVE) {
10948                    Slog.d(TAG, "Propagating install state across reinstall");
10949                }
10950                for (int i = 0; i < allUserHandles.length; i++) {
10951                    if (DEBUG_REMOVE) {
10952                        Slog.d(TAG, "    user " + allUserHandles[i]
10953                                + " => " + perUserInstalled[i]);
10954                    }
10955                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10956                }
10957                // Regardless of writeSettings we need to ensure that this restriction
10958                // state propagation is persisted
10959                mSettings.writeAllUsersPackageRestrictionsLPr();
10960            }
10961            // can downgrade to reader here
10962            if (writeSettings) {
10963                mSettings.writeLPr();
10964            }
10965        }
10966        return true;
10967    }
10968
10969    private boolean deleteInstalledPackageLI(PackageSetting ps,
10970            boolean deleteCodeAndResources, int flags,
10971            int[] allUserHandles, boolean[] perUserInstalled,
10972            PackageRemovedInfo outInfo, boolean writeSettings) {
10973        if (outInfo != null) {
10974            outInfo.uid = ps.appId;
10975        }
10976
10977        // Delete package data from internal structures and also remove data if flag is set
10978        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
10979
10980        // Delete application code and resources
10981        if (deleteCodeAndResources && (outInfo != null)) {
10982            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
10983                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
10984                    getAppDexInstructionSets(ps));
10985            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
10986        }
10987        return true;
10988    }
10989
10990    @Override
10991    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
10992            int userId) {
10993        mContext.enforceCallingOrSelfPermission(
10994                android.Manifest.permission.DELETE_PACKAGES, null);
10995        synchronized (mPackages) {
10996            PackageSetting ps = mSettings.mPackages.get(packageName);
10997            if (ps == null) {
10998                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
10999                return false;
11000            }
11001            if (!ps.getInstalled(userId)) {
11002                // Can't block uninstall for an app that is not installed or enabled.
11003                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11004                return false;
11005            }
11006            ps.setBlockUninstall(blockUninstall, userId);
11007            mSettings.writePackageRestrictionsLPr(userId);
11008        }
11009        return true;
11010    }
11011
11012    @Override
11013    public boolean getBlockUninstallForUser(String packageName, int userId) {
11014        synchronized (mPackages) {
11015            PackageSetting ps = mSettings.mPackages.get(packageName);
11016            if (ps == null) {
11017                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11018                return false;
11019            }
11020            return ps.getBlockUninstall(userId);
11021        }
11022    }
11023
11024    /*
11025     * This method handles package deletion in general
11026     */
11027    private boolean deletePackageLI(String packageName, UserHandle user,
11028            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11029            int flags, PackageRemovedInfo outInfo,
11030            boolean writeSettings) {
11031        if (packageName == null) {
11032            Slog.w(TAG, "Attempt to delete null packageName.");
11033            return false;
11034        }
11035        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11036        PackageSetting ps;
11037        boolean dataOnly = false;
11038        int removeUser = -1;
11039        int appId = -1;
11040        synchronized (mPackages) {
11041            ps = mSettings.mPackages.get(packageName);
11042            if (ps == null) {
11043                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11044                return false;
11045            }
11046            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11047                    && user.getIdentifier() != UserHandle.USER_ALL) {
11048                // The caller is asking that the package only be deleted for a single
11049                // user.  To do this, we just mark its uninstalled state and delete
11050                // its data.  If this is a system app, we only allow this to happen if
11051                // they have set the special DELETE_SYSTEM_APP which requests different
11052                // semantics than normal for uninstalling system apps.
11053                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11054                ps.setUserState(user.getIdentifier(),
11055                        COMPONENT_ENABLED_STATE_DEFAULT,
11056                        false, //installed
11057                        true,  //stopped
11058                        true,  //notLaunched
11059                        false, //hidden
11060                        null, null, null,
11061                        false // blockUninstall
11062                        );
11063                if (!isSystemApp(ps)) {
11064                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11065                        // Other user still have this package installed, so all
11066                        // we need to do is clear this user's data and save that
11067                        // it is uninstalled.
11068                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11069                        removeUser = user.getIdentifier();
11070                        appId = ps.appId;
11071                        mSettings.writePackageRestrictionsLPr(removeUser);
11072                    } else {
11073                        // We need to set it back to 'installed' so the uninstall
11074                        // broadcasts will be sent correctly.
11075                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11076                        ps.setInstalled(true, user.getIdentifier());
11077                    }
11078                } else {
11079                    // This is a system app, so we assume that the
11080                    // other users still have this package installed, so all
11081                    // we need to do is clear this user's data and save that
11082                    // it is uninstalled.
11083                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11084                    removeUser = user.getIdentifier();
11085                    appId = ps.appId;
11086                    mSettings.writePackageRestrictionsLPr(removeUser);
11087                }
11088            }
11089        }
11090
11091        if (removeUser >= 0) {
11092            // From above, we determined that we are deleting this only
11093            // for a single user.  Continue the work here.
11094            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11095            if (outInfo != null) {
11096                outInfo.removedPackage = packageName;
11097                outInfo.removedAppId = appId;
11098                outInfo.removedUsers = new int[] {removeUser};
11099            }
11100            mInstaller.clearUserData(packageName, removeUser);
11101            removeKeystoreDataIfNeeded(removeUser, appId);
11102            schedulePackageCleaning(packageName, removeUser, false);
11103            return true;
11104        }
11105
11106        if (dataOnly) {
11107            // Delete application data first
11108            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11109            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11110            return true;
11111        }
11112
11113        boolean ret = false;
11114        if (isSystemApp(ps)) {
11115            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11116            // When an updated system application is deleted we delete the existing resources as well and
11117            // fall back to existing code in system partition
11118            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11119                    flags, outInfo, writeSettings);
11120        } else {
11121            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11122            // Kill application pre-emptively especially for apps on sd.
11123            killApplication(packageName, ps.appId, "uninstall pkg");
11124            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11125                    allUserHandles, perUserInstalled,
11126                    outInfo, writeSettings);
11127        }
11128
11129        return ret;
11130    }
11131
11132    private final class ClearStorageConnection implements ServiceConnection {
11133        IMediaContainerService mContainerService;
11134
11135        @Override
11136        public void onServiceConnected(ComponentName name, IBinder service) {
11137            synchronized (this) {
11138                mContainerService = IMediaContainerService.Stub.asInterface(service);
11139                notifyAll();
11140            }
11141        }
11142
11143        @Override
11144        public void onServiceDisconnected(ComponentName name) {
11145        }
11146    }
11147
11148    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11149        final boolean mounted;
11150        if (Environment.isExternalStorageEmulated()) {
11151            mounted = true;
11152        } else {
11153            final String status = Environment.getExternalStorageState();
11154
11155            mounted = status.equals(Environment.MEDIA_MOUNTED)
11156                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11157        }
11158
11159        if (!mounted) {
11160            return;
11161        }
11162
11163        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11164        int[] users;
11165        if (userId == UserHandle.USER_ALL) {
11166            users = sUserManager.getUserIds();
11167        } else {
11168            users = new int[] { userId };
11169        }
11170        final ClearStorageConnection conn = new ClearStorageConnection();
11171        if (mContext.bindServiceAsUser(
11172                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11173            try {
11174                for (int curUser : users) {
11175                    long timeout = SystemClock.uptimeMillis() + 5000;
11176                    synchronized (conn) {
11177                        long now = SystemClock.uptimeMillis();
11178                        while (conn.mContainerService == null && now < timeout) {
11179                            try {
11180                                conn.wait(timeout - now);
11181                            } catch (InterruptedException e) {
11182                            }
11183                        }
11184                    }
11185                    if (conn.mContainerService == null) {
11186                        return;
11187                    }
11188
11189                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11190                    clearDirectory(conn.mContainerService,
11191                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11192                    if (allData) {
11193                        clearDirectory(conn.mContainerService,
11194                                userEnv.buildExternalStorageAppDataDirs(packageName));
11195                        clearDirectory(conn.mContainerService,
11196                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11197                    }
11198                }
11199            } finally {
11200                mContext.unbindService(conn);
11201            }
11202        }
11203    }
11204
11205    @Override
11206    public void clearApplicationUserData(final String packageName,
11207            final IPackageDataObserver observer, final int userId) {
11208        mContext.enforceCallingOrSelfPermission(
11209                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11210        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11211        // Queue up an async operation since the package deletion may take a little while.
11212        mHandler.post(new Runnable() {
11213            public void run() {
11214                mHandler.removeCallbacks(this);
11215                final boolean succeeded;
11216                synchronized (mInstallLock) {
11217                    succeeded = clearApplicationUserDataLI(packageName, userId);
11218                }
11219                clearExternalStorageDataSync(packageName, userId, true);
11220                if (succeeded) {
11221                    // invoke DeviceStorageMonitor's update method to clear any notifications
11222                    DeviceStorageMonitorInternal
11223                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11224                    if (dsm != null) {
11225                        dsm.checkMemory();
11226                    }
11227                }
11228                if(observer != null) {
11229                    try {
11230                        observer.onRemoveCompleted(packageName, succeeded);
11231                    } catch (RemoteException e) {
11232                        Log.i(TAG, "Observer no longer exists.");
11233                    }
11234                } //end if observer
11235            } //end run
11236        });
11237    }
11238
11239    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11240        if (packageName == null) {
11241            Slog.w(TAG, "Attempt to delete null packageName.");
11242            return false;
11243        }
11244
11245        // Try finding details about the requested package
11246        PackageParser.Package pkg;
11247        synchronized (mPackages) {
11248            pkg = mPackages.get(packageName);
11249            if (pkg == null) {
11250                final PackageSetting ps = mSettings.mPackages.get(packageName);
11251                if (ps != null) {
11252                    pkg = ps.pkg;
11253                }
11254            }
11255        }
11256
11257        if (pkg == null) {
11258            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11259        }
11260
11261        // Always delete data directories for package, even if we found no other
11262        // record of app. This helps users recover from UID mismatches without
11263        // resorting to a full data wipe.
11264        int retCode = mInstaller.clearUserData(packageName, userId);
11265        if (retCode < 0) {
11266            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11267            return false;
11268        }
11269
11270        if (pkg == null) {
11271            return false;
11272        }
11273
11274        if (pkg != null && pkg.applicationInfo != null) {
11275            final int appId = pkg.applicationInfo.uid;
11276            removeKeystoreDataIfNeeded(userId, appId);
11277        }
11278
11279        // Create a native library symlink only if we have native libraries
11280        // and if the native libraries are 32 bit libraries. We do not provide
11281        // this symlink for 64 bit libraries.
11282        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11283                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11284            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11285            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11286                Slog.w(TAG, "Failed linking native library dir");
11287                return false;
11288            }
11289        }
11290
11291        return true;
11292    }
11293
11294    /**
11295     * Remove entries from the keystore daemon. Will only remove it if the
11296     * {@code appId} is valid.
11297     */
11298    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11299        if (appId < 0) {
11300            return;
11301        }
11302
11303        final KeyStore keyStore = KeyStore.getInstance();
11304        if (keyStore != null) {
11305            if (userId == UserHandle.USER_ALL) {
11306                for (final int individual : sUserManager.getUserIds()) {
11307                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11308                }
11309            } else {
11310                keyStore.clearUid(UserHandle.getUid(userId, appId));
11311            }
11312        } else {
11313            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11314        }
11315    }
11316
11317    @Override
11318    public void deleteApplicationCacheFiles(final String packageName,
11319            final IPackageDataObserver observer) {
11320        mContext.enforceCallingOrSelfPermission(
11321                android.Manifest.permission.DELETE_CACHE_FILES, null);
11322        // Queue up an async operation since the package deletion may take a little while.
11323        final int userId = UserHandle.getCallingUserId();
11324        mHandler.post(new Runnable() {
11325            public void run() {
11326                mHandler.removeCallbacks(this);
11327                final boolean succeded;
11328                synchronized (mInstallLock) {
11329                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11330                }
11331                clearExternalStorageDataSync(packageName, userId, false);
11332                if(observer != null) {
11333                    try {
11334                        observer.onRemoveCompleted(packageName, succeded);
11335                    } catch (RemoteException e) {
11336                        Log.i(TAG, "Observer no longer exists.");
11337                    }
11338                } //end if observer
11339            } //end run
11340        });
11341    }
11342
11343    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11344        if (packageName == null) {
11345            Slog.w(TAG, "Attempt to delete null packageName.");
11346            return false;
11347        }
11348        PackageParser.Package p;
11349        synchronized (mPackages) {
11350            p = mPackages.get(packageName);
11351        }
11352        if (p == null) {
11353            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11354            return false;
11355        }
11356        final ApplicationInfo applicationInfo = p.applicationInfo;
11357        if (applicationInfo == null) {
11358            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11359            return false;
11360        }
11361        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11362        if (retCode < 0) {
11363            Slog.w(TAG, "Couldn't remove cache files for package: "
11364                       + packageName + " u" + userId);
11365            return false;
11366        }
11367        return true;
11368    }
11369
11370    @Override
11371    public void getPackageSizeInfo(final String packageName, int userHandle,
11372            final IPackageStatsObserver observer) {
11373        mContext.enforceCallingOrSelfPermission(
11374                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11375        if (packageName == null) {
11376            throw new IllegalArgumentException("Attempt to get size of null packageName");
11377        }
11378
11379        PackageStats stats = new PackageStats(packageName, userHandle);
11380
11381        /*
11382         * Queue up an async operation since the package measurement may take a
11383         * little while.
11384         */
11385        Message msg = mHandler.obtainMessage(INIT_COPY);
11386        msg.obj = new MeasureParams(stats, observer);
11387        mHandler.sendMessage(msg);
11388    }
11389
11390    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11391            PackageStats pStats) {
11392        if (packageName == null) {
11393            Slog.w(TAG, "Attempt to get size of null packageName.");
11394            return false;
11395        }
11396        PackageParser.Package p;
11397        boolean dataOnly = false;
11398        String libDirRoot = null;
11399        String asecPath = null;
11400        PackageSetting ps = null;
11401        synchronized (mPackages) {
11402            p = mPackages.get(packageName);
11403            ps = mSettings.mPackages.get(packageName);
11404            if(p == null) {
11405                dataOnly = true;
11406                if((ps == null) || (ps.pkg == null)) {
11407                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11408                    return false;
11409                }
11410                p = ps.pkg;
11411            }
11412            if (ps != null) {
11413                libDirRoot = ps.legacyNativeLibraryPathString;
11414            }
11415            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11416                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11417                if (secureContainerId != null) {
11418                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11419                }
11420            }
11421        }
11422        String publicSrcDir = null;
11423        if(!dataOnly) {
11424            final ApplicationInfo applicationInfo = p.applicationInfo;
11425            if (applicationInfo == null) {
11426                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11427                return false;
11428            }
11429            if (isForwardLocked(p)) {
11430                publicSrcDir = applicationInfo.getBaseResourcePath();
11431            }
11432        }
11433        // TODO: extend to measure size of split APKs
11434        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11435        // not just the first level.
11436        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11437        // just the primary.
11438        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11439        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11440                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11441        if (res < 0) {
11442            return false;
11443        }
11444
11445        // Fix-up for forward-locked applications in ASEC containers.
11446        if (!isExternal(p)) {
11447            pStats.codeSize += pStats.externalCodeSize;
11448            pStats.externalCodeSize = 0L;
11449        }
11450
11451        return true;
11452    }
11453
11454
11455    @Override
11456    public void addPackageToPreferred(String packageName) {
11457        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11458    }
11459
11460    @Override
11461    public void removePackageFromPreferred(String packageName) {
11462        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11463    }
11464
11465    @Override
11466    public List<PackageInfo> getPreferredPackages(int flags) {
11467        return new ArrayList<PackageInfo>();
11468    }
11469
11470    private int getUidTargetSdkVersionLockedLPr(int uid) {
11471        Object obj = mSettings.getUserIdLPr(uid);
11472        if (obj instanceof SharedUserSetting) {
11473            final SharedUserSetting sus = (SharedUserSetting) obj;
11474            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11475            final Iterator<PackageSetting> it = sus.packages.iterator();
11476            while (it.hasNext()) {
11477                final PackageSetting ps = it.next();
11478                if (ps.pkg != null) {
11479                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11480                    if (v < vers) vers = v;
11481                }
11482            }
11483            return vers;
11484        } else if (obj instanceof PackageSetting) {
11485            final PackageSetting ps = (PackageSetting) obj;
11486            if (ps.pkg != null) {
11487                return ps.pkg.applicationInfo.targetSdkVersion;
11488            }
11489        }
11490        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11491    }
11492
11493    @Override
11494    public void addPreferredActivity(IntentFilter filter, int match,
11495            ComponentName[] set, ComponentName activity, int userId) {
11496        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11497                "Adding preferred");
11498    }
11499
11500    private void addPreferredActivityInternal(IntentFilter filter, int match,
11501            ComponentName[] set, ComponentName activity, boolean always, int userId,
11502            String opname) {
11503        // writer
11504        int callingUid = Binder.getCallingUid();
11505        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11506        if (filter.countActions() == 0) {
11507            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11508            return;
11509        }
11510        synchronized (mPackages) {
11511            if (mContext.checkCallingOrSelfPermission(
11512                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11513                    != PackageManager.PERMISSION_GRANTED) {
11514                if (getUidTargetSdkVersionLockedLPr(callingUid)
11515                        < Build.VERSION_CODES.FROYO) {
11516                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11517                            + callingUid);
11518                    return;
11519                }
11520                mContext.enforceCallingOrSelfPermission(
11521                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11522            }
11523
11524            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11525            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11526                    + userId + ":");
11527            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11528            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11529            mSettings.writePackageRestrictionsLPr(userId);
11530        }
11531    }
11532
11533    @Override
11534    public void replacePreferredActivity(IntentFilter filter, int match,
11535            ComponentName[] set, ComponentName activity, int userId) {
11536        if (filter.countActions() != 1) {
11537            throw new IllegalArgumentException(
11538                    "replacePreferredActivity expects filter to have only 1 action.");
11539        }
11540        if (filter.countDataAuthorities() != 0
11541                || filter.countDataPaths() != 0
11542                || filter.countDataSchemes() > 1
11543                || filter.countDataTypes() != 0) {
11544            throw new IllegalArgumentException(
11545                    "replacePreferredActivity expects filter to have no data authorities, " +
11546                    "paths, or types; and at most one scheme.");
11547        }
11548
11549        final int callingUid = Binder.getCallingUid();
11550        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11551        synchronized (mPackages) {
11552            if (mContext.checkCallingOrSelfPermission(
11553                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11554                    != PackageManager.PERMISSION_GRANTED) {
11555                if (getUidTargetSdkVersionLockedLPr(callingUid)
11556                        < Build.VERSION_CODES.FROYO) {
11557                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11558                            + Binder.getCallingUid());
11559                    return;
11560                }
11561                mContext.enforceCallingOrSelfPermission(
11562                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11563            }
11564
11565            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11566            if (pir != null) {
11567                // Get all of the existing entries that exactly match this filter.
11568                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11569                if (existing != null && existing.size() == 1) {
11570                    PreferredActivity cur = existing.get(0);
11571                    if (DEBUG_PREFERRED) {
11572                        Slog.i(TAG, "Checking replace of preferred:");
11573                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11574                        if (!cur.mPref.mAlways) {
11575                            Slog.i(TAG, "  -- CUR; not mAlways!");
11576                        } else {
11577                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11578                            Slog.i(TAG, "  -- CUR: mSet="
11579                                    + Arrays.toString(cur.mPref.mSetComponents));
11580                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11581                            Slog.i(TAG, "  -- NEW: mMatch="
11582                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11583                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11584                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11585                        }
11586                    }
11587                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11588                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11589                            && cur.mPref.sameSet(set)) {
11590                        // Setting the preferred activity to what it happens to be already
11591                        if (DEBUG_PREFERRED) {
11592                            Slog.i(TAG, "Replacing with same preferred activity "
11593                                    + cur.mPref.mShortComponent + " for user "
11594                                    + userId + ":");
11595                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11596                        }
11597                        return;
11598                    }
11599                }
11600
11601                if (existing != null) {
11602                    if (DEBUG_PREFERRED) {
11603                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11604                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11605                    }
11606                    for (int i = 0; i < existing.size(); i++) {
11607                        PreferredActivity pa = existing.get(i);
11608                        if (DEBUG_PREFERRED) {
11609                            Slog.i(TAG, "Removing existing preferred activity "
11610                                    + pa.mPref.mComponent + ":");
11611                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11612                        }
11613                        pir.removeFilter(pa);
11614                    }
11615                }
11616            }
11617            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11618                    "Replacing preferred");
11619        }
11620    }
11621
11622    @Override
11623    public void clearPackagePreferredActivities(String packageName) {
11624        final int uid = Binder.getCallingUid();
11625        // writer
11626        synchronized (mPackages) {
11627            PackageParser.Package pkg = mPackages.get(packageName);
11628            if (pkg == null || pkg.applicationInfo.uid != uid) {
11629                if (mContext.checkCallingOrSelfPermission(
11630                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11631                        != PackageManager.PERMISSION_GRANTED) {
11632                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11633                            < Build.VERSION_CODES.FROYO) {
11634                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11635                                + Binder.getCallingUid());
11636                        return;
11637                    }
11638                    mContext.enforceCallingOrSelfPermission(
11639                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11640                }
11641            }
11642
11643            int user = UserHandle.getCallingUserId();
11644            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11645                mSettings.writePackageRestrictionsLPr(user);
11646                scheduleWriteSettingsLocked();
11647            }
11648        }
11649    }
11650
11651    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11652    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11653        ArrayList<PreferredActivity> removed = null;
11654        boolean changed = false;
11655        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11656            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11657            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11658            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11659                continue;
11660            }
11661            Iterator<PreferredActivity> it = pir.filterIterator();
11662            while (it.hasNext()) {
11663                PreferredActivity pa = it.next();
11664                // Mark entry for removal only if it matches the package name
11665                // and the entry is of type "always".
11666                if (packageName == null ||
11667                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11668                                && pa.mPref.mAlways)) {
11669                    if (removed == null) {
11670                        removed = new ArrayList<PreferredActivity>();
11671                    }
11672                    removed.add(pa);
11673                }
11674            }
11675            if (removed != null) {
11676                for (int j=0; j<removed.size(); j++) {
11677                    PreferredActivity pa = removed.get(j);
11678                    pir.removeFilter(pa);
11679                }
11680                changed = true;
11681            }
11682        }
11683        return changed;
11684    }
11685
11686    @Override
11687    public void resetPreferredActivities(int userId) {
11688        /* TODO: Actually use userId. Why is it being passed in? */
11689        mContext.enforceCallingOrSelfPermission(
11690                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11691        // writer
11692        synchronized (mPackages) {
11693            int user = UserHandle.getCallingUserId();
11694            clearPackagePreferredActivitiesLPw(null, user);
11695            mSettings.readDefaultPreferredAppsLPw(this, user);
11696            mSettings.writePackageRestrictionsLPr(user);
11697            scheduleWriteSettingsLocked();
11698        }
11699    }
11700
11701    @Override
11702    public int getPreferredActivities(List<IntentFilter> outFilters,
11703            List<ComponentName> outActivities, String packageName) {
11704
11705        int num = 0;
11706        final int userId = UserHandle.getCallingUserId();
11707        // reader
11708        synchronized (mPackages) {
11709            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11710            if (pir != null) {
11711                final Iterator<PreferredActivity> it = pir.filterIterator();
11712                while (it.hasNext()) {
11713                    final PreferredActivity pa = it.next();
11714                    if (packageName == null
11715                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11716                                    && pa.mPref.mAlways)) {
11717                        if (outFilters != null) {
11718                            outFilters.add(new IntentFilter(pa));
11719                        }
11720                        if (outActivities != null) {
11721                            outActivities.add(pa.mPref.mComponent);
11722                        }
11723                    }
11724                }
11725            }
11726        }
11727
11728        return num;
11729    }
11730
11731    @Override
11732    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11733            int userId) {
11734        int callingUid = Binder.getCallingUid();
11735        if (callingUid != Process.SYSTEM_UID) {
11736            throw new SecurityException(
11737                    "addPersistentPreferredActivity can only be run by the system");
11738        }
11739        if (filter.countActions() == 0) {
11740            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11741            return;
11742        }
11743        synchronized (mPackages) {
11744            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11745                    " :");
11746            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11747            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11748                    new PersistentPreferredActivity(filter, activity));
11749            mSettings.writePackageRestrictionsLPr(userId);
11750        }
11751    }
11752
11753    @Override
11754    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11755        int callingUid = Binder.getCallingUid();
11756        if (callingUid != Process.SYSTEM_UID) {
11757            throw new SecurityException(
11758                    "clearPackagePersistentPreferredActivities can only be run by the system");
11759        }
11760        ArrayList<PersistentPreferredActivity> removed = null;
11761        boolean changed = false;
11762        synchronized (mPackages) {
11763            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11764                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11765                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11766                        .valueAt(i);
11767                if (userId != thisUserId) {
11768                    continue;
11769                }
11770                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11771                while (it.hasNext()) {
11772                    PersistentPreferredActivity ppa = it.next();
11773                    // Mark entry for removal only if it matches the package name.
11774                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11775                        if (removed == null) {
11776                            removed = new ArrayList<PersistentPreferredActivity>();
11777                        }
11778                        removed.add(ppa);
11779                    }
11780                }
11781                if (removed != null) {
11782                    for (int j=0; j<removed.size(); j++) {
11783                        PersistentPreferredActivity ppa = removed.get(j);
11784                        ppir.removeFilter(ppa);
11785                    }
11786                    changed = true;
11787                }
11788            }
11789
11790            if (changed) {
11791                mSettings.writePackageRestrictionsLPr(userId);
11792            }
11793        }
11794    }
11795
11796    @Override
11797    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11798            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11799        mContext.enforceCallingOrSelfPermission(
11800                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11801        int callingUid = Binder.getCallingUid();
11802        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11803        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11804        if (intentFilter.countActions() == 0) {
11805            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11806            return;
11807        }
11808        synchronized (mPackages) {
11809            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11810                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11811            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11812            mSettings.writePackageRestrictionsLPr(sourceUserId);
11813        }
11814    }
11815
11816    @Override
11817    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11818            int ownerUserId) {
11819        mContext.enforceCallingOrSelfPermission(
11820                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11821        int callingUid = Binder.getCallingUid();
11822        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11823        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11824        int callingUserId = UserHandle.getUserId(callingUid);
11825        synchronized (mPackages) {
11826            CrossProfileIntentResolver resolver =
11827                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11828            HashSet<CrossProfileIntentFilter> set =
11829                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11830            for (CrossProfileIntentFilter filter : set) {
11831                if (filter.getOwnerPackage().equals(ownerPackage)
11832                        && filter.getOwnerUserId() == callingUserId) {
11833                    resolver.removeFilter(filter);
11834                }
11835            }
11836            mSettings.writePackageRestrictionsLPr(sourceUserId);
11837        }
11838    }
11839
11840    // Enforcing that callingUid is owning pkg on userId
11841    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11842        // The system owns everything.
11843        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11844            return;
11845        }
11846        int callingUserId = UserHandle.getUserId(callingUid);
11847        if (callingUserId != userId) {
11848            throw new SecurityException("calling uid " + callingUid
11849                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11850                    + callingUserId);
11851        }
11852        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11853        if (pi == null) {
11854            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11855                    + callingUserId);
11856        }
11857        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11858            throw new SecurityException("Calling uid " + callingUid
11859                    + " does not own package " + pkg);
11860        }
11861    }
11862
11863    @Override
11864    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11865        Intent intent = new Intent(Intent.ACTION_MAIN);
11866        intent.addCategory(Intent.CATEGORY_HOME);
11867
11868        final int callingUserId = UserHandle.getCallingUserId();
11869        List<ResolveInfo> list = queryIntentActivities(intent, null,
11870                PackageManager.GET_META_DATA, callingUserId);
11871        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11872                true, false, false, callingUserId);
11873
11874        allHomeCandidates.clear();
11875        if (list != null) {
11876            for (ResolveInfo ri : list) {
11877                allHomeCandidates.add(ri);
11878            }
11879        }
11880        return (preferred == null || preferred.activityInfo == null)
11881                ? null
11882                : new ComponentName(preferred.activityInfo.packageName,
11883                        preferred.activityInfo.name);
11884    }
11885
11886    @Override
11887    public void setApplicationEnabledSetting(String appPackageName,
11888            int newState, int flags, int userId, String callingPackage) {
11889        if (!sUserManager.exists(userId)) return;
11890        if (callingPackage == null) {
11891            callingPackage = Integer.toString(Binder.getCallingUid());
11892        }
11893        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11894    }
11895
11896    @Override
11897    public void setComponentEnabledSetting(ComponentName componentName,
11898            int newState, int flags, int userId) {
11899        if (!sUserManager.exists(userId)) return;
11900        setEnabledSetting(componentName.getPackageName(),
11901                componentName.getClassName(), newState, flags, userId, null);
11902    }
11903
11904    private void setEnabledSetting(final String packageName, String className, int newState,
11905            final int flags, int userId, String callingPackage) {
11906        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11907              || newState == COMPONENT_ENABLED_STATE_ENABLED
11908              || newState == COMPONENT_ENABLED_STATE_DISABLED
11909              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11910              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11911            throw new IllegalArgumentException("Invalid new component state: "
11912                    + newState);
11913        }
11914        PackageSetting pkgSetting;
11915        final int uid = Binder.getCallingUid();
11916        final int permission = mContext.checkCallingOrSelfPermission(
11917                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11918        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11919        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11920        boolean sendNow = false;
11921        boolean isApp = (className == null);
11922        String componentName = isApp ? packageName : className;
11923        int packageUid = -1;
11924        ArrayList<String> components;
11925
11926        // writer
11927        synchronized (mPackages) {
11928            pkgSetting = mSettings.mPackages.get(packageName);
11929            if (pkgSetting == null) {
11930                if (className == null) {
11931                    throw new IllegalArgumentException(
11932                            "Unknown package: " + packageName);
11933                }
11934                throw new IllegalArgumentException(
11935                        "Unknown component: " + packageName
11936                        + "/" + className);
11937            }
11938            // Allow root and verify that userId is not being specified by a different user
11939            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
11940                throw new SecurityException(
11941                        "Permission Denial: attempt to change component state from pid="
11942                        + Binder.getCallingPid()
11943                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
11944            }
11945            if (className == null) {
11946                // We're dealing with an application/package level state change
11947                if (pkgSetting.getEnabled(userId) == newState) {
11948                    // Nothing to do
11949                    return;
11950                }
11951                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
11952                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
11953                    // Don't care about who enables an app.
11954                    callingPackage = null;
11955                }
11956                pkgSetting.setEnabled(newState, userId, callingPackage);
11957                // pkgSetting.pkg.mSetEnabled = newState;
11958            } else {
11959                // We're dealing with a component level state change
11960                // First, verify that this is a valid class name.
11961                PackageParser.Package pkg = pkgSetting.pkg;
11962                if (pkg == null || !pkg.hasComponentClassName(className)) {
11963                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
11964                        throw new IllegalArgumentException("Component class " + className
11965                                + " does not exist in " + packageName);
11966                    } else {
11967                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
11968                                + className + " does not exist in " + packageName);
11969                    }
11970                }
11971                switch (newState) {
11972                case COMPONENT_ENABLED_STATE_ENABLED:
11973                    if (!pkgSetting.enableComponentLPw(className, userId)) {
11974                        return;
11975                    }
11976                    break;
11977                case COMPONENT_ENABLED_STATE_DISABLED:
11978                    if (!pkgSetting.disableComponentLPw(className, userId)) {
11979                        return;
11980                    }
11981                    break;
11982                case COMPONENT_ENABLED_STATE_DEFAULT:
11983                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
11984                        return;
11985                    }
11986                    break;
11987                default:
11988                    Slog.e(TAG, "Invalid new component state: " + newState);
11989                    return;
11990                }
11991            }
11992            mSettings.writePackageRestrictionsLPr(userId);
11993            components = mPendingBroadcasts.get(userId, packageName);
11994            final boolean newPackage = components == null;
11995            if (newPackage) {
11996                components = new ArrayList<String>();
11997            }
11998            if (!components.contains(componentName)) {
11999                components.add(componentName);
12000            }
12001            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12002                sendNow = true;
12003                // Purge entry from pending broadcast list if another one exists already
12004                // since we are sending one right away.
12005                mPendingBroadcasts.remove(userId, packageName);
12006            } else {
12007                if (newPackage) {
12008                    mPendingBroadcasts.put(userId, packageName, components);
12009                }
12010                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12011                    // Schedule a message
12012                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12013                }
12014            }
12015        }
12016
12017        long callingId = Binder.clearCallingIdentity();
12018        try {
12019            if (sendNow) {
12020                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12021                sendPackageChangedBroadcast(packageName,
12022                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12023            }
12024        } finally {
12025            Binder.restoreCallingIdentity(callingId);
12026        }
12027    }
12028
12029    private void sendPackageChangedBroadcast(String packageName,
12030            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12031        if (DEBUG_INSTALL)
12032            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12033                    + componentNames);
12034        Bundle extras = new Bundle(4);
12035        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12036        String nameList[] = new String[componentNames.size()];
12037        componentNames.toArray(nameList);
12038        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12039        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12040        extras.putInt(Intent.EXTRA_UID, packageUid);
12041        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12042                new int[] {UserHandle.getUserId(packageUid)});
12043    }
12044
12045    @Override
12046    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12047        if (!sUserManager.exists(userId)) return;
12048        final int uid = Binder.getCallingUid();
12049        final int permission = mContext.checkCallingOrSelfPermission(
12050                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12051        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12052        enforceCrossUserPermission(uid, userId, true, true, "stop package");
12053        // writer
12054        synchronized (mPackages) {
12055            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12056                    uid, userId)) {
12057                scheduleWritePackageRestrictionsLocked(userId);
12058            }
12059        }
12060    }
12061
12062    @Override
12063    public String getInstallerPackageName(String packageName) {
12064        // reader
12065        synchronized (mPackages) {
12066            return mSettings.getInstallerPackageNameLPr(packageName);
12067        }
12068    }
12069
12070    @Override
12071    public int getApplicationEnabledSetting(String packageName, int userId) {
12072        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12073        int uid = Binder.getCallingUid();
12074        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
12075        // reader
12076        synchronized (mPackages) {
12077            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12078        }
12079    }
12080
12081    @Override
12082    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12083        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12084        int uid = Binder.getCallingUid();
12085        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
12086        // reader
12087        synchronized (mPackages) {
12088            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12089        }
12090    }
12091
12092    @Override
12093    public void enterSafeMode() {
12094        enforceSystemOrRoot("Only the system can request entering safe mode");
12095
12096        if (!mSystemReady) {
12097            mSafeMode = true;
12098        }
12099    }
12100
12101    @Override
12102    public void systemReady() {
12103        mSystemReady = true;
12104
12105        // Read the compatibilty setting when the system is ready.
12106        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12107                mContext.getContentResolver(),
12108                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12109        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12110        if (DEBUG_SETTINGS) {
12111            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12112        }
12113
12114        synchronized (mPackages) {
12115            // Verify that all of the preferred activity components actually
12116            // exist.  It is possible for applications to be updated and at
12117            // that point remove a previously declared activity component that
12118            // had been set as a preferred activity.  We try to clean this up
12119            // the next time we encounter that preferred activity, but it is
12120            // possible for the user flow to never be able to return to that
12121            // situation so here we do a sanity check to make sure we haven't
12122            // left any junk around.
12123            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12124            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12125                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12126                removed.clear();
12127                for (PreferredActivity pa : pir.filterSet()) {
12128                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12129                        removed.add(pa);
12130                    }
12131                }
12132                if (removed.size() > 0) {
12133                    for (int r=0; r<removed.size(); r++) {
12134                        PreferredActivity pa = removed.get(r);
12135                        Slog.w(TAG, "Removing dangling preferred activity: "
12136                                + pa.mPref.mComponent);
12137                        pir.removeFilter(pa);
12138                    }
12139                    mSettings.writePackageRestrictionsLPr(
12140                            mSettings.mPreferredActivities.keyAt(i));
12141                }
12142            }
12143        }
12144        sUserManager.systemReady();
12145
12146        // Kick off any messages waiting for system ready
12147        if (mPostSystemReadyMessages != null) {
12148            for (Message msg : mPostSystemReadyMessages) {
12149                msg.sendToTarget();
12150            }
12151            mPostSystemReadyMessages = null;
12152        }
12153    }
12154
12155    @Override
12156    public boolean isSafeMode() {
12157        return mSafeMode;
12158    }
12159
12160    @Override
12161    public boolean hasSystemUidErrors() {
12162        return mHasSystemUidErrors;
12163    }
12164
12165    static String arrayToString(int[] array) {
12166        StringBuffer buf = new StringBuffer(128);
12167        buf.append('[');
12168        if (array != null) {
12169            for (int i=0; i<array.length; i++) {
12170                if (i > 0) buf.append(", ");
12171                buf.append(array[i]);
12172            }
12173        }
12174        buf.append(']');
12175        return buf.toString();
12176    }
12177
12178    static class DumpState {
12179        public static final int DUMP_LIBS = 1 << 0;
12180        public static final int DUMP_FEATURES = 1 << 1;
12181        public static final int DUMP_RESOLVERS = 1 << 2;
12182        public static final int DUMP_PERMISSIONS = 1 << 3;
12183        public static final int DUMP_PACKAGES = 1 << 4;
12184        public static final int DUMP_SHARED_USERS = 1 << 5;
12185        public static final int DUMP_MESSAGES = 1 << 6;
12186        public static final int DUMP_PROVIDERS = 1 << 7;
12187        public static final int DUMP_VERIFIERS = 1 << 8;
12188        public static final int DUMP_PREFERRED = 1 << 9;
12189        public static final int DUMP_PREFERRED_XML = 1 << 10;
12190        public static final int DUMP_KEYSETS = 1 << 11;
12191        public static final int DUMP_VERSION = 1 << 12;
12192        public static final int DUMP_INSTALLS = 1 << 13;
12193
12194        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12195
12196        private int mTypes;
12197
12198        private int mOptions;
12199
12200        private boolean mTitlePrinted;
12201
12202        private SharedUserSetting mSharedUser;
12203
12204        public boolean isDumping(int type) {
12205            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12206                return true;
12207            }
12208
12209            return (mTypes & type) != 0;
12210        }
12211
12212        public void setDump(int type) {
12213            mTypes |= type;
12214        }
12215
12216        public boolean isOptionEnabled(int option) {
12217            return (mOptions & option) != 0;
12218        }
12219
12220        public void setOptionEnabled(int option) {
12221            mOptions |= option;
12222        }
12223
12224        public boolean onTitlePrinted() {
12225            final boolean printed = mTitlePrinted;
12226            mTitlePrinted = true;
12227            return printed;
12228        }
12229
12230        public boolean getTitlePrinted() {
12231            return mTitlePrinted;
12232        }
12233
12234        public void setTitlePrinted(boolean enabled) {
12235            mTitlePrinted = enabled;
12236        }
12237
12238        public SharedUserSetting getSharedUser() {
12239            return mSharedUser;
12240        }
12241
12242        public void setSharedUser(SharedUserSetting user) {
12243            mSharedUser = user;
12244        }
12245    }
12246
12247    @Override
12248    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12249        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12250                != PackageManager.PERMISSION_GRANTED) {
12251            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12252                    + Binder.getCallingPid()
12253                    + ", uid=" + Binder.getCallingUid()
12254                    + " without permission "
12255                    + android.Manifest.permission.DUMP);
12256            return;
12257        }
12258
12259        DumpState dumpState = new DumpState();
12260        boolean fullPreferred = false;
12261        boolean checkin = false;
12262
12263        String packageName = null;
12264
12265        int opti = 0;
12266        while (opti < args.length) {
12267            String opt = args[opti];
12268            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12269                break;
12270            }
12271            opti++;
12272
12273            if ("-a".equals(opt)) {
12274                // Right now we only know how to print all.
12275            } else if ("-h".equals(opt)) {
12276                pw.println("Package manager dump options:");
12277                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12278                pw.println("    --checkin: dump for a checkin");
12279                pw.println("    -f: print details of intent filters");
12280                pw.println("    -h: print this help");
12281                pw.println("  cmd may be one of:");
12282                pw.println("    l[ibraries]: list known shared libraries");
12283                pw.println("    f[ibraries]: list device features");
12284                pw.println("    k[eysets]: print known keysets");
12285                pw.println("    r[esolvers]: dump intent resolvers");
12286                pw.println("    perm[issions]: dump permissions");
12287                pw.println("    pref[erred]: print preferred package settings");
12288                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12289                pw.println("    prov[iders]: dump content providers");
12290                pw.println("    p[ackages]: dump installed packages");
12291                pw.println("    s[hared-users]: dump shared user IDs");
12292                pw.println("    m[essages]: print collected runtime messages");
12293                pw.println("    v[erifiers]: print package verifier info");
12294                pw.println("    version: print database version info");
12295                pw.println("    write: write current settings now");
12296                pw.println("    <package.name>: info about given package");
12297                pw.println("    installs: details about install sessions");
12298                return;
12299            } else if ("--checkin".equals(opt)) {
12300                checkin = true;
12301            } else if ("-f".equals(opt)) {
12302                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12303            } else {
12304                pw.println("Unknown argument: " + opt + "; use -h for help");
12305            }
12306        }
12307
12308        // Is the caller requesting to dump a particular piece of data?
12309        if (opti < args.length) {
12310            String cmd = args[opti];
12311            opti++;
12312            // Is this a package name?
12313            if ("android".equals(cmd) || cmd.contains(".")) {
12314                packageName = cmd;
12315                // When dumping a single package, we always dump all of its
12316                // filter information since the amount of data will be reasonable.
12317                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12318            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12319                dumpState.setDump(DumpState.DUMP_LIBS);
12320            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12321                dumpState.setDump(DumpState.DUMP_FEATURES);
12322            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12323                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12324            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12325                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12326            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12327                dumpState.setDump(DumpState.DUMP_PREFERRED);
12328            } else if ("preferred-xml".equals(cmd)) {
12329                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12330                if (opti < args.length && "--full".equals(args[opti])) {
12331                    fullPreferred = true;
12332                    opti++;
12333                }
12334            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12335                dumpState.setDump(DumpState.DUMP_PACKAGES);
12336            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12337                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12338            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12339                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12340            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12341                dumpState.setDump(DumpState.DUMP_MESSAGES);
12342            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12343                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12344            } else if ("version".equals(cmd)) {
12345                dumpState.setDump(DumpState.DUMP_VERSION);
12346            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12347                dumpState.setDump(DumpState.DUMP_KEYSETS);
12348            } else if ("installs".equals(cmd)) {
12349                dumpState.setDump(DumpState.DUMP_INSTALLS);
12350            } else if ("write".equals(cmd)) {
12351                synchronized (mPackages) {
12352                    mSettings.writeLPr();
12353                    pw.println("Settings written.");
12354                    return;
12355                }
12356            }
12357        }
12358
12359        if (checkin) {
12360            pw.println("vers,1");
12361        }
12362
12363        // reader
12364        synchronized (mPackages) {
12365            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12366                if (!checkin) {
12367                    if (dumpState.onTitlePrinted())
12368                        pw.println();
12369                    pw.println("Database versions:");
12370                    pw.print("  SDK Version:");
12371                    pw.print(" internal=");
12372                    pw.print(mSettings.mInternalSdkPlatform);
12373                    pw.print(" external=");
12374                    pw.println(mSettings.mExternalSdkPlatform);
12375                    pw.print("  DB Version:");
12376                    pw.print(" internal=");
12377                    pw.print(mSettings.mInternalDatabaseVersion);
12378                    pw.print(" external=");
12379                    pw.println(mSettings.mExternalDatabaseVersion);
12380                }
12381            }
12382
12383            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12384                if (!checkin) {
12385                    if (dumpState.onTitlePrinted())
12386                        pw.println();
12387                    pw.println("Verifiers:");
12388                    pw.print("  Required: ");
12389                    pw.print(mRequiredVerifierPackage);
12390                    pw.print(" (uid=");
12391                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12392                    pw.println(")");
12393                } else if (mRequiredVerifierPackage != null) {
12394                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12395                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12396                }
12397            }
12398
12399            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12400                boolean printedHeader = false;
12401                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12402                while (it.hasNext()) {
12403                    String name = it.next();
12404                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12405                    if (!checkin) {
12406                        if (!printedHeader) {
12407                            if (dumpState.onTitlePrinted())
12408                                pw.println();
12409                            pw.println("Libraries:");
12410                            printedHeader = true;
12411                        }
12412                        pw.print("  ");
12413                    } else {
12414                        pw.print("lib,");
12415                    }
12416                    pw.print(name);
12417                    if (!checkin) {
12418                        pw.print(" -> ");
12419                    }
12420                    if (ent.path != null) {
12421                        if (!checkin) {
12422                            pw.print("(jar) ");
12423                            pw.print(ent.path);
12424                        } else {
12425                            pw.print(",jar,");
12426                            pw.print(ent.path);
12427                        }
12428                    } else {
12429                        if (!checkin) {
12430                            pw.print("(apk) ");
12431                            pw.print(ent.apk);
12432                        } else {
12433                            pw.print(",apk,");
12434                            pw.print(ent.apk);
12435                        }
12436                    }
12437                    pw.println();
12438                }
12439            }
12440
12441            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12442                if (dumpState.onTitlePrinted())
12443                    pw.println();
12444                if (!checkin) {
12445                    pw.println("Features:");
12446                }
12447                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12448                while (it.hasNext()) {
12449                    String name = it.next();
12450                    if (!checkin) {
12451                        pw.print("  ");
12452                    } else {
12453                        pw.print("feat,");
12454                    }
12455                    pw.println(name);
12456                }
12457            }
12458
12459            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12460                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12461                        : "Activity Resolver Table:", "  ", packageName,
12462                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12463                    dumpState.setTitlePrinted(true);
12464                }
12465                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12466                        : "Receiver Resolver Table:", "  ", packageName,
12467                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12468                    dumpState.setTitlePrinted(true);
12469                }
12470                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12471                        : "Service Resolver Table:", "  ", packageName,
12472                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12473                    dumpState.setTitlePrinted(true);
12474                }
12475                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12476                        : "Provider Resolver Table:", "  ", packageName,
12477                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12478                    dumpState.setTitlePrinted(true);
12479                }
12480            }
12481
12482            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12483                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12484                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12485                    int user = mSettings.mPreferredActivities.keyAt(i);
12486                    if (pir.dump(pw,
12487                            dumpState.getTitlePrinted()
12488                                ? "\nPreferred Activities User " + user + ":"
12489                                : "Preferred Activities User " + user + ":", "  ",
12490                            packageName, true)) {
12491                        dumpState.setTitlePrinted(true);
12492                    }
12493                }
12494            }
12495
12496            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12497                pw.flush();
12498                FileOutputStream fout = new FileOutputStream(fd);
12499                BufferedOutputStream str = new BufferedOutputStream(fout);
12500                XmlSerializer serializer = new FastXmlSerializer();
12501                try {
12502                    serializer.setOutput(str, "utf-8");
12503                    serializer.startDocument(null, true);
12504                    serializer.setFeature(
12505                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12506                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12507                    serializer.endDocument();
12508                    serializer.flush();
12509                } catch (IllegalArgumentException e) {
12510                    pw.println("Failed writing: " + e);
12511                } catch (IllegalStateException e) {
12512                    pw.println("Failed writing: " + e);
12513                } catch (IOException e) {
12514                    pw.println("Failed writing: " + e);
12515                }
12516            }
12517
12518            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12519                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12520                if (packageName == null) {
12521                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12522                        if (iperm == 0) {
12523                            if (dumpState.onTitlePrinted())
12524                                pw.println();
12525                            pw.println("AppOp Permissions:");
12526                        }
12527                        pw.print("  AppOp Permission ");
12528                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12529                        pw.println(":");
12530                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12531                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12532                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12533                        }
12534                    }
12535                }
12536            }
12537
12538            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12539                boolean printedSomething = false;
12540                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12541                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12542                        continue;
12543                    }
12544                    if (!printedSomething) {
12545                        if (dumpState.onTitlePrinted())
12546                            pw.println();
12547                        pw.println("Registered ContentProviders:");
12548                        printedSomething = true;
12549                    }
12550                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12551                    pw.print("    "); pw.println(p.toString());
12552                }
12553                printedSomething = false;
12554                for (Map.Entry<String, PackageParser.Provider> entry :
12555                        mProvidersByAuthority.entrySet()) {
12556                    PackageParser.Provider p = entry.getValue();
12557                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12558                        continue;
12559                    }
12560                    if (!printedSomething) {
12561                        if (dumpState.onTitlePrinted())
12562                            pw.println();
12563                        pw.println("ContentProvider Authorities:");
12564                        printedSomething = true;
12565                    }
12566                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12567                    pw.print("    "); pw.println(p.toString());
12568                    if (p.info != null && p.info.applicationInfo != null) {
12569                        final String appInfo = p.info.applicationInfo.toString();
12570                        pw.print("      applicationInfo="); pw.println(appInfo);
12571                    }
12572                }
12573            }
12574
12575            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12576                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12577            }
12578
12579            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12580                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12581            }
12582
12583            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12584                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12585            }
12586
12587            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12588                // XXX should handle packageName != null by dumping only install data that
12589                // the given package is involved with.
12590                if (dumpState.onTitlePrinted()) pw.println();
12591                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12592            }
12593
12594            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12595                if (dumpState.onTitlePrinted()) pw.println();
12596                mSettings.dumpReadMessagesLPr(pw, dumpState);
12597
12598                pw.println();
12599                pw.println("Package warning messages:");
12600                final File fname = getSettingsProblemFile();
12601                FileInputStream in = null;
12602                try {
12603                    in = new FileInputStream(fname);
12604                    final int avail = in.available();
12605                    final byte[] data = new byte[avail];
12606                    in.read(data);
12607                    pw.print(new String(data));
12608                } catch (FileNotFoundException e) {
12609                } catch (IOException e) {
12610                } finally {
12611                    if (in != null) {
12612                        try {
12613                            in.close();
12614                        } catch (IOException e) {
12615                        }
12616                    }
12617                }
12618            }
12619
12620            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
12621                BufferedReader in = null;
12622                String line = null;
12623                try {
12624                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12625                    while ((line = in.readLine()) != null) {
12626                        pw.print("msg,");
12627                        pw.println(line);
12628                    }
12629                } catch (IOException ignored) {
12630                } finally {
12631                    IoUtils.closeQuietly(in);
12632                }
12633            }
12634        }
12635    }
12636
12637    // ------- apps on sdcard specific code -------
12638    static final boolean DEBUG_SD_INSTALL = false;
12639
12640    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12641
12642    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12643
12644    private boolean mMediaMounted = false;
12645
12646    static String getEncryptKey() {
12647        try {
12648            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12649                    SD_ENCRYPTION_KEYSTORE_NAME);
12650            if (sdEncKey == null) {
12651                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12652                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12653                if (sdEncKey == null) {
12654                    Slog.e(TAG, "Failed to create encryption keys");
12655                    return null;
12656                }
12657            }
12658            return sdEncKey;
12659        } catch (NoSuchAlgorithmException nsae) {
12660            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12661            return null;
12662        } catch (IOException ioe) {
12663            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12664            return null;
12665        }
12666    }
12667
12668    /*
12669     * Update media status on PackageManager.
12670     */
12671    @Override
12672    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12673        int callingUid = Binder.getCallingUid();
12674        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12675            throw new SecurityException("Media status can only be updated by the system");
12676        }
12677        // reader; this apparently protects mMediaMounted, but should probably
12678        // be a different lock in that case.
12679        synchronized (mPackages) {
12680            Log.i(TAG, "Updating external media status from "
12681                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12682                    + (mediaStatus ? "mounted" : "unmounted"));
12683            if (DEBUG_SD_INSTALL)
12684                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12685                        + ", mMediaMounted=" + mMediaMounted);
12686            if (mediaStatus == mMediaMounted) {
12687                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12688                        : 0, -1);
12689                mHandler.sendMessage(msg);
12690                return;
12691            }
12692            mMediaMounted = mediaStatus;
12693        }
12694        // Queue up an async operation since the package installation may take a
12695        // little while.
12696        mHandler.post(new Runnable() {
12697            public void run() {
12698                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12699            }
12700        });
12701    }
12702
12703    /**
12704     * Called by MountService when the initial ASECs to scan are available.
12705     * Should block until all the ASEC containers are finished being scanned.
12706     */
12707    public void scanAvailableAsecs() {
12708        updateExternalMediaStatusInner(true, false, false);
12709        if (mShouldRestoreconData) {
12710            SELinuxMMAC.setRestoreconDone();
12711            mShouldRestoreconData = false;
12712        }
12713    }
12714
12715    /*
12716     * Collect information of applications on external media, map them against
12717     * existing containers and update information based on current mount status.
12718     * Please note that we always have to report status if reportStatus has been
12719     * set to true especially when unloading packages.
12720     */
12721    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12722            boolean externalStorage) {
12723        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12724        int[] uidArr = EmptyArray.INT;
12725
12726        final String[] list = PackageHelper.getSecureContainerList();
12727        if (ArrayUtils.isEmpty(list)) {
12728            Log.i(TAG, "No secure containers found");
12729        } else {
12730            // Process list of secure containers and categorize them
12731            // as active or stale based on their package internal state.
12732
12733            // reader
12734            synchronized (mPackages) {
12735                for (String cid : list) {
12736                    // Leave stages untouched for now; installer service owns them
12737                    if (PackageInstallerService.isStageName(cid)) continue;
12738
12739                    if (DEBUG_SD_INSTALL)
12740                        Log.i(TAG, "Processing container " + cid);
12741                    String pkgName = getAsecPackageName(cid);
12742                    if (pkgName == null) {
12743                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12744                        continue;
12745                    }
12746                    if (DEBUG_SD_INSTALL)
12747                        Log.i(TAG, "Looking for pkg : " + pkgName);
12748
12749                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12750                    if (ps == null) {
12751                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12752                        continue;
12753                    }
12754
12755                    /*
12756                     * Skip packages that are not external if we're unmounting
12757                     * external storage.
12758                     */
12759                    if (externalStorage && !isMounted && !isExternal(ps)) {
12760                        continue;
12761                    }
12762
12763                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12764                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12765                    // The package status is changed only if the code path
12766                    // matches between settings and the container id.
12767                    if (ps.codePathString != null
12768                            && ps.codePathString.startsWith(args.getCodePath())) {
12769                        if (DEBUG_SD_INSTALL) {
12770                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12771                                    + " at code path: " + ps.codePathString);
12772                        }
12773
12774                        // We do have a valid package installed on sdcard
12775                        processCids.put(args, ps.codePathString);
12776                        final int uid = ps.appId;
12777                        if (uid != -1) {
12778                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12779                        }
12780                    } else {
12781                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12782                                + ps.codePathString);
12783                    }
12784                }
12785            }
12786
12787            Arrays.sort(uidArr);
12788        }
12789
12790        // Process packages with valid entries.
12791        if (isMounted) {
12792            if (DEBUG_SD_INSTALL)
12793                Log.i(TAG, "Loading packages");
12794            loadMediaPackages(processCids, uidArr);
12795            startCleaningPackages();
12796            mInstallerService.onSecureContainersAvailable();
12797        } else {
12798            if (DEBUG_SD_INSTALL)
12799                Log.i(TAG, "Unloading packages");
12800            unloadMediaPackages(processCids, uidArr, reportStatus);
12801        }
12802    }
12803
12804    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12805            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12806        int size = pkgList.size();
12807        if (size > 0) {
12808            // Send broadcasts here
12809            Bundle extras = new Bundle();
12810            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12811                    .toArray(new String[size]));
12812            if (uidArr != null) {
12813                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12814            }
12815            if (replacing) {
12816                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12817            }
12818            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12819                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12820            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12821        }
12822    }
12823
12824   /*
12825     * Look at potentially valid container ids from processCids If package
12826     * information doesn't match the one on record or package scanning fails,
12827     * the cid is added to list of removeCids. We currently don't delete stale
12828     * containers.
12829     */
12830    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12831        ArrayList<String> pkgList = new ArrayList<String>();
12832        Set<AsecInstallArgs> keys = processCids.keySet();
12833
12834        for (AsecInstallArgs args : keys) {
12835            String codePath = processCids.get(args);
12836            if (DEBUG_SD_INSTALL)
12837                Log.i(TAG, "Loading container : " + args.cid);
12838            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12839            try {
12840                // Make sure there are no container errors first.
12841                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12842                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12843                            + " when installing from sdcard");
12844                    continue;
12845                }
12846                // Check code path here.
12847                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12848                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12849                            + " does not match one in settings " + codePath);
12850                    continue;
12851                }
12852                // Parse package
12853                int parseFlags = mDefParseFlags;
12854                if (args.isExternal()) {
12855                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12856                }
12857                if (args.isFwdLocked()) {
12858                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12859                }
12860
12861                synchronized (mInstallLock) {
12862                    PackageParser.Package pkg = null;
12863                    try {
12864                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12865                    } catch (PackageManagerException e) {
12866                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12867                    }
12868                    // Scan the package
12869                    if (pkg != null) {
12870                        /*
12871                         * TODO why is the lock being held? doPostInstall is
12872                         * called in other places without the lock. This needs
12873                         * to be straightened out.
12874                         */
12875                        // writer
12876                        synchronized (mPackages) {
12877                            retCode = PackageManager.INSTALL_SUCCEEDED;
12878                            pkgList.add(pkg.packageName);
12879                            // Post process args
12880                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12881                                    pkg.applicationInfo.uid);
12882                        }
12883                    } else {
12884                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12885                    }
12886                }
12887
12888            } finally {
12889                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12890                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12891                }
12892            }
12893        }
12894        // writer
12895        synchronized (mPackages) {
12896            // If the platform SDK has changed since the last time we booted,
12897            // we need to re-grant app permission to catch any new ones that
12898            // appear. This is really a hack, and means that apps can in some
12899            // cases get permissions that the user didn't initially explicitly
12900            // allow... it would be nice to have some better way to handle
12901            // this situation.
12902            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12903            if (regrantPermissions)
12904                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12905                        + mSdkVersion + "; regranting permissions for external storage");
12906            mSettings.mExternalSdkPlatform = mSdkVersion;
12907
12908            // Make sure group IDs have been assigned, and any permission
12909            // changes in other apps are accounted for
12910            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12911                    | (regrantPermissions
12912                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12913                            : 0));
12914
12915            mSettings.updateExternalDatabaseVersion();
12916
12917            // can downgrade to reader
12918            // Persist settings
12919            mSettings.writeLPr();
12920        }
12921        // Send a broadcast to let everyone know we are done processing
12922        if (pkgList.size() > 0) {
12923            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12924        }
12925    }
12926
12927   /*
12928     * Utility method to unload a list of specified containers
12929     */
12930    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12931        // Just unmount all valid containers.
12932        for (AsecInstallArgs arg : cidArgs) {
12933            synchronized (mInstallLock) {
12934                arg.doPostDeleteLI(false);
12935           }
12936       }
12937   }
12938
12939    /*
12940     * Unload packages mounted on external media. This involves deleting package
12941     * data from internal structures, sending broadcasts about diabled packages,
12942     * gc'ing to free up references, unmounting all secure containers
12943     * corresponding to packages on external media, and posting a
12944     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
12945     * that we always have to post this message if status has been requested no
12946     * matter what.
12947     */
12948    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
12949            final boolean reportStatus) {
12950        if (DEBUG_SD_INSTALL)
12951            Log.i(TAG, "unloading media packages");
12952        ArrayList<String> pkgList = new ArrayList<String>();
12953        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
12954        final Set<AsecInstallArgs> keys = processCids.keySet();
12955        for (AsecInstallArgs args : keys) {
12956            String pkgName = args.getPackageName();
12957            if (DEBUG_SD_INSTALL)
12958                Log.i(TAG, "Trying to unload pkg : " + pkgName);
12959            // Delete package internally
12960            PackageRemovedInfo outInfo = new PackageRemovedInfo();
12961            synchronized (mInstallLock) {
12962                boolean res = deletePackageLI(pkgName, null, false, null, null,
12963                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
12964                if (res) {
12965                    pkgList.add(pkgName);
12966                } else {
12967                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
12968                    failedList.add(args);
12969                }
12970            }
12971        }
12972
12973        // reader
12974        synchronized (mPackages) {
12975            // We didn't update the settings after removing each package;
12976            // write them now for all packages.
12977            mSettings.writeLPr();
12978        }
12979
12980        // We have to absolutely send UPDATED_MEDIA_STATUS only
12981        // after confirming that all the receivers processed the ordered
12982        // broadcast when packages get disabled, force a gc to clean things up.
12983        // and unload all the containers.
12984        if (pkgList.size() > 0) {
12985            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
12986                    new IIntentReceiver.Stub() {
12987                public void performReceive(Intent intent, int resultCode, String data,
12988                        Bundle extras, boolean ordered, boolean sticky,
12989                        int sendingUser) throws RemoteException {
12990                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
12991                            reportStatus ? 1 : 0, 1, keys);
12992                    mHandler.sendMessage(msg);
12993                }
12994            });
12995        } else {
12996            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
12997                    keys);
12998            mHandler.sendMessage(msg);
12999        }
13000    }
13001
13002    /** Binder call */
13003    @Override
13004    public void movePackage(final String packageName, final IPackageMoveObserver observer,
13005            final int flags) {
13006        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
13007        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
13008        int returnCode = PackageManager.MOVE_SUCCEEDED;
13009        int currInstallFlags = 0;
13010        int newInstallFlags = 0;
13011
13012        File codeFile = null;
13013        String installerPackageName = null;
13014        String packageAbiOverride = null;
13015
13016        // reader
13017        synchronized (mPackages) {
13018            final PackageParser.Package pkg = mPackages.get(packageName);
13019            final PackageSetting ps = mSettings.mPackages.get(packageName);
13020            if (pkg == null || ps == null) {
13021                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13022            } else {
13023                // Disable moving fwd locked apps and system packages
13024                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
13025                    Slog.w(TAG, "Cannot move system application");
13026                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13027                } else if (pkg.mOperationPending) {
13028                    Slog.w(TAG, "Attempt to move package which has pending operations");
13029                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13030                } else {
13031                    // Find install location first
13032                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13033                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13034                        Slog.w(TAG, "Ambigous flags specified for move location.");
13035                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13036                    } else {
13037                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13038                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13039                        currInstallFlags = isExternal(pkg)
13040                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13041
13042                        if (newInstallFlags == currInstallFlags) {
13043                            Slog.w(TAG, "No move required. Trying to move to same location");
13044                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13045                        } else {
13046                            if (isForwardLocked(pkg)) {
13047                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13048                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13049                            }
13050                        }
13051                    }
13052                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13053                        pkg.mOperationPending = true;
13054                    }
13055                }
13056
13057                codeFile = new File(pkg.codePath);
13058                installerPackageName = ps.installerPackageName;
13059                packageAbiOverride = ps.cpuAbiOverrideString;
13060            }
13061        }
13062
13063        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13064            try {
13065                observer.packageMoved(packageName, returnCode);
13066            } catch (RemoteException ignored) {
13067            }
13068            return;
13069        }
13070
13071        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
13072            @Override
13073            public void onUserActionRequired(Intent intent) throws RemoteException {
13074                throw new IllegalStateException();
13075            }
13076
13077            @Override
13078            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
13079                    Bundle extras) throws RemoteException {
13080                Slog.d(TAG, "Install result for move: "
13081                        + PackageManager.installStatusToString(returnCode, msg));
13082
13083                // We usually have a new package now after the install, but if
13084                // we failed we need to clear the pending flag on the original
13085                // package object.
13086                synchronized (mPackages) {
13087                    final PackageParser.Package pkg = mPackages.get(packageName);
13088                    if (pkg != null) {
13089                        pkg.mOperationPending = false;
13090                    }
13091                }
13092
13093                final int status = PackageManager.installStatusToPublicStatus(returnCode);
13094                switch (status) {
13095                    case PackageInstaller.STATUS_SUCCESS:
13096                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
13097                        break;
13098                    case PackageInstaller.STATUS_FAILURE_STORAGE:
13099                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
13100                        break;
13101                    default:
13102                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
13103                        break;
13104                }
13105            }
13106        };
13107
13108        // Treat a move like reinstalling an existing app, which ensures that we
13109        // process everythign uniformly, like unpacking native libraries.
13110        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
13111
13112        final Message msg = mHandler.obtainMessage(INIT_COPY);
13113        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
13114        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
13115                installerPackageName, null, user, packageAbiOverride);
13116        mHandler.sendMessage(msg);
13117    }
13118
13119    @Override
13120    public boolean setInstallLocation(int loc) {
13121        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13122                null);
13123        if (getInstallLocation() == loc) {
13124            return true;
13125        }
13126        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13127                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13128            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13129                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13130            return true;
13131        }
13132        return false;
13133   }
13134
13135    @Override
13136    public int getInstallLocation() {
13137        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13138                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13139                PackageHelper.APP_INSTALL_AUTO);
13140    }
13141
13142    /** Called by UserManagerService */
13143    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13144        mDirtyUsers.remove(userHandle);
13145        mSettings.removeUserLPw(userHandle);
13146        mPendingBroadcasts.remove(userHandle);
13147        if (mInstaller != null) {
13148            // Technically, we shouldn't be doing this with the package lock
13149            // held.  However, this is very rare, and there is already so much
13150            // other disk I/O going on, that we'll let it slide for now.
13151            mInstaller.removeUserDataDirs(userHandle);
13152        }
13153        mUserNeedsBadging.delete(userHandle);
13154        removeUnusedPackagesLILPw(userManager, userHandle);
13155    }
13156
13157    /**
13158     * We're removing userHandle and would like to remove any downloaded packages
13159     * that are no longer in use by any other user.
13160     * @param userHandle the user being removed
13161     */
13162    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13163        final boolean DEBUG_CLEAN_APKS = false;
13164        int [] users = userManager.getUserIdsLPr();
13165        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13166        while (psit.hasNext()) {
13167            PackageSetting ps = psit.next();
13168            if (ps.pkg == null) {
13169                continue;
13170            }
13171            final String packageName = ps.pkg.packageName;
13172            // Skip over if system app
13173            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13174                continue;
13175            }
13176            if (DEBUG_CLEAN_APKS) {
13177                Slog.i(TAG, "Checking package " + packageName);
13178            }
13179            boolean keep = false;
13180            for (int i = 0; i < users.length; i++) {
13181                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13182                    keep = true;
13183                    if (DEBUG_CLEAN_APKS) {
13184                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13185                                + users[i]);
13186                    }
13187                    break;
13188                }
13189            }
13190            if (!keep) {
13191                if (DEBUG_CLEAN_APKS) {
13192                    Slog.i(TAG, "  Removing package " + packageName);
13193                }
13194                mHandler.post(new Runnable() {
13195                    public void run() {
13196                        deletePackageX(packageName, userHandle, 0);
13197                    } //end run
13198                });
13199            }
13200        }
13201    }
13202
13203    /** Called by UserManagerService */
13204    void createNewUserLILPw(int userHandle, File path) {
13205        if (mInstaller != null) {
13206            mInstaller.createUserConfig(userHandle);
13207            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13208        }
13209    }
13210
13211    @Override
13212    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13213        mContext.enforceCallingOrSelfPermission(
13214                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13215                "Only package verification agents can read the verifier device identity");
13216
13217        synchronized (mPackages) {
13218            return mSettings.getVerifierDeviceIdentityLPw();
13219        }
13220    }
13221
13222    @Override
13223    public void setPermissionEnforced(String permission, boolean enforced) {
13224        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13225        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13226            synchronized (mPackages) {
13227                if (mSettings.mReadExternalStorageEnforced == null
13228                        || mSettings.mReadExternalStorageEnforced != enforced) {
13229                    mSettings.mReadExternalStorageEnforced = enforced;
13230                    mSettings.writeLPr();
13231                }
13232            }
13233            // kill any non-foreground processes so we restart them and
13234            // grant/revoke the GID.
13235            final IActivityManager am = ActivityManagerNative.getDefault();
13236            if (am != null) {
13237                final long token = Binder.clearCallingIdentity();
13238                try {
13239                    am.killProcessesBelowForeground("setPermissionEnforcement");
13240                } catch (RemoteException e) {
13241                } finally {
13242                    Binder.restoreCallingIdentity(token);
13243                }
13244            }
13245        } else {
13246            throw new IllegalArgumentException("No selective enforcement for " + permission);
13247        }
13248    }
13249
13250    @Override
13251    @Deprecated
13252    public boolean isPermissionEnforced(String permission) {
13253        return true;
13254    }
13255
13256    @Override
13257    public boolean isStorageLow() {
13258        final long token = Binder.clearCallingIdentity();
13259        try {
13260            final DeviceStorageMonitorInternal
13261                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13262            if (dsm != null) {
13263                return dsm.isMemoryLow();
13264            } else {
13265                return false;
13266            }
13267        } finally {
13268            Binder.restoreCallingIdentity(token);
13269        }
13270    }
13271
13272    @Override
13273    public IPackageInstaller getPackageInstaller() {
13274        return mInstallerService;
13275    }
13276
13277    private boolean userNeedsBadging(int userId) {
13278        int index = mUserNeedsBadging.indexOfKey(userId);
13279        if (index < 0) {
13280            final UserInfo userInfo;
13281            final long token = Binder.clearCallingIdentity();
13282            try {
13283                userInfo = sUserManager.getUserInfo(userId);
13284            } finally {
13285                Binder.restoreCallingIdentity(token);
13286            }
13287            final boolean b;
13288            if (userInfo != null && userInfo.isManagedProfile()) {
13289                b = true;
13290            } else {
13291                b = false;
13292            }
13293            mUserNeedsBadging.put(userId, b);
13294            return b;
13295        }
13296        return mUserNeedsBadging.valueAt(index);
13297    }
13298
13299    @Override
13300    public KeySet getKeySetByAlias(String packageName, String alias) {
13301        if (packageName == null || alias == null) {
13302            return null;
13303        }
13304        synchronized(mPackages) {
13305            final PackageParser.Package pkg = mPackages.get(packageName);
13306            if (pkg == null) {
13307                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13308                throw new IllegalArgumentException("Unknown package: " + packageName);
13309            }
13310            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13311            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13312        }
13313    }
13314
13315    @Override
13316    public KeySet getSigningKeySet(String packageName) {
13317        if (packageName == null) {
13318            return null;
13319        }
13320        synchronized(mPackages) {
13321            final PackageParser.Package pkg = mPackages.get(packageName);
13322            if (pkg == null) {
13323                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13324                throw new IllegalArgumentException("Unknown package: " + packageName);
13325            }
13326            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13327                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13328                throw new SecurityException("May not access signing KeySet of other apps.");
13329            }
13330            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13331            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13332        }
13333    }
13334
13335    @Override
13336    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13337        if (packageName == null || ks == null) {
13338            return false;
13339        }
13340        synchronized(mPackages) {
13341            final PackageParser.Package pkg = mPackages.get(packageName);
13342            if (pkg == null) {
13343                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13344                throw new IllegalArgumentException("Unknown package: " + packageName);
13345            }
13346            IBinder ksh = ks.getToken();
13347            if (ksh instanceof KeySetHandle) {
13348                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13349                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13350            }
13351            return false;
13352        }
13353    }
13354
13355    @Override
13356    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13357        if (packageName == null || ks == null) {
13358            return false;
13359        }
13360        synchronized(mPackages) {
13361            final PackageParser.Package pkg = mPackages.get(packageName);
13362            if (pkg == null) {
13363                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13364                throw new IllegalArgumentException("Unknown package: " + packageName);
13365            }
13366            IBinder ksh = ks.getToken();
13367            if (ksh instanceof KeySetHandle) {
13368                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13369                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13370            }
13371            return false;
13372        }
13373    }
13374}
13375