PackageManagerService.java revision 33d92c56781f6058c9e682737a06c41f3a2d2f3a
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    final boolean mIsUpgrade;
336
337    // This is where all application persistent data goes.
338    final File mAppDataDir;
339
340    // This is where all application persistent data goes for secondary users.
341    final File mUserAppDataDir;
342
343    /** The location for ASEC container files on internal storage. */
344    final String mAsecInternalPath;
345
346    // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages
347    // LOCK HELD.  Can be called with mInstallLock held.
348    final Installer mInstaller;
349
350    /** Directory where installed third-party apps stored */
351    final File mAppInstallDir;
352
353    /**
354     * Directory to which applications installed internally have their
355     * 32 bit native libraries copied.
356     */
357    private File mAppLib32InstallDir;
358
359    // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked
360    // apps.
361    final File mDrmAppPrivateInstallDir;
362
363    // ----------------------------------------------------------------
364
365    // Lock for state used when installing and doing other long running
366    // operations.  Methods that must be called with this lock held have
367    // the suffix "LI".
368    final Object mInstallLock = new Object();
369
370    // ----------------------------------------------------------------
371
372    // Keys are String (package name), values are Package.  This also serves
373    // as the lock for the global state.  Methods that must be called with
374    // this lock held have the prefix "LP".
375    final HashMap<String, PackageParser.Package> mPackages =
376            new HashMap<String, PackageParser.Package>();
377
378    // Tracks available target package names -> overlay package paths.
379    final HashMap<String, HashMap<String, PackageParser.Package>> mOverlays =
380        new HashMap<String, HashMap<String, PackageParser.Package>>();
381
382    final Settings mSettings;
383    boolean mRestoredSettings;
384
385    // System configuration read by SystemConfig.
386    final int[] mGlobalGids;
387    final SparseArray<HashSet<String>> mSystemPermissions;
388    final HashMap<String, FeatureInfo> mAvailableFeatures;
389
390    // If mac_permissions.xml was found for seinfo labeling.
391    boolean mFoundPolicyFile;
392
393    // If a recursive restorecon of /data/data/<pkg> is needed.
394    private boolean mShouldRestoreconData = SELinuxMMAC.shouldRestorecon();
395
396    public static final class SharedLibraryEntry {
397        public final String path;
398        public final String apk;
399
400        SharedLibraryEntry(String _path, String _apk) {
401            path = _path;
402            apk = _apk;
403        }
404    }
405
406    // Currently known shared libraries.
407    final HashMap<String, SharedLibraryEntry> mSharedLibraries =
408            new HashMap<String, SharedLibraryEntry>();
409
410    // All available activities, for your resolving pleasure.
411    final ActivityIntentResolver mActivities =
412            new ActivityIntentResolver();
413
414    // All available receivers, for your resolving pleasure.
415    final ActivityIntentResolver mReceivers =
416            new ActivityIntentResolver();
417
418    // All available services, for your resolving pleasure.
419    final ServiceIntentResolver mServices = new ServiceIntentResolver();
420
421    // All available providers, for your resolving pleasure.
422    final ProviderIntentResolver mProviders = new ProviderIntentResolver();
423
424    // Mapping from provider base names (first directory in content URI codePath)
425    // to the provider information.
426    final HashMap<String, PackageParser.Provider> mProvidersByAuthority =
427            new HashMap<String, PackageParser.Provider>();
428
429    // Mapping from instrumentation class names to info about them.
430    final HashMap<ComponentName, PackageParser.Instrumentation> mInstrumentation =
431            new HashMap<ComponentName, PackageParser.Instrumentation>();
432
433    // Mapping from permission names to info about them.
434    final HashMap<String, PackageParser.PermissionGroup> mPermissionGroups =
435            new HashMap<String, PackageParser.PermissionGroup>();
436
437    // Packages whose data we have transfered into another package, thus
438    // should no longer exist.
439    final HashSet<String> mTransferedPackages = new HashSet<String>();
440
441    // Broadcast actions that are only available to the system.
442    final HashSet<String> mProtectedBroadcasts = new HashSet<String>();
443
444    /** List of packages waiting for verification. */
445    final SparseArray<PackageVerificationState> mPendingVerification
446            = new SparseArray<PackageVerificationState>();
447
448    /** Set of packages associated with each app op permission. */
449    final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>();
450
451    final PackageInstallerService mInstallerService;
452
453    HashSet<PackageParser.Package> mDeferredDexOpt = null;
454
455    // Cache of users who need badging.
456    SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray();
457
458    /** Token for keys in mPendingVerification. */
459    private int mPendingVerificationToken = 0;
460
461    volatile boolean mSystemReady;
462    volatile boolean mSafeMode;
463    volatile boolean mHasSystemUidErrors;
464
465    ApplicationInfo mAndroidApplication;
466    final ActivityInfo mResolveActivity = new ActivityInfo();
467    final ResolveInfo mResolveInfo = new ResolveInfo();
468    ComponentName mResolveComponentName;
469    PackageParser.Package mPlatformPackage;
470    ComponentName mCustomResolverComponentName;
471
472    boolean mResolverReplaced = false;
473
474    // Set of pending broadcasts for aggregating enable/disable of components.
475    static class PendingPackageBroadcasts {
476        // for each user id, a map of <package name -> components within that package>
477        final SparseArray<HashMap<String, ArrayList<String>>> mUidMap;
478
479        public PendingPackageBroadcasts() {
480            mUidMap = new SparseArray<HashMap<String, ArrayList<String>>>(2);
481        }
482
483        public ArrayList<String> get(int userId, String packageName) {
484            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
485            return packages.get(packageName);
486        }
487
488        public void put(int userId, String packageName, ArrayList<String> components) {
489            HashMap<String, ArrayList<String>> packages = getOrAllocate(userId);
490            packages.put(packageName, components);
491        }
492
493        public void remove(int userId, String packageName) {
494            HashMap<String, ArrayList<String>> packages = mUidMap.get(userId);
495            if (packages != null) {
496                packages.remove(packageName);
497            }
498        }
499
500        public void remove(int userId) {
501            mUidMap.remove(userId);
502        }
503
504        public int userIdCount() {
505            return mUidMap.size();
506        }
507
508        public int userIdAt(int n) {
509            return mUidMap.keyAt(n);
510        }
511
512        public HashMap<String, ArrayList<String>> packagesForUserId(int userId) {
513            return mUidMap.get(userId);
514        }
515
516        public int size() {
517            // total number of pending broadcast entries across all userIds
518            int num = 0;
519            for (int i = 0; i< mUidMap.size(); i++) {
520                num += mUidMap.valueAt(i).size();
521            }
522            return num;
523        }
524
525        public void clear() {
526            mUidMap.clear();
527        }
528
529        private HashMap<String, ArrayList<String>> getOrAllocate(int userId) {
530            HashMap<String, ArrayList<String>> map = mUidMap.get(userId);
531            if (map == null) {
532                map = new HashMap<String, ArrayList<String>>();
533                mUidMap.put(userId, map);
534            }
535            return map;
536        }
537    }
538    final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts();
539
540    // Service Connection to remote media container service to copy
541    // package uri's from external media onto secure containers
542    // or internal storage.
543    private IMediaContainerService mContainerService = null;
544
545    static final int SEND_PENDING_BROADCAST = 1;
546    static final int MCS_BOUND = 3;
547    static final int END_COPY = 4;
548    static final int INIT_COPY = 5;
549    static final int MCS_UNBIND = 6;
550    static final int START_CLEANING_PACKAGE = 7;
551    static final int FIND_INSTALL_LOC = 8;
552    static final int POST_INSTALL = 9;
553    static final int MCS_RECONNECT = 10;
554    static final int MCS_GIVE_UP = 11;
555    static final int UPDATED_MEDIA_STATUS = 12;
556    static final int WRITE_SETTINGS = 13;
557    static final int WRITE_PACKAGE_RESTRICTIONS = 14;
558    static final int PACKAGE_VERIFIED = 15;
559    static final int CHECK_PENDING_VERIFICATION = 16;
560
561    static final int WRITE_SETTINGS_DELAY = 10*1000;  // 10 seconds
562
563    // Delay time in millisecs
564    static final int BROADCAST_DELAY = 10 * 1000;
565
566    static UserManagerService sUserManager;
567
568    // Stores a list of users whose package restrictions file needs to be updated
569    private HashSet<Integer> mDirtyUsers = new HashSet<Integer>();
570
571    final private DefaultContainerConnection mDefContainerConn =
572            new DefaultContainerConnection();
573    class DefaultContainerConnection implements ServiceConnection {
574        public void onServiceConnected(ComponentName name, IBinder service) {
575            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected");
576            IMediaContainerService imcs =
577                IMediaContainerService.Stub.asInterface(service);
578            mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs));
579        }
580
581        public void onServiceDisconnected(ComponentName name) {
582            if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected");
583        }
584    };
585
586    // Recordkeeping of restore-after-install operations that are currently in flight
587    // between the Package Manager and the Backup Manager
588    class PostInstallData {
589        public InstallArgs args;
590        public PackageInstalledInfo res;
591
592        PostInstallData(InstallArgs _a, PackageInstalledInfo _r) {
593            args = _a;
594            res = _r;
595        }
596    };
597    final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>();
598    int mNextInstallToken = 1;  // nonzero; will be wrapped back to 1 when ++ overflows
599
600    private final String mRequiredVerifierPackage;
601
602    private final PackageUsage mPackageUsage = new PackageUsage();
603
604    private class PackageUsage {
605        private static final int WRITE_INTERVAL
606            = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms
607
608        private final Object mFileLock = new Object();
609        private final AtomicLong mLastWritten = new AtomicLong(0);
610        private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false);
611
612        private boolean mIsHistoricalPackageUsageAvailable = true;
613
614        boolean isHistoricalPackageUsageAvailable() {
615            return mIsHistoricalPackageUsageAvailable;
616        }
617
618        void write(boolean force) {
619            if (force) {
620                writeInternal();
621                return;
622            }
623            if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL
624                && !DEBUG_DEXOPT) {
625                return;
626            }
627            if (mBackgroundWriteRunning.compareAndSet(false, true)) {
628                new Thread("PackageUsage_DiskWriter") {
629                    @Override
630                    public void run() {
631                        try {
632                            writeInternal();
633                        } finally {
634                            mBackgroundWriteRunning.set(false);
635                        }
636                    }
637                }.start();
638            }
639        }
640
641        private void writeInternal() {
642            synchronized (mPackages) {
643                synchronized (mFileLock) {
644                    AtomicFile file = getFile();
645                    FileOutputStream f = null;
646                    try {
647                        f = file.startWrite();
648                        BufferedOutputStream out = new BufferedOutputStream(f);
649                        FileUtils.setPermissions(file.getBaseFile().getPath(), 0660, SYSTEM_UID, PACKAGE_INFO_GID);
650                        StringBuilder sb = new StringBuilder();
651                        for (PackageParser.Package pkg : mPackages.values()) {
652                            if (pkg.mLastPackageUsageTimeInMills == 0) {
653                                continue;
654                            }
655                            sb.setLength(0);
656                            sb.append(pkg.packageName);
657                            sb.append(' ');
658                            sb.append((long)pkg.mLastPackageUsageTimeInMills);
659                            sb.append('\n');
660                            out.write(sb.toString().getBytes(StandardCharsets.US_ASCII));
661                        }
662                        out.flush();
663                        file.finishWrite(f);
664                    } catch (IOException e) {
665                        if (f != null) {
666                            file.failWrite(f);
667                        }
668                        Log.e(TAG, "Failed to write package usage times", e);
669                    }
670                }
671            }
672            mLastWritten.set(SystemClock.elapsedRealtime());
673        }
674
675        void readLP() {
676            synchronized (mFileLock) {
677                AtomicFile file = getFile();
678                BufferedInputStream in = null;
679                try {
680                    in = new BufferedInputStream(file.openRead());
681                    StringBuffer sb = new StringBuffer();
682                    while (true) {
683                        String packageName = readToken(in, sb, ' ');
684                        if (packageName == null) {
685                            break;
686                        }
687                        String timeInMillisString = readToken(in, sb, '\n');
688                        if (timeInMillisString == null) {
689                            throw new IOException("Failed to find last usage time for package "
690                                                  + packageName);
691                        }
692                        PackageParser.Package pkg = mPackages.get(packageName);
693                        if (pkg == null) {
694                            continue;
695                        }
696                        long timeInMillis;
697                        try {
698                            timeInMillis = Long.parseLong(timeInMillisString.toString());
699                        } catch (NumberFormatException e) {
700                            throw new IOException("Failed to parse " + timeInMillisString
701                                                  + " as a long.", e);
702                        }
703                        pkg.mLastPackageUsageTimeInMills = timeInMillis;
704                    }
705                } catch (FileNotFoundException expected) {
706                    mIsHistoricalPackageUsageAvailable = false;
707                } catch (IOException e) {
708                    Log.w(TAG, "Failed to read package usage times", e);
709                } finally {
710                    IoUtils.closeQuietly(in);
711                }
712            }
713            mLastWritten.set(SystemClock.elapsedRealtime());
714        }
715
716        private String readToken(InputStream in, StringBuffer sb, char endOfToken)
717                throws IOException {
718            sb.setLength(0);
719            while (true) {
720                int ch = in.read();
721                if (ch == -1) {
722                    if (sb.length() == 0) {
723                        return null;
724                    }
725                    throw new IOException("Unexpected EOF");
726                }
727                if (ch == endOfToken) {
728                    return sb.toString();
729                }
730                sb.append((char)ch);
731            }
732        }
733
734        private AtomicFile getFile() {
735            File dataDir = Environment.getDataDirectory();
736            File systemDir = new File(dataDir, "system");
737            File fname = new File(systemDir, "package-usage.list");
738            return new AtomicFile(fname);
739        }
740    }
741
742    class PackageHandler extends Handler {
743        private boolean mBound = false;
744        final ArrayList<HandlerParams> mPendingInstalls =
745            new ArrayList<HandlerParams>();
746
747        private boolean connectToService() {
748            if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" +
749                    " DefaultContainerService");
750            Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
751            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
752            if (mContext.bindServiceAsUser(service, mDefContainerConn,
753                    Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
754                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
755                mBound = true;
756                return true;
757            }
758            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
759            return false;
760        }
761
762        private void disconnectService() {
763            mContainerService = null;
764            mBound = false;
765            Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
766            mContext.unbindService(mDefContainerConn);
767            Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
768        }
769
770        PackageHandler(Looper looper) {
771            super(looper);
772        }
773
774        public void handleMessage(Message msg) {
775            try {
776                doHandleMessage(msg);
777            } finally {
778                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
779            }
780        }
781
782        void doHandleMessage(Message msg) {
783            switch (msg.what) {
784                case INIT_COPY: {
785                    HandlerParams params = (HandlerParams) msg.obj;
786                    int idx = mPendingInstalls.size();
787                    if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params);
788                    // If a bind was already initiated we dont really
789                    // need to do anything. The pending install
790                    // will be processed later on.
791                    if (!mBound) {
792                        // If this is the only one pending we might
793                        // have to bind to the service again.
794                        if (!connectToService()) {
795                            Slog.e(TAG, "Failed to bind to media container service");
796                            params.serviceError();
797                            return;
798                        } else {
799                            // Once we bind to the service, the first
800                            // pending request will be processed.
801                            mPendingInstalls.add(idx, params);
802                        }
803                    } else {
804                        mPendingInstalls.add(idx, params);
805                        // Already bound to the service. Just make
806                        // sure we trigger off processing the first request.
807                        if (idx == 0) {
808                            mHandler.sendEmptyMessage(MCS_BOUND);
809                        }
810                    }
811                    break;
812                }
813                case MCS_BOUND: {
814                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound");
815                    if (msg.obj != null) {
816                        mContainerService = (IMediaContainerService) msg.obj;
817                    }
818                    if (mContainerService == null) {
819                        // Something seriously wrong. Bail out
820                        Slog.e(TAG, "Cannot bind to media container service");
821                        for (HandlerParams params : mPendingInstalls) {
822                            // Indicate service bind error
823                            params.serviceError();
824                        }
825                        mPendingInstalls.clear();
826                    } else if (mPendingInstalls.size() > 0) {
827                        HandlerParams params = mPendingInstalls.get(0);
828                        if (params != null) {
829                            if (params.startCopy()) {
830                                // We are done...  look for more work or to
831                                // go idle.
832                                if (DEBUG_SD_INSTALL) Log.i(TAG,
833                                        "Checking for more work or unbind...");
834                                // Delete pending install
835                                if (mPendingInstalls.size() > 0) {
836                                    mPendingInstalls.remove(0);
837                                }
838                                if (mPendingInstalls.size() == 0) {
839                                    if (mBound) {
840                                        if (DEBUG_SD_INSTALL) Log.i(TAG,
841                                                "Posting delayed MCS_UNBIND");
842                                        removeMessages(MCS_UNBIND);
843                                        Message ubmsg = obtainMessage(MCS_UNBIND);
844                                        // Unbind after a little delay, to avoid
845                                        // continual thrashing.
846                                        sendMessageDelayed(ubmsg, 10000);
847                                    }
848                                } else {
849                                    // There are more pending requests in queue.
850                                    // Just post MCS_BOUND message to trigger processing
851                                    // of next pending install.
852                                    if (DEBUG_SD_INSTALL) Log.i(TAG,
853                                            "Posting MCS_BOUND for next work");
854                                    mHandler.sendEmptyMessage(MCS_BOUND);
855                                }
856                            }
857                        }
858                    } else {
859                        // Should never happen ideally.
860                        Slog.w(TAG, "Empty queue");
861                    }
862                    break;
863                }
864                case MCS_RECONNECT: {
865                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect");
866                    if (mPendingInstalls.size() > 0) {
867                        if (mBound) {
868                            disconnectService();
869                        }
870                        if (!connectToService()) {
871                            Slog.e(TAG, "Failed to bind to media container service");
872                            for (HandlerParams params : mPendingInstalls) {
873                                // Indicate service bind error
874                                params.serviceError();
875                            }
876                            mPendingInstalls.clear();
877                        }
878                    }
879                    break;
880                }
881                case MCS_UNBIND: {
882                    // If there is no actual work left, then time to unbind.
883                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind");
884
885                    if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) {
886                        if (mBound) {
887                            if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()");
888
889                            disconnectService();
890                        }
891                    } else if (mPendingInstalls.size() > 0) {
892                        // There are more pending requests in queue.
893                        // Just post MCS_BOUND message to trigger processing
894                        // of next pending install.
895                        mHandler.sendEmptyMessage(MCS_BOUND);
896                    }
897
898                    break;
899                }
900                case MCS_GIVE_UP: {
901                    if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries");
902                    mPendingInstalls.remove(0);
903                    break;
904                }
905                case SEND_PENDING_BROADCAST: {
906                    String packages[];
907                    ArrayList<String> components[];
908                    int size = 0;
909                    int uids[];
910                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
911                    synchronized (mPackages) {
912                        if (mPendingBroadcasts == null) {
913                            return;
914                        }
915                        size = mPendingBroadcasts.size();
916                        if (size <= 0) {
917                            // Nothing to be done. Just return
918                            return;
919                        }
920                        packages = new String[size];
921                        components = new ArrayList[size];
922                        uids = new int[size];
923                        int i = 0;  // filling out the above arrays
924
925                        for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) {
926                            int packageUserId = mPendingBroadcasts.userIdAt(n);
927                            Iterator<Map.Entry<String, ArrayList<String>>> it
928                                    = mPendingBroadcasts.packagesForUserId(packageUserId)
929                                            .entrySet().iterator();
930                            while (it.hasNext() && i < size) {
931                                Map.Entry<String, ArrayList<String>> ent = it.next();
932                                packages[i] = ent.getKey();
933                                components[i] = ent.getValue();
934                                PackageSetting ps = mSettings.mPackages.get(ent.getKey());
935                                uids[i] = (ps != null)
936                                        ? UserHandle.getUid(packageUserId, ps.appId)
937                                        : -1;
938                                i++;
939                            }
940                        }
941                        size = i;
942                        mPendingBroadcasts.clear();
943                    }
944                    // Send broadcasts
945                    for (int i = 0; i < size; i++) {
946                        sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]);
947                    }
948                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
949                    break;
950                }
951                case START_CLEANING_PACKAGE: {
952                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
953                    final String packageName = (String)msg.obj;
954                    final int userId = msg.arg1;
955                    final boolean andCode = msg.arg2 != 0;
956                    synchronized (mPackages) {
957                        if (userId == UserHandle.USER_ALL) {
958                            int[] users = sUserManager.getUserIds();
959                            for (int user : users) {
960                                mSettings.addPackageToCleanLPw(
961                                        new PackageCleanItem(user, packageName, andCode));
962                            }
963                        } else {
964                            mSettings.addPackageToCleanLPw(
965                                    new PackageCleanItem(userId, packageName, andCode));
966                        }
967                    }
968                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
969                    startCleaningPackages();
970                } break;
971                case POST_INSTALL: {
972                    if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1);
973                    PostInstallData data = mRunningInstalls.get(msg.arg1);
974                    mRunningInstalls.delete(msg.arg1);
975                    boolean deleteOld = false;
976
977                    if (data != null) {
978                        InstallArgs args = data.args;
979                        PackageInstalledInfo res = data.res;
980
981                        if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
982                            res.removedInfo.sendBroadcast(false, true, false);
983                            Bundle extras = new Bundle(1);
984                            extras.putInt(Intent.EXTRA_UID, res.uid);
985                            // Determine the set of users who are adding this
986                            // package for the first time vs. those who are seeing
987                            // an update.
988                            int[] firstUsers;
989                            int[] updateUsers = new int[0];
990                            if (res.origUsers == null || res.origUsers.length == 0) {
991                                firstUsers = res.newUsers;
992                            } else {
993                                firstUsers = new int[0];
994                                for (int i=0; i<res.newUsers.length; i++) {
995                                    int user = res.newUsers[i];
996                                    boolean isNew = true;
997                                    for (int j=0; j<res.origUsers.length; j++) {
998                                        if (res.origUsers[j] == user) {
999                                            isNew = false;
1000                                            break;
1001                                        }
1002                                    }
1003                                    if (isNew) {
1004                                        int[] newFirst = new int[firstUsers.length+1];
1005                                        System.arraycopy(firstUsers, 0, newFirst, 0,
1006                                                firstUsers.length);
1007                                        newFirst[firstUsers.length] = user;
1008                                        firstUsers = newFirst;
1009                                    } else {
1010                                        int[] newUpdate = new int[updateUsers.length+1];
1011                                        System.arraycopy(updateUsers, 0, newUpdate, 0,
1012                                                updateUsers.length);
1013                                        newUpdate[updateUsers.length] = user;
1014                                        updateUsers = newUpdate;
1015                                    }
1016                                }
1017                            }
1018                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1019                                    res.pkg.applicationInfo.packageName,
1020                                    extras, null, null, firstUsers);
1021                            final boolean update = res.removedInfo.removedPackage != null;
1022                            if (update) {
1023                                extras.putBoolean(Intent.EXTRA_REPLACING, true);
1024                            }
1025                            sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
1026                                    res.pkg.applicationInfo.packageName,
1027                                    extras, null, null, updateUsers);
1028                            if (update) {
1029                                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED,
1030                                        res.pkg.applicationInfo.packageName,
1031                                        extras, null, null, updateUsers);
1032                                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED,
1033                                        null, null,
1034                                        res.pkg.applicationInfo.packageName, null, updateUsers);
1035
1036                                // treat asec-hosted packages like removable media on upgrade
1037                                if (isForwardLocked(res.pkg) || isExternal(res.pkg)) {
1038                                    if (DEBUG_INSTALL) {
1039                                        Slog.i(TAG, "upgrading pkg " + res.pkg
1040                                                + " is ASEC-hosted -> AVAILABLE");
1041                                    }
1042                                    int[] uidArray = new int[] { res.pkg.applicationInfo.uid };
1043                                    ArrayList<String> pkgList = new ArrayList<String>(1);
1044                                    pkgList.add(res.pkg.applicationInfo.packageName);
1045                                    sendResourcesChangedBroadcast(true, true,
1046                                            pkgList,uidArray, null);
1047                                }
1048                            }
1049                            if (res.removedInfo.args != null) {
1050                                // Remove the replaced package's older resources safely now
1051                                deleteOld = true;
1052                            }
1053
1054                            // Log current value of "unknown sources" setting
1055                            EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED,
1056                                getUnknownSourcesSettings());
1057                        }
1058                        // Force a gc to clear up things
1059                        Runtime.getRuntime().gc();
1060                        // We delete after a gc for applications  on sdcard.
1061                        if (deleteOld) {
1062                            synchronized (mInstallLock) {
1063                                res.removedInfo.args.doPostDeleteLI(true);
1064                            }
1065                        }
1066                        if (args.observer != null) {
1067                            try {
1068                                Bundle extras = extrasForInstallResult(res);
1069                                args.observer.onPackageInstalled(res.name, res.returnCode,
1070                                        res.returnMsg, extras);
1071                            } catch (RemoteException e) {
1072                                Slog.i(TAG, "Observer no longer exists.");
1073                            }
1074                        }
1075                    } else {
1076                        Slog.e(TAG, "Bogus post-install token " + msg.arg1);
1077                    }
1078                } break;
1079                case UPDATED_MEDIA_STATUS: {
1080                    if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS");
1081                    boolean reportStatus = msg.arg1 == 1;
1082                    boolean doGc = msg.arg2 == 1;
1083                    if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc);
1084                    if (doGc) {
1085                        // Force a gc to clear up stale containers.
1086                        Runtime.getRuntime().gc();
1087                    }
1088                    if (msg.obj != null) {
1089                        @SuppressWarnings("unchecked")
1090                        Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj;
1091                        if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers");
1092                        // Unload containers
1093                        unloadAllContainers(args);
1094                    }
1095                    if (reportStatus) {
1096                        try {
1097                            if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back");
1098                            PackageHelper.getMountService().finishMediaUpdate();
1099                        } catch (RemoteException e) {
1100                            Log.e(TAG, "MountService not running?");
1101                        }
1102                    }
1103                } break;
1104                case WRITE_SETTINGS: {
1105                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1106                    synchronized (mPackages) {
1107                        removeMessages(WRITE_SETTINGS);
1108                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1109                        mSettings.writeLPr();
1110                        mDirtyUsers.clear();
1111                    }
1112                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1113                } break;
1114                case WRITE_PACKAGE_RESTRICTIONS: {
1115                    Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT);
1116                    synchronized (mPackages) {
1117                        removeMessages(WRITE_PACKAGE_RESTRICTIONS);
1118                        for (int userId : mDirtyUsers) {
1119                            mSettings.writePackageRestrictionsLPr(userId);
1120                        }
1121                        mDirtyUsers.clear();
1122                    }
1123                    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
1124                } break;
1125                case CHECK_PENDING_VERIFICATION: {
1126                    final int verificationId = msg.arg1;
1127                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1128
1129                    if ((state != null) && !state.timeoutExtended()) {
1130                        final InstallArgs args = state.getInstallArgs();
1131                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1132
1133                        Slog.i(TAG, "Verification timed out for " + originUri);
1134                        mPendingVerification.remove(verificationId);
1135
1136                        int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1137
1138                        if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) {
1139                            Slog.i(TAG, "Continuing with installation of " + originUri);
1140                            state.setVerifierResponse(Binder.getCallingUid(),
1141                                    PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT);
1142                            broadcastPackageVerified(verificationId, originUri,
1143                                    PackageManager.VERIFICATION_ALLOW,
1144                                    state.getInstallArgs().getUser());
1145                            try {
1146                                ret = args.copyApk(mContainerService, true);
1147                            } catch (RemoteException e) {
1148                                Slog.e(TAG, "Could not contact the ContainerService");
1149                            }
1150                        } else {
1151                            broadcastPackageVerified(verificationId, originUri,
1152                                    PackageManager.VERIFICATION_REJECT,
1153                                    state.getInstallArgs().getUser());
1154                        }
1155
1156                        processPendingInstall(args, ret);
1157                        mHandler.sendEmptyMessage(MCS_UNBIND);
1158                    }
1159                    break;
1160                }
1161                case PACKAGE_VERIFIED: {
1162                    final int verificationId = msg.arg1;
1163
1164                    final PackageVerificationState state = mPendingVerification.get(verificationId);
1165                    if (state == null) {
1166                        Slog.w(TAG, "Invalid verification token " + verificationId + " received");
1167                        break;
1168                    }
1169
1170                    final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj;
1171
1172                    state.setVerifierResponse(response.callerUid, response.code);
1173
1174                    if (state.isVerificationComplete()) {
1175                        mPendingVerification.remove(verificationId);
1176
1177                        final InstallArgs args = state.getInstallArgs();
1178                        final Uri originUri = Uri.fromFile(args.origin.resolvedFile);
1179
1180                        int ret;
1181                        if (state.isInstallAllowed()) {
1182                            ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
1183                            broadcastPackageVerified(verificationId, originUri,
1184                                    response.code, state.getInstallArgs().getUser());
1185                            try {
1186                                ret = args.copyApk(mContainerService, true);
1187                            } catch (RemoteException e) {
1188                                Slog.e(TAG, "Could not contact the ContainerService");
1189                            }
1190                        } else {
1191                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
1192                        }
1193
1194                        processPendingInstall(args, ret);
1195
1196                        mHandler.sendEmptyMessage(MCS_UNBIND);
1197                    }
1198
1199                    break;
1200                }
1201            }
1202        }
1203    }
1204
1205    Bundle extrasForInstallResult(PackageInstalledInfo res) {
1206        Bundle extras = null;
1207        switch (res.returnCode) {
1208            case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: {
1209                extras = new Bundle();
1210                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION,
1211                        res.origPermission);
1212                extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE,
1213                        res.origPackage);
1214                break;
1215            }
1216        }
1217        return extras;
1218    }
1219
1220    void scheduleWriteSettingsLocked() {
1221        if (!mHandler.hasMessages(WRITE_SETTINGS)) {
1222            mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY);
1223        }
1224    }
1225
1226    void scheduleWritePackageRestrictionsLocked(int userId) {
1227        if (!sUserManager.exists(userId)) return;
1228        mDirtyUsers.add(userId);
1229        if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) {
1230            mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY);
1231        }
1232    }
1233
1234    public static final PackageManagerService main(Context context, Installer installer,
1235            boolean factoryTest, boolean onlyCore) {
1236        PackageManagerService m = new PackageManagerService(context, installer,
1237                factoryTest, onlyCore);
1238        ServiceManager.addService("package", m);
1239        return m;
1240    }
1241
1242    static String[] splitString(String str, char sep) {
1243        int count = 1;
1244        int i = 0;
1245        while ((i=str.indexOf(sep, i)) >= 0) {
1246            count++;
1247            i++;
1248        }
1249
1250        String[] res = new String[count];
1251        i=0;
1252        count = 0;
1253        int lastI=0;
1254        while ((i=str.indexOf(sep, i)) >= 0) {
1255            res[count] = str.substring(lastI, i);
1256            count++;
1257            i++;
1258            lastI = i;
1259        }
1260        res[count] = str.substring(lastI, str.length());
1261        return res;
1262    }
1263
1264    private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) {
1265        DisplayManager displayManager = (DisplayManager) context.getSystemService(
1266                Context.DISPLAY_SERVICE);
1267        displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics);
1268    }
1269
1270    public PackageManagerService(Context context, Installer installer,
1271            boolean factoryTest, boolean onlyCore) {
1272        EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START,
1273                SystemClock.uptimeMillis());
1274
1275        if (mSdkVersion <= 0) {
1276            Slog.w(TAG, "**** ro.build.version.sdk not set!");
1277        }
1278
1279        mContext = context;
1280        mFactoryTest = factoryTest;
1281        mOnlyCore = onlyCore;
1282        mLazyDexOpt = "eng".equals(SystemProperties.get("ro.build.type"));
1283        mMetrics = new DisplayMetrics();
1284        mSettings = new Settings(context);
1285        mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID,
1286                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1287        mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID,
1288                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1289        mSettings.addSharedUserLPw("android.uid.log", LOG_UID,
1290                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1291        mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID,
1292                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1293        mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID,
1294                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1295        mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID,
1296                ApplicationInfo.FLAG_SYSTEM|ApplicationInfo.FLAG_PRIVILEGED);
1297
1298        String separateProcesses = SystemProperties.get("debug.separate_processes");
1299        if (separateProcesses != null && separateProcesses.length() > 0) {
1300            if ("*".equals(separateProcesses)) {
1301                mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES;
1302                mSeparateProcesses = null;
1303                Slog.w(TAG, "Running with debug.separate_processes: * (ALL)");
1304            } else {
1305                mDefParseFlags = 0;
1306                mSeparateProcesses = separateProcesses.split(",");
1307                Slog.w(TAG, "Running with debug.separate_processes: "
1308                        + separateProcesses);
1309            }
1310        } else {
1311            mDefParseFlags = 0;
1312            mSeparateProcesses = null;
1313        }
1314
1315        mInstaller = installer;
1316
1317        getDefaultDisplayMetrics(context, mMetrics);
1318
1319        SystemConfig systemConfig = SystemConfig.getInstance();
1320        mGlobalGids = systemConfig.getGlobalGids();
1321        mSystemPermissions = systemConfig.getSystemPermissions();
1322        mAvailableFeatures = systemConfig.getAvailableFeatures();
1323
1324        synchronized (mInstallLock) {
1325        // writer
1326        synchronized (mPackages) {
1327            mHandlerThread = new ServiceThread(TAG,
1328                    Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/);
1329            mHandlerThread.start();
1330            mHandler = new PackageHandler(mHandlerThread.getLooper());
1331            Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT);
1332
1333            File dataDir = Environment.getDataDirectory();
1334            mAppDataDir = new File(dataDir, "data");
1335            mAppInstallDir = new File(dataDir, "app");
1336            mAppLib32InstallDir = new File(dataDir, "app-lib");
1337            mAsecInternalPath = new File(dataDir, "app-asec").getPath();
1338            mUserAppDataDir = new File(dataDir, "user");
1339            mDrmAppPrivateInstallDir = new File(dataDir, "app-private");
1340
1341            sUserManager = new UserManagerService(context, this,
1342                    mInstallLock, mPackages);
1343
1344            // Propagate permission configuration in to package manager.
1345            ArrayMap<String, SystemConfig.PermissionEntry> permConfig
1346                    = systemConfig.getPermissions();
1347            for (int i=0; i<permConfig.size(); i++) {
1348                SystemConfig.PermissionEntry perm = permConfig.valueAt(i);
1349                BasePermission bp = mSettings.mPermissions.get(perm.name);
1350                if (bp == null) {
1351                    bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN);
1352                    mSettings.mPermissions.put(perm.name, bp);
1353                }
1354                if (perm.gids != null) {
1355                    bp.gids = appendInts(bp.gids, perm.gids);
1356                }
1357            }
1358
1359            ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries();
1360            for (int i=0; i<libConfig.size(); i++) {
1361                mSharedLibraries.put(libConfig.keyAt(i),
1362                        new SharedLibraryEntry(libConfig.valueAt(i), null));
1363            }
1364
1365            mFoundPolicyFile = SELinuxMMAC.readInstallPolicy();
1366
1367            mRestoredSettings = mSettings.readLPw(this, sUserManager.getUsers(false),
1368                    mSdkVersion, mOnlyCore);
1369
1370            String customResolverActivity = Resources.getSystem().getString(
1371                    R.string.config_customResolverActivity);
1372            if (TextUtils.isEmpty(customResolverActivity)) {
1373                customResolverActivity = null;
1374            } else {
1375                mCustomResolverComponentName = ComponentName.unflattenFromString(
1376                        customResolverActivity);
1377            }
1378
1379            long startTime = SystemClock.uptimeMillis();
1380
1381            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START,
1382                    startTime);
1383
1384            // Set flag to monitor and not change apk file paths when
1385            // scanning install directories.
1386            final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING;
1387
1388            final HashSet<String> alreadyDexOpted = new HashSet<String>();
1389
1390            /**
1391             * Add everything in the in the boot class path to the
1392             * list of process files because dexopt will have been run
1393             * if necessary during zygote startup.
1394             */
1395            final String bootClassPath = System.getenv("BOOTCLASSPATH");
1396            final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH");
1397
1398            if (bootClassPath != null) {
1399                String[] bootClassPathElements = splitString(bootClassPath, ':');
1400                for (String element : bootClassPathElements) {
1401                    alreadyDexOpted.add(element);
1402                }
1403            } else {
1404                Slog.w(TAG, "No BOOTCLASSPATH found!");
1405            }
1406
1407            if (systemServerClassPath != null) {
1408                String[] systemServerClassPathElements = splitString(systemServerClassPath, ':');
1409                for (String element : systemServerClassPathElements) {
1410                    alreadyDexOpted.add(element);
1411                }
1412            } else {
1413                Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!");
1414            }
1415
1416            boolean didDexOptLibraryOrTool = false;
1417
1418            final List<String> allInstructionSets = getAllInstructionSets();
1419            final String[] dexCodeInstructionSets =
1420                getDexCodeInstructionSets(allInstructionSets.toArray(new String[allInstructionSets.size()]));
1421
1422            /**
1423             * Ensure all external libraries have had dexopt run on them.
1424             */
1425            if (mSharedLibraries.size() > 0) {
1426                // NOTE: For now, we're compiling these system "shared libraries"
1427                // (and framework jars) into all available architectures. It's possible
1428                // to compile them only when we come across an app that uses them (there's
1429                // already logic for that in scanPackageLI) but that adds some complexity.
1430                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1431                    for (SharedLibraryEntry libEntry : mSharedLibraries.values()) {
1432                        final String lib = libEntry.path;
1433                        if (lib == null) {
1434                            continue;
1435                        }
1436
1437                        try {
1438                            byte dexoptRequired = DexFile.isDexOptNeededInternal(lib, null,
1439                                                                                 dexCodeInstructionSet,
1440                                                                                 false);
1441                            if (dexoptRequired != DexFile.UP_TO_DATE) {
1442                                alreadyDexOpted.add(lib);
1443
1444                                // The list of "shared libraries" we have at this point is
1445                                if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1446                                    mInstaller.dexopt(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1447                                } else {
1448                                    mInstaller.patchoat(lib, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1449                                }
1450                                didDexOptLibraryOrTool = true;
1451                            }
1452                        } catch (FileNotFoundException e) {
1453                            Slog.w(TAG, "Library not found: " + lib);
1454                        } catch (IOException e) {
1455                            Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? "
1456                                    + e.getMessage());
1457                        }
1458                    }
1459                }
1460            }
1461
1462            File frameworkDir = new File(Environment.getRootDirectory(), "framework");
1463
1464            // Gross hack for now: we know this file doesn't contain any
1465            // code, so don't dexopt it to avoid the resulting log spew.
1466            alreadyDexOpted.add(frameworkDir.getPath() + "/framework-res.apk");
1467
1468            // Gross hack for now: we know this file is only part of
1469            // the boot class path for art, so don't dexopt it to
1470            // avoid the resulting log spew.
1471            alreadyDexOpted.add(frameworkDir.getPath() + "/core-libart.jar");
1472
1473            /**
1474             * And there are a number of commands implemented in Java, which
1475             * we currently need to do the dexopt on so that they can be
1476             * run from a non-root shell.
1477             */
1478            String[] frameworkFiles = frameworkDir.list();
1479            if (frameworkFiles != null) {
1480                // TODO: We could compile these only for the most preferred ABI. We should
1481                // first double check that the dex files for these commands are not referenced
1482                // by other system apps.
1483                for (String dexCodeInstructionSet : dexCodeInstructionSets) {
1484                    for (int i=0; i<frameworkFiles.length; i++) {
1485                        File libPath = new File(frameworkDir, frameworkFiles[i]);
1486                        String path = libPath.getPath();
1487                        // Skip the file if we already did it.
1488                        if (alreadyDexOpted.contains(path)) {
1489                            continue;
1490                        }
1491                        // Skip the file if it is not a type we want to dexopt.
1492                        if (!path.endsWith(".apk") && !path.endsWith(".jar")) {
1493                            continue;
1494                        }
1495                        try {
1496                            byte dexoptRequired = DexFile.isDexOptNeededInternal(path, null,
1497                                                                                 dexCodeInstructionSet,
1498                                                                                 false);
1499                            if (dexoptRequired == DexFile.DEXOPT_NEEDED) {
1500                                mInstaller.dexopt(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1501                                didDexOptLibraryOrTool = true;
1502                            } else if (dexoptRequired == DexFile.PATCHOAT_NEEDED) {
1503                                mInstaller.patchoat(path, Process.SYSTEM_UID, true, dexCodeInstructionSet);
1504                                didDexOptLibraryOrTool = true;
1505                            }
1506                        } catch (FileNotFoundException e) {
1507                            Slog.w(TAG, "Jar not found: " + path);
1508                        } catch (IOException e) {
1509                            Slog.w(TAG, "Exception reading jar: " + path, e);
1510                        }
1511                    }
1512                }
1513            }
1514
1515            // Collect vendor overlay packages.
1516            // (Do this before scanning any apps.)
1517            // For security and version matching reason, only consider
1518            // overlay packages if they reside in VENDOR_OVERLAY_DIR.
1519            File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR);
1520            scanDirLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM
1521                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0);
1522
1523            // Find base frameworks (resource packages without code).
1524            scanDirLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM
1525                    | PackageParser.PARSE_IS_SYSTEM_DIR
1526                    | PackageParser.PARSE_IS_PRIVILEGED,
1527                    scanFlags | SCAN_NO_DEX, 0);
1528
1529            // Collected privileged system packages.
1530            final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app");
1531            scanDirLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM
1532                    | PackageParser.PARSE_IS_SYSTEM_DIR
1533                    | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0);
1534
1535            // Collect ordinary system packages.
1536            final File systemAppDir = new File(Environment.getRootDirectory(), "app");
1537            scanDirLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM
1538                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1539
1540            // Collect all vendor packages.
1541            File vendorAppDir = new File("/vendor/app");
1542            try {
1543                vendorAppDir = vendorAppDir.getCanonicalFile();
1544            } catch (IOException e) {
1545                // failed to look up canonical path, continue with original one
1546            }
1547            scanDirLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM
1548                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1549
1550            // Collect all OEM packages.
1551            final File oemAppDir = new File(Environment.getOemDirectory(), "app");
1552            scanDirLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM
1553                    | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0);
1554
1555            if (DEBUG_UPGRADE) Log.v(TAG, "Running installd update commands");
1556            mInstaller.moveFiles();
1557
1558            // Prune any system packages that no longer exist.
1559            final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>();
1560            final ArrayMap<String, File> expectingBetter = new ArrayMap<>();
1561            if (!mOnlyCore) {
1562                Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
1563                while (psit.hasNext()) {
1564                    PackageSetting ps = psit.next();
1565
1566                    /*
1567                     * If this is not a system app, it can't be a
1568                     * disable system app.
1569                     */
1570                    if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) {
1571                        continue;
1572                    }
1573
1574                    /*
1575                     * If the package is scanned, it's not erased.
1576                     */
1577                    final PackageParser.Package scannedPkg = mPackages.get(ps.name);
1578                    if (scannedPkg != null) {
1579                        /*
1580                         * If the system app is both scanned and in the
1581                         * disabled packages list, then it must have been
1582                         * added via OTA. Remove it from the currently
1583                         * scanned package so the previously user-installed
1584                         * application can be scanned.
1585                         */
1586                        if (mSettings.isDisabledSystemPackageLPr(ps.name)) {
1587                            logCriticalInfo(Log.WARN, "Expecting better updated system app for "
1588                                    + ps.name + "; removing system app.  Last known codePath="
1589                                    + ps.codePathString + ", installStatus=" + ps.installStatus
1590                                    + ", versionCode=" + ps.versionCode + "; scanned versionCode="
1591                                    + scannedPkg.mVersionCode);
1592                            removePackageLI(ps, true);
1593                            expectingBetter.put(ps.name, ps.codePath);
1594                        }
1595
1596                        continue;
1597                    }
1598
1599                    if (!mSettings.isDisabledSystemPackageLPr(ps.name)) {
1600                        psit.remove();
1601                        logCriticalInfo(Log.WARN, "System package " + ps.name
1602                                + " no longer exists; wiping its data");
1603                        removeDataDirsLI(ps.name);
1604                    } else {
1605                        final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name);
1606                        if (disabledPs.codePath == null || !disabledPs.codePath.exists()) {
1607                            possiblyDeletedUpdatedSystemApps.add(ps.name);
1608                        }
1609                    }
1610                }
1611            }
1612
1613            //look for any incomplete package installations
1614            ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr();
1615            //clean up list
1616            for(int i = 0; i < deletePkgsList.size(); i++) {
1617                //clean up here
1618                cleanupInstallFailedPackage(deletePkgsList.get(i));
1619            }
1620            //delete tmp files
1621            deleteTempPackageFiles();
1622
1623            // Remove any shared userIDs that have no associated packages
1624            mSettings.pruneSharedUsersLPw();
1625
1626            if (!mOnlyCore) {
1627                EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START,
1628                        SystemClock.uptimeMillis());
1629                scanDirLI(mAppInstallDir, 0, scanFlags, 0);
1630
1631                scanDirLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK,
1632                        scanFlags, 0);
1633
1634                /**
1635                 * Remove disable package settings for any updated system
1636                 * apps that were removed via an OTA. If they're not a
1637                 * previously-updated app, remove them completely.
1638                 * Otherwise, just revoke their system-level permissions.
1639                 */
1640                for (String deletedAppName : possiblyDeletedUpdatedSystemApps) {
1641                    PackageParser.Package deletedPkg = mPackages.get(deletedAppName);
1642                    mSettings.removeDisabledSystemPackageLPw(deletedAppName);
1643
1644                    String msg;
1645                    if (deletedPkg == null) {
1646                        msg = "Updated system package " + deletedAppName
1647                                + " no longer exists; wiping its data";
1648                        removeDataDirsLI(deletedAppName);
1649                    } else {
1650                        msg = "Updated system app + " + deletedAppName
1651                                + " no longer present; removing system privileges for "
1652                                + deletedAppName;
1653
1654                        deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM;
1655
1656                        PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName);
1657                        deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM;
1658                    }
1659                    logCriticalInfo(Log.WARN, msg);
1660                }
1661
1662                /**
1663                 * Make sure all system apps that we expected to appear on
1664                 * the userdata partition actually showed up. If they never
1665                 * appeared, crawl back and revive the system version.
1666                 */
1667                for (int i = 0; i < expectingBetter.size(); i++) {
1668                    final String packageName = expectingBetter.keyAt(i);
1669                    if (!mPackages.containsKey(packageName)) {
1670                        final File scanFile = expectingBetter.valueAt(i);
1671
1672                        logCriticalInfo(Log.WARN, "Expected better " + packageName
1673                                + " but never showed up; reverting to system");
1674
1675                        final int reparseFlags;
1676                        if (FileUtils.contains(privilegedAppDir, scanFile)) {
1677                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1678                                    | PackageParser.PARSE_IS_SYSTEM_DIR
1679                                    | PackageParser.PARSE_IS_PRIVILEGED;
1680                        } else if (FileUtils.contains(systemAppDir, scanFile)) {
1681                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1682                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1683                        } else if (FileUtils.contains(vendorAppDir, scanFile)) {
1684                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1685                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1686                        } else if (FileUtils.contains(oemAppDir, scanFile)) {
1687                            reparseFlags = PackageParser.PARSE_IS_SYSTEM
1688                                    | PackageParser.PARSE_IS_SYSTEM_DIR;
1689                        } else {
1690                            Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile);
1691                            continue;
1692                        }
1693
1694                        mSettings.enableSystemPackageLPw(packageName);
1695
1696                        try {
1697                            scanPackageLI(scanFile, reparseFlags, scanFlags, 0, null);
1698                        } catch (PackageManagerException e) {
1699                            Slog.e(TAG, "Failed to parse original system package: "
1700                                    + e.getMessage());
1701                        }
1702                    }
1703                }
1704            }
1705
1706            // Now that we know all of the shared libraries, update all clients to have
1707            // the correct library paths.
1708            updateAllSharedLibrariesLPw();
1709
1710            for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) {
1711                // NOTE: We ignore potential failures here during a system scan (like
1712                // the rest of the commands above) because there's precious little we
1713                // can do about it. A settings error is reported, though.
1714                adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */,
1715                        false /* force dexopt */, false /* defer dexopt */);
1716            }
1717
1718            // Now that we know all the packages we are keeping,
1719            // read and update their last usage times.
1720            mPackageUsage.readLP();
1721
1722            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END,
1723                    SystemClock.uptimeMillis());
1724            Slog.i(TAG, "Time to scan packages: "
1725                    + ((SystemClock.uptimeMillis()-startTime)/1000f)
1726                    + " seconds");
1727
1728            // If the platform SDK has changed since the last time we booted,
1729            // we need to re-grant app permission to catch any new ones that
1730            // appear.  This is really a hack, and means that apps can in some
1731            // cases get permissions that the user didn't initially explicitly
1732            // allow...  it would be nice to have some better way to handle
1733            // this situation.
1734            final boolean regrantPermissions = mSettings.mInternalSdkPlatform
1735                    != mSdkVersion;
1736            if (regrantPermissions) Slog.i(TAG, "Platform changed from "
1737                    + mSettings.mInternalSdkPlatform + " to " + mSdkVersion
1738                    + "; regranting permissions for internal storage");
1739            mSettings.mInternalSdkPlatform = mSdkVersion;
1740
1741            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
1742                    | (regrantPermissions
1743                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
1744                            : 0));
1745
1746            // If this is the first boot, and it is a normal boot, then
1747            // we need to initialize the default preferred apps.
1748            if (!mRestoredSettings && !onlyCore) {
1749                mSettings.readDefaultPreferredAppsLPw(this, 0);
1750            }
1751
1752            // If this is first boot after an OTA, and a normal boot, then
1753            // we need to clear code cache directories.
1754            mIsUpgrade = !Build.FINGERPRINT.equals(mSettings.mFingerprint);
1755            if (mIsUpgrade && !onlyCore) {
1756                Slog.i(TAG, "Build fingerprint changed; clearing code caches");
1757                for (String pkgName : mSettings.mPackages.keySet()) {
1758                    deleteCodeCacheDirsLI(pkgName);
1759                }
1760                mSettings.mFingerprint = Build.FINGERPRINT;
1761            }
1762
1763            // All the changes are done during package scanning.
1764            mSettings.updateInternalDatabaseVersion();
1765
1766            // can downgrade to reader
1767            mSettings.writeLPr();
1768
1769            EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY,
1770                    SystemClock.uptimeMillis());
1771
1772
1773            mRequiredVerifierPackage = getRequiredVerifierLPr();
1774        } // synchronized (mPackages)
1775        } // synchronized (mInstallLock)
1776
1777        mInstallerService = new PackageInstallerService(context, this, mAppInstallDir);
1778
1779        // Now after opening every single application zip, make sure they
1780        // are all flushed.  Not really needed, but keeps things nice and
1781        // tidy.
1782        Runtime.getRuntime().gc();
1783    }
1784
1785    @Override
1786    public boolean isFirstBoot() {
1787        return !mRestoredSettings;
1788    }
1789
1790    @Override
1791    public boolean isOnlyCoreApps() {
1792        return mOnlyCore;
1793    }
1794
1795    @Override
1796    public boolean isUpgrade() {
1797        return mIsUpgrade;
1798    }
1799
1800    private String getRequiredVerifierLPr() {
1801        final Intent verification = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
1802        final List<ResolveInfo> receivers = queryIntentReceivers(verification, PACKAGE_MIME_TYPE,
1803                PackageManager.GET_DISABLED_COMPONENTS, 0 /* TODO: Which userId? */);
1804
1805        String requiredVerifier = null;
1806
1807        final int N = receivers.size();
1808        for (int i = 0; i < N; i++) {
1809            final ResolveInfo info = receivers.get(i);
1810
1811            if (info.activityInfo == null) {
1812                continue;
1813            }
1814
1815            final String packageName = info.activityInfo.packageName;
1816
1817            final PackageSetting ps = mSettings.mPackages.get(packageName);
1818            if (ps == null) {
1819                continue;
1820            }
1821
1822            final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1823            if (!gp.grantedPermissions
1824                    .contains(android.Manifest.permission.PACKAGE_VERIFICATION_AGENT)) {
1825                continue;
1826            }
1827
1828            if (requiredVerifier != null) {
1829                throw new RuntimeException("There can be only one required verifier");
1830            }
1831
1832            requiredVerifier = packageName;
1833        }
1834
1835        return requiredVerifier;
1836    }
1837
1838    @Override
1839    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
1840            throws RemoteException {
1841        try {
1842            return super.onTransact(code, data, reply, flags);
1843        } catch (RuntimeException e) {
1844            if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) {
1845                Slog.wtf(TAG, "Package Manager Crash", e);
1846            }
1847            throw e;
1848        }
1849    }
1850
1851    void cleanupInstallFailedPackage(PackageSetting ps) {
1852        logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + ps.name);
1853
1854        removeDataDirsLI(ps.name);
1855        if (ps.codePath != null) {
1856            if (ps.codePath.isDirectory()) {
1857                FileUtils.deleteContents(ps.codePath);
1858            }
1859            ps.codePath.delete();
1860        }
1861        if (ps.resourcePath != null && !ps.resourcePath.equals(ps.codePath)) {
1862            if (ps.resourcePath.isDirectory()) {
1863                FileUtils.deleteContents(ps.resourcePath);
1864            }
1865            ps.resourcePath.delete();
1866        }
1867        mSettings.removePackageLPw(ps.name);
1868    }
1869
1870    static int[] appendInts(int[] cur, int[] add) {
1871        if (add == null) return cur;
1872        if (cur == null) return add;
1873        final int N = add.length;
1874        for (int i=0; i<N; i++) {
1875            cur = appendInt(cur, add[i]);
1876        }
1877        return cur;
1878    }
1879
1880    static int[] removeInts(int[] cur, int[] rem) {
1881        if (rem == null) return cur;
1882        if (cur == null) return cur;
1883        final int N = rem.length;
1884        for (int i=0; i<N; i++) {
1885            cur = removeInt(cur, rem[i]);
1886        }
1887        return cur;
1888    }
1889
1890    PackageInfo generatePackageInfo(PackageParser.Package p, int flags, int userId) {
1891        if (!sUserManager.exists(userId)) return null;
1892        final PackageSetting ps = (PackageSetting) p.mExtras;
1893        if (ps == null) {
1894            return null;
1895        }
1896        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
1897        final PackageUserState state = ps.readUserState(userId);
1898        return PackageParser.generatePackageInfo(p, gp.gids, flags,
1899                ps.firstInstallTime, ps.lastUpdateTime, gp.grantedPermissions,
1900                state, userId);
1901    }
1902
1903    @Override
1904    public boolean isPackageAvailable(String packageName, int userId) {
1905        if (!sUserManager.exists(userId)) return false;
1906        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "is package available");
1907        synchronized (mPackages) {
1908            PackageParser.Package p = mPackages.get(packageName);
1909            if (p != null) {
1910                final PackageSetting ps = (PackageSetting) p.mExtras;
1911                if (ps != null) {
1912                    final PackageUserState state = ps.readUserState(userId);
1913                    if (state != null) {
1914                        return PackageParser.isAvailable(state);
1915                    }
1916                }
1917            }
1918        }
1919        return false;
1920    }
1921
1922    @Override
1923    public PackageInfo getPackageInfo(String packageName, int flags, int userId) {
1924        if (!sUserManager.exists(userId)) return null;
1925        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package info");
1926        // reader
1927        synchronized (mPackages) {
1928            PackageParser.Package p = mPackages.get(packageName);
1929            if (DEBUG_PACKAGE_INFO)
1930                Log.v(TAG, "getPackageInfo " + packageName + ": " + p);
1931            if (p != null) {
1932                return generatePackageInfo(p, flags, userId);
1933            }
1934            if((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
1935                return generatePackageInfoFromSettingsLPw(packageName, flags, userId);
1936            }
1937        }
1938        return null;
1939    }
1940
1941    @Override
1942    public String[] currentToCanonicalPackageNames(String[] names) {
1943        String[] out = new String[names.length];
1944        // reader
1945        synchronized (mPackages) {
1946            for (int i=names.length-1; i>=0; i--) {
1947                PackageSetting ps = mSettings.mPackages.get(names[i]);
1948                out[i] = ps != null && ps.realName != null ? ps.realName : names[i];
1949            }
1950        }
1951        return out;
1952    }
1953
1954    @Override
1955    public String[] canonicalToCurrentPackageNames(String[] names) {
1956        String[] out = new String[names.length];
1957        // reader
1958        synchronized (mPackages) {
1959            for (int i=names.length-1; i>=0; i--) {
1960                String cur = mSettings.mRenamedPackages.get(names[i]);
1961                out[i] = cur != null ? cur : names[i];
1962            }
1963        }
1964        return out;
1965    }
1966
1967    @Override
1968    public int getPackageUid(String packageName, int userId) {
1969        if (!sUserManager.exists(userId)) return -1;
1970        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get package uid");
1971        // reader
1972        synchronized (mPackages) {
1973            PackageParser.Package p = mPackages.get(packageName);
1974            if(p != null) {
1975                return UserHandle.getUid(userId, p.applicationInfo.uid);
1976            }
1977            PackageSetting ps = mSettings.mPackages.get(packageName);
1978            if((ps == null) || (ps.pkg == null) || (ps.pkg.applicationInfo == null)) {
1979                return -1;
1980            }
1981            p = ps.pkg;
1982            return p != null ? UserHandle.getUid(userId, p.applicationInfo.uid) : -1;
1983        }
1984    }
1985
1986    @Override
1987    public int[] getPackageGids(String packageName) {
1988        // reader
1989        synchronized (mPackages) {
1990            PackageParser.Package p = mPackages.get(packageName);
1991            if (DEBUG_PACKAGE_INFO)
1992                Log.v(TAG, "getPackageGids" + packageName + ": " + p);
1993            if (p != null) {
1994                final PackageSetting ps = (PackageSetting)p.mExtras;
1995                return ps.getGids();
1996            }
1997        }
1998        // stupid thing to indicate an error.
1999        return new int[0];
2000    }
2001
2002    static final PermissionInfo generatePermissionInfo(
2003            BasePermission bp, int flags) {
2004        if (bp.perm != null) {
2005            return PackageParser.generatePermissionInfo(bp.perm, flags);
2006        }
2007        PermissionInfo pi = new PermissionInfo();
2008        pi.name = bp.name;
2009        pi.packageName = bp.sourcePackage;
2010        pi.nonLocalizedLabel = bp.name;
2011        pi.protectionLevel = bp.protectionLevel;
2012        return pi;
2013    }
2014
2015    @Override
2016    public PermissionInfo getPermissionInfo(String name, int flags) {
2017        // reader
2018        synchronized (mPackages) {
2019            final BasePermission p = mSettings.mPermissions.get(name);
2020            if (p != null) {
2021                return generatePermissionInfo(p, flags);
2022            }
2023            return null;
2024        }
2025    }
2026
2027    @Override
2028    public List<PermissionInfo> queryPermissionsByGroup(String group, int flags) {
2029        // reader
2030        synchronized (mPackages) {
2031            ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10);
2032            for (BasePermission p : mSettings.mPermissions.values()) {
2033                if (group == null) {
2034                    if (p.perm == null || p.perm.info.group == null) {
2035                        out.add(generatePermissionInfo(p, flags));
2036                    }
2037                } else {
2038                    if (p.perm != null && group.equals(p.perm.info.group)) {
2039                        out.add(PackageParser.generatePermissionInfo(p.perm, flags));
2040                    }
2041                }
2042            }
2043
2044            if (out.size() > 0) {
2045                return out;
2046            }
2047            return mPermissionGroups.containsKey(group) ? out : null;
2048        }
2049    }
2050
2051    @Override
2052    public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) {
2053        // reader
2054        synchronized (mPackages) {
2055            return PackageParser.generatePermissionGroupInfo(
2056                    mPermissionGroups.get(name), flags);
2057        }
2058    }
2059
2060    @Override
2061    public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
2062        // reader
2063        synchronized (mPackages) {
2064            final int N = mPermissionGroups.size();
2065            ArrayList<PermissionGroupInfo> out
2066                    = new ArrayList<PermissionGroupInfo>(N);
2067            for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) {
2068                out.add(PackageParser.generatePermissionGroupInfo(pg, flags));
2069            }
2070            return out;
2071        }
2072    }
2073
2074    private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags,
2075            int userId) {
2076        if (!sUserManager.exists(userId)) return null;
2077        PackageSetting ps = mSettings.mPackages.get(packageName);
2078        if (ps != null) {
2079            if (ps.pkg == null) {
2080                PackageInfo pInfo = generatePackageInfoFromSettingsLPw(packageName,
2081                        flags, userId);
2082                if (pInfo != null) {
2083                    return pInfo.applicationInfo;
2084                }
2085                return null;
2086            }
2087            return PackageParser.generateApplicationInfo(ps.pkg, flags,
2088                    ps.readUserState(userId), userId);
2089        }
2090        return null;
2091    }
2092
2093    private PackageInfo generatePackageInfoFromSettingsLPw(String packageName, int flags,
2094            int userId) {
2095        if (!sUserManager.exists(userId)) return null;
2096        PackageSetting ps = mSettings.mPackages.get(packageName);
2097        if (ps != null) {
2098            PackageParser.Package pkg = ps.pkg;
2099            if (pkg == null) {
2100                if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) == 0) {
2101                    return null;
2102                }
2103                // Only data remains, so we aren't worried about code paths
2104                pkg = new PackageParser.Package(packageName);
2105                pkg.applicationInfo.packageName = packageName;
2106                pkg.applicationInfo.flags = ps.pkgFlags | ApplicationInfo.FLAG_IS_DATA_ONLY;
2107                pkg.applicationInfo.dataDir =
2108                        getDataPathForPackage(packageName, 0).getPath();
2109                pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString;
2110                pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString;
2111            }
2112            return generatePackageInfo(pkg, flags, userId);
2113        }
2114        return null;
2115    }
2116
2117    @Override
2118    public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) {
2119        if (!sUserManager.exists(userId)) return null;
2120        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get application info");
2121        // writer
2122        synchronized (mPackages) {
2123            PackageParser.Package p = mPackages.get(packageName);
2124            if (DEBUG_PACKAGE_INFO) Log.v(
2125                    TAG, "getApplicationInfo " + packageName
2126                    + ": " + p);
2127            if (p != null) {
2128                PackageSetting ps = mSettings.mPackages.get(packageName);
2129                if (ps == null) return null;
2130                // Note: isEnabledLP() does not apply here - always return info
2131                return PackageParser.generateApplicationInfo(
2132                        p, flags, ps.readUserState(userId), userId);
2133            }
2134            if ("android".equals(packageName)||"system".equals(packageName)) {
2135                return mAndroidApplication;
2136            }
2137            if ((flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0) {
2138                return generateApplicationInfoFromSettingsLPw(packageName, flags, userId);
2139            }
2140        }
2141        return null;
2142    }
2143
2144
2145    @Override
2146    public void freeStorageAndNotify(final long freeStorageSize, final IPackageDataObserver observer) {
2147        mContext.enforceCallingOrSelfPermission(
2148                android.Manifest.permission.CLEAR_APP_CACHE, null);
2149        // Queue up an async operation since clearing cache may take a little while.
2150        mHandler.post(new Runnable() {
2151            public void run() {
2152                mHandler.removeCallbacks(this);
2153                int retCode = -1;
2154                synchronized (mInstallLock) {
2155                    retCode = mInstaller.freeCache(freeStorageSize);
2156                    if (retCode < 0) {
2157                        Slog.w(TAG, "Couldn't clear application caches");
2158                    }
2159                }
2160                if (observer != null) {
2161                    try {
2162                        observer.onRemoveCompleted(null, (retCode >= 0));
2163                    } catch (RemoteException e) {
2164                        Slog.w(TAG, "RemoveException when invoking call back");
2165                    }
2166                }
2167            }
2168        });
2169    }
2170
2171    @Override
2172    public void freeStorage(final long freeStorageSize, final IntentSender pi) {
2173        mContext.enforceCallingOrSelfPermission(
2174                android.Manifest.permission.CLEAR_APP_CACHE, null);
2175        // Queue up an async operation since clearing cache may take a little while.
2176        mHandler.post(new Runnable() {
2177            public void run() {
2178                mHandler.removeCallbacks(this);
2179                int retCode = -1;
2180                synchronized (mInstallLock) {
2181                    retCode = mInstaller.freeCache(freeStorageSize);
2182                    if (retCode < 0) {
2183                        Slog.w(TAG, "Couldn't clear application caches");
2184                    }
2185                }
2186                if(pi != null) {
2187                    try {
2188                        // Callback via pending intent
2189                        int code = (retCode >= 0) ? 1 : 0;
2190                        pi.sendIntent(null, code, null,
2191                                null, null);
2192                    } catch (SendIntentException e1) {
2193                        Slog.i(TAG, "Failed to send pending intent");
2194                    }
2195                }
2196            }
2197        });
2198    }
2199
2200    void freeStorage(long freeStorageSize) throws IOException {
2201        synchronized (mInstallLock) {
2202            if (mInstaller.freeCache(freeStorageSize) < 0) {
2203                throw new IOException("Failed to free enough space");
2204            }
2205        }
2206    }
2207
2208    @Override
2209    public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) {
2210        if (!sUserManager.exists(userId)) return null;
2211        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get activity info");
2212        synchronized (mPackages) {
2213            PackageParser.Activity a = mActivities.mActivities.get(component);
2214
2215            if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a);
2216            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2217                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2218                if (ps == null) return null;
2219                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2220                        userId);
2221            }
2222            if (mResolveComponentName.equals(component)) {
2223                return PackageParser.generateActivityInfo(mResolveActivity, flags,
2224                        new PackageUserState(), userId);
2225            }
2226        }
2227        return null;
2228    }
2229
2230    @Override
2231    public boolean activitySupportsIntent(ComponentName component, Intent intent,
2232            String resolvedType) {
2233        synchronized (mPackages) {
2234            PackageParser.Activity a = mActivities.mActivities.get(component);
2235            if (a == null) {
2236                return false;
2237            }
2238            for (int i=0; i<a.intents.size(); i++) {
2239                if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(),
2240                        intent.getData(), intent.getCategories(), TAG) >= 0) {
2241                    return true;
2242                }
2243            }
2244            return false;
2245        }
2246    }
2247
2248    @Override
2249    public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) {
2250        if (!sUserManager.exists(userId)) return null;
2251        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get receiver info");
2252        synchronized (mPackages) {
2253            PackageParser.Activity a = mReceivers.mActivities.get(component);
2254            if (DEBUG_PACKAGE_INFO) Log.v(
2255                TAG, "getReceiverInfo " + component + ": " + a);
2256            if (a != null && mSettings.isEnabledLPr(a.info, flags, userId)) {
2257                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2258                if (ps == null) return null;
2259                return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId),
2260                        userId);
2261            }
2262        }
2263        return null;
2264    }
2265
2266    @Override
2267    public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) {
2268        if (!sUserManager.exists(userId)) return null;
2269        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get service info");
2270        synchronized (mPackages) {
2271            PackageParser.Service s = mServices.mServices.get(component);
2272            if (DEBUG_PACKAGE_INFO) Log.v(
2273                TAG, "getServiceInfo " + component + ": " + s);
2274            if (s != null && mSettings.isEnabledLPr(s.info, flags, userId)) {
2275                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2276                if (ps == null) return null;
2277                return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId),
2278                        userId);
2279            }
2280        }
2281        return null;
2282    }
2283
2284    @Override
2285    public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) {
2286        if (!sUserManager.exists(userId)) return null;
2287        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "get provider info");
2288        synchronized (mPackages) {
2289            PackageParser.Provider p = mProviders.mProviders.get(component);
2290            if (DEBUG_PACKAGE_INFO) Log.v(
2291                TAG, "getProviderInfo " + component + ": " + p);
2292            if (p != null && mSettings.isEnabledLPr(p.info, flags, userId)) {
2293                PackageSetting ps = mSettings.mPackages.get(component.getPackageName());
2294                if (ps == null) return null;
2295                return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId),
2296                        userId);
2297            }
2298        }
2299        return null;
2300    }
2301
2302    @Override
2303    public String[] getSystemSharedLibraryNames() {
2304        Set<String> libSet;
2305        synchronized (mPackages) {
2306            libSet = mSharedLibraries.keySet();
2307            int size = libSet.size();
2308            if (size > 0) {
2309                String[] libs = new String[size];
2310                libSet.toArray(libs);
2311                return libs;
2312            }
2313        }
2314        return null;
2315    }
2316
2317    @Override
2318    public FeatureInfo[] getSystemAvailableFeatures() {
2319        Collection<FeatureInfo> featSet;
2320        synchronized (mPackages) {
2321            featSet = mAvailableFeatures.values();
2322            int size = featSet.size();
2323            if (size > 0) {
2324                FeatureInfo[] features = new FeatureInfo[size+1];
2325                featSet.toArray(features);
2326                FeatureInfo fi = new FeatureInfo();
2327                fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version",
2328                        FeatureInfo.GL_ES_VERSION_UNDEFINED);
2329                features[size] = fi;
2330                return features;
2331            }
2332        }
2333        return null;
2334    }
2335
2336    @Override
2337    public boolean hasSystemFeature(String name) {
2338        synchronized (mPackages) {
2339            return mAvailableFeatures.containsKey(name);
2340        }
2341    }
2342
2343    private void checkValidCaller(int uid, int userId) {
2344        if (UserHandle.getUserId(uid) == userId || uid == Process.SYSTEM_UID || uid == 0)
2345            return;
2346
2347        throw new SecurityException("Caller uid=" + uid
2348                + " is not privileged to communicate with user=" + userId);
2349    }
2350
2351    @Override
2352    public int checkPermission(String permName, String pkgName) {
2353        synchronized (mPackages) {
2354            PackageParser.Package p = mPackages.get(pkgName);
2355            if (p != null && p.mExtras != null) {
2356                PackageSetting ps = (PackageSetting)p.mExtras;
2357                if (ps.sharedUser != null) {
2358                    if (ps.sharedUser.grantedPermissions.contains(permName)) {
2359                        return PackageManager.PERMISSION_GRANTED;
2360                    }
2361                } else if (ps.grantedPermissions.contains(permName)) {
2362                    return PackageManager.PERMISSION_GRANTED;
2363                }
2364            }
2365        }
2366        return PackageManager.PERMISSION_DENIED;
2367    }
2368
2369    @Override
2370    public int checkUidPermission(String permName, int uid) {
2371        synchronized (mPackages) {
2372            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2373            if (obj != null) {
2374                GrantedPermissions gp = (GrantedPermissions)obj;
2375                if (gp.grantedPermissions.contains(permName)) {
2376                    return PackageManager.PERMISSION_GRANTED;
2377                }
2378            } else {
2379                HashSet<String> perms = mSystemPermissions.get(uid);
2380                if (perms != null && perms.contains(permName)) {
2381                    return PackageManager.PERMISSION_GRANTED;
2382                }
2383            }
2384        }
2385        return PackageManager.PERMISSION_DENIED;
2386    }
2387
2388    /**
2389     * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS
2390     * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller.
2391     * @param checkShell TODO(yamasani):
2392     * @param message the message to log on security exception
2393     */
2394    void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission,
2395            boolean checkShell, String message) {
2396        if (userId < 0) {
2397            throw new IllegalArgumentException("Invalid userId " + userId);
2398        }
2399        if (checkShell) {
2400            enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId);
2401        }
2402        if (userId == UserHandle.getUserId(callingUid)) return;
2403        if (callingUid != Process.SYSTEM_UID && callingUid != 0) {
2404            if (requireFullPermission) {
2405                mContext.enforceCallingOrSelfPermission(
2406                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2407            } else {
2408                try {
2409                    mContext.enforceCallingOrSelfPermission(
2410                            android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message);
2411                } catch (SecurityException se) {
2412                    mContext.enforceCallingOrSelfPermission(
2413                            android.Manifest.permission.INTERACT_ACROSS_USERS, message);
2414                }
2415            }
2416        }
2417    }
2418
2419    void enforceShellRestriction(String restriction, int callingUid, int userHandle) {
2420        if (callingUid == Process.SHELL_UID) {
2421            if (userHandle >= 0
2422                    && sUserManager.hasUserRestriction(restriction, userHandle)) {
2423                throw new SecurityException("Shell does not have permission to access user "
2424                        + userHandle);
2425            } else if (userHandle < 0) {
2426                Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t"
2427                        + Debug.getCallers(3));
2428            }
2429        }
2430    }
2431
2432    private BasePermission findPermissionTreeLP(String permName) {
2433        for(BasePermission bp : mSettings.mPermissionTrees.values()) {
2434            if (permName.startsWith(bp.name) &&
2435                    permName.length() > bp.name.length() &&
2436                    permName.charAt(bp.name.length()) == '.') {
2437                return bp;
2438            }
2439        }
2440        return null;
2441    }
2442
2443    private BasePermission checkPermissionTreeLP(String permName) {
2444        if (permName != null) {
2445            BasePermission bp = findPermissionTreeLP(permName);
2446            if (bp != null) {
2447                if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) {
2448                    return bp;
2449                }
2450                throw new SecurityException("Calling uid "
2451                        + Binder.getCallingUid()
2452                        + " is not allowed to add to permission tree "
2453                        + bp.name + " owned by uid " + bp.uid);
2454            }
2455        }
2456        throw new SecurityException("No permission tree found for " + permName);
2457    }
2458
2459    static boolean compareStrings(CharSequence s1, CharSequence s2) {
2460        if (s1 == null) {
2461            return s2 == null;
2462        }
2463        if (s2 == null) {
2464            return false;
2465        }
2466        if (s1.getClass() != s2.getClass()) {
2467            return false;
2468        }
2469        return s1.equals(s2);
2470    }
2471
2472    static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) {
2473        if (pi1.icon != pi2.icon) return false;
2474        if (pi1.logo != pi2.logo) return false;
2475        if (pi1.protectionLevel != pi2.protectionLevel) return false;
2476        if (!compareStrings(pi1.name, pi2.name)) return false;
2477        if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false;
2478        // We'll take care of setting this one.
2479        if (!compareStrings(pi1.packageName, pi2.packageName)) return false;
2480        // These are not currently stored in settings.
2481        //if (!compareStrings(pi1.group, pi2.group)) return false;
2482        //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false;
2483        //if (pi1.labelRes != pi2.labelRes) return false;
2484        //if (pi1.descriptionRes != pi2.descriptionRes) return false;
2485        return true;
2486    }
2487
2488    int permissionInfoFootprint(PermissionInfo info) {
2489        int size = info.name.length();
2490        if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length();
2491        if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length();
2492        return size;
2493    }
2494
2495    int calculateCurrentPermissionFootprintLocked(BasePermission tree) {
2496        int size = 0;
2497        for (BasePermission perm : mSettings.mPermissions.values()) {
2498            if (perm.uid == tree.uid) {
2499                size += perm.name.length() + permissionInfoFootprint(perm.perm.info);
2500            }
2501        }
2502        return size;
2503    }
2504
2505    void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) {
2506        // We calculate the max size of permissions defined by this uid and throw
2507        // if that plus the size of 'info' would exceed our stated maximum.
2508        if (tree.uid != Process.SYSTEM_UID) {
2509            final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree);
2510            if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) {
2511                throw new SecurityException("Permission tree size cap exceeded");
2512            }
2513        }
2514    }
2515
2516    boolean addPermissionLocked(PermissionInfo info, boolean async) {
2517        if (info.labelRes == 0 && info.nonLocalizedLabel == null) {
2518            throw new SecurityException("Label must be specified in permission");
2519        }
2520        BasePermission tree = checkPermissionTreeLP(info.name);
2521        BasePermission bp = mSettings.mPermissions.get(info.name);
2522        boolean added = bp == null;
2523        boolean changed = true;
2524        int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel);
2525        if (added) {
2526            enforcePermissionCapLocked(info, tree);
2527            bp = new BasePermission(info.name, tree.sourcePackage,
2528                    BasePermission.TYPE_DYNAMIC);
2529        } else if (bp.type != BasePermission.TYPE_DYNAMIC) {
2530            throw new SecurityException(
2531                    "Not allowed to modify non-dynamic permission "
2532                    + info.name);
2533        } else {
2534            if (bp.protectionLevel == fixedLevel
2535                    && bp.perm.owner.equals(tree.perm.owner)
2536                    && bp.uid == tree.uid
2537                    && comparePermissionInfos(bp.perm.info, info)) {
2538                changed = false;
2539            }
2540        }
2541        bp.protectionLevel = fixedLevel;
2542        info = new PermissionInfo(info);
2543        info.protectionLevel = fixedLevel;
2544        bp.perm = new PackageParser.Permission(tree.perm.owner, info);
2545        bp.perm.info.packageName = tree.perm.info.packageName;
2546        bp.uid = tree.uid;
2547        if (added) {
2548            mSettings.mPermissions.put(info.name, bp);
2549        }
2550        if (changed) {
2551            if (!async) {
2552                mSettings.writeLPr();
2553            } else {
2554                scheduleWriteSettingsLocked();
2555            }
2556        }
2557        return added;
2558    }
2559
2560    @Override
2561    public boolean addPermission(PermissionInfo info) {
2562        synchronized (mPackages) {
2563            return addPermissionLocked(info, false);
2564        }
2565    }
2566
2567    @Override
2568    public boolean addPermissionAsync(PermissionInfo info) {
2569        synchronized (mPackages) {
2570            return addPermissionLocked(info, true);
2571        }
2572    }
2573
2574    @Override
2575    public void removePermission(String name) {
2576        synchronized (mPackages) {
2577            checkPermissionTreeLP(name);
2578            BasePermission bp = mSettings.mPermissions.get(name);
2579            if (bp != null) {
2580                if (bp.type != BasePermission.TYPE_DYNAMIC) {
2581                    throw new SecurityException(
2582                            "Not allowed to modify non-dynamic permission "
2583                            + name);
2584                }
2585                mSettings.mPermissions.remove(name);
2586                mSettings.writeLPr();
2587            }
2588        }
2589    }
2590
2591    private static void checkGrantRevokePermissions(PackageParser.Package pkg, BasePermission bp) {
2592        int index = pkg.requestedPermissions.indexOf(bp.name);
2593        if (index == -1) {
2594            throw new SecurityException("Package " + pkg.packageName
2595                    + " has not requested permission " + bp.name);
2596        }
2597        boolean isNormal =
2598                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2599                        == PermissionInfo.PROTECTION_NORMAL);
2600        boolean isDangerous =
2601                ((bp.protectionLevel&PermissionInfo.PROTECTION_MASK_BASE)
2602                        == PermissionInfo.PROTECTION_DANGEROUS);
2603        boolean isDevelopment =
2604                ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0);
2605
2606        if (!isNormal && !isDangerous && !isDevelopment) {
2607            throw new SecurityException("Permission " + bp.name
2608                    + " is not a changeable permission type");
2609        }
2610
2611        if (isNormal || isDangerous) {
2612            if (pkg.requestedPermissionsRequired.get(index)) {
2613                throw new SecurityException("Can't change " + bp.name
2614                        + ". It is required by the application");
2615            }
2616        }
2617    }
2618
2619    @Override
2620    public void grantPermission(String packageName, String permissionName) {
2621        mContext.enforceCallingOrSelfPermission(
2622                android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2623        synchronized (mPackages) {
2624            final PackageParser.Package pkg = mPackages.get(packageName);
2625            if (pkg == null) {
2626                throw new IllegalArgumentException("Unknown package: " + packageName);
2627            }
2628            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2629            if (bp == null) {
2630                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2631            }
2632
2633            checkGrantRevokePermissions(pkg, bp);
2634
2635            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2636            if (ps == null) {
2637                return;
2638            }
2639            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2640            if (gp.grantedPermissions.add(permissionName)) {
2641                if (ps.haveGids) {
2642                    gp.gids = appendInts(gp.gids, bp.gids);
2643                }
2644                mSettings.writeLPr();
2645            }
2646        }
2647    }
2648
2649    @Override
2650    public void revokePermission(String packageName, String permissionName) {
2651        int changedAppId = -1;
2652
2653        synchronized (mPackages) {
2654            final PackageParser.Package pkg = mPackages.get(packageName);
2655            if (pkg == null) {
2656                throw new IllegalArgumentException("Unknown package: " + packageName);
2657            }
2658            if (pkg.applicationInfo.uid != Binder.getCallingUid()) {
2659                mContext.enforceCallingOrSelfPermission(
2660                        android.Manifest.permission.GRANT_REVOKE_PERMISSIONS, null);
2661            }
2662            final BasePermission bp = mSettings.mPermissions.get(permissionName);
2663            if (bp == null) {
2664                throw new IllegalArgumentException("Unknown permission: " + permissionName);
2665            }
2666
2667            checkGrantRevokePermissions(pkg, bp);
2668
2669            final PackageSetting ps = (PackageSetting) pkg.mExtras;
2670            if (ps == null) {
2671                return;
2672            }
2673            final GrantedPermissions gp = (ps.sharedUser != null) ? ps.sharedUser : ps;
2674            if (gp.grantedPermissions.remove(permissionName)) {
2675                gp.grantedPermissions.remove(permissionName);
2676                if (ps.haveGids) {
2677                    gp.gids = removeInts(gp.gids, bp.gids);
2678                }
2679                mSettings.writeLPr();
2680                changedAppId = ps.appId;
2681            }
2682        }
2683
2684        if (changedAppId >= 0) {
2685            // We changed the perm on someone, kill its processes.
2686            IActivityManager am = ActivityManagerNative.getDefault();
2687            if (am != null) {
2688                final int callingUserId = UserHandle.getCallingUserId();
2689                final long ident = Binder.clearCallingIdentity();
2690                try {
2691                    //XXX we should only revoke for the calling user's app permissions,
2692                    // but for now we impact all users.
2693                    //am.killUid(UserHandle.getUid(callingUserId, changedAppId),
2694                    //        "revoke " + permissionName);
2695                    int[] users = sUserManager.getUserIds();
2696                    for (int user : users) {
2697                        am.killUid(UserHandle.getUid(user, changedAppId),
2698                                "revoke " + permissionName);
2699                    }
2700                } catch (RemoteException e) {
2701                } finally {
2702                    Binder.restoreCallingIdentity(ident);
2703                }
2704            }
2705        }
2706    }
2707
2708    @Override
2709    public boolean isProtectedBroadcast(String actionName) {
2710        synchronized (mPackages) {
2711            return mProtectedBroadcasts.contains(actionName);
2712        }
2713    }
2714
2715    @Override
2716    public int checkSignatures(String pkg1, String pkg2) {
2717        synchronized (mPackages) {
2718            final PackageParser.Package p1 = mPackages.get(pkg1);
2719            final PackageParser.Package p2 = mPackages.get(pkg2);
2720            if (p1 == null || p1.mExtras == null
2721                    || p2 == null || p2.mExtras == null) {
2722                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2723            }
2724            return compareSignatures(p1.mSignatures, p2.mSignatures);
2725        }
2726    }
2727
2728    @Override
2729    public int checkUidSignatures(int uid1, int uid2) {
2730        // Map to base uids.
2731        uid1 = UserHandle.getAppId(uid1);
2732        uid2 = UserHandle.getAppId(uid2);
2733        // reader
2734        synchronized (mPackages) {
2735            Signature[] s1;
2736            Signature[] s2;
2737            Object obj = mSettings.getUserIdLPr(uid1);
2738            if (obj != null) {
2739                if (obj instanceof SharedUserSetting) {
2740                    s1 = ((SharedUserSetting)obj).signatures.mSignatures;
2741                } else if (obj instanceof PackageSetting) {
2742                    s1 = ((PackageSetting)obj).signatures.mSignatures;
2743                } else {
2744                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2745                }
2746            } else {
2747                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2748            }
2749            obj = mSettings.getUserIdLPr(uid2);
2750            if (obj != null) {
2751                if (obj instanceof SharedUserSetting) {
2752                    s2 = ((SharedUserSetting)obj).signatures.mSignatures;
2753                } else if (obj instanceof PackageSetting) {
2754                    s2 = ((PackageSetting)obj).signatures.mSignatures;
2755                } else {
2756                    return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2757                }
2758            } else {
2759                return PackageManager.SIGNATURE_UNKNOWN_PACKAGE;
2760            }
2761            return compareSignatures(s1, s2);
2762        }
2763    }
2764
2765    /**
2766     * Compares two sets of signatures. Returns:
2767     * <br />
2768     * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null,
2769     * <br />
2770     * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null,
2771     * <br />
2772     * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null,
2773     * <br />
2774     * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical,
2775     * <br />
2776     * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ.
2777     */
2778    static int compareSignatures(Signature[] s1, Signature[] s2) {
2779        if (s1 == null) {
2780            return s2 == null
2781                    ? PackageManager.SIGNATURE_NEITHER_SIGNED
2782                    : PackageManager.SIGNATURE_FIRST_NOT_SIGNED;
2783        }
2784
2785        if (s2 == null) {
2786            return PackageManager.SIGNATURE_SECOND_NOT_SIGNED;
2787        }
2788
2789        if (s1.length != s2.length) {
2790            return PackageManager.SIGNATURE_NO_MATCH;
2791        }
2792
2793        // Since both signature sets are of size 1, we can compare without HashSets.
2794        if (s1.length == 1) {
2795            return s1[0].equals(s2[0]) ?
2796                    PackageManager.SIGNATURE_MATCH :
2797                    PackageManager.SIGNATURE_NO_MATCH;
2798        }
2799
2800        HashSet<Signature> set1 = new HashSet<Signature>();
2801        for (Signature sig : s1) {
2802            set1.add(sig);
2803        }
2804        HashSet<Signature> set2 = new HashSet<Signature>();
2805        for (Signature sig : s2) {
2806            set2.add(sig);
2807        }
2808        // Make sure s2 contains all signatures in s1.
2809        if (set1.equals(set2)) {
2810            return PackageManager.SIGNATURE_MATCH;
2811        }
2812        return PackageManager.SIGNATURE_NO_MATCH;
2813    }
2814
2815    /**
2816     * If the database version for this type of package (internal storage or
2817     * external storage) is less than the version where package signatures
2818     * were updated, return true.
2819     */
2820    private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2821        return (isExternal(scannedPkg) && mSettings.isExternalDatabaseVersionOlderThan(
2822                DatabaseVersion.SIGNATURE_END_ENTITY))
2823                || (!isExternal(scannedPkg) && mSettings.isInternalDatabaseVersionOlderThan(
2824                        DatabaseVersion.SIGNATURE_END_ENTITY));
2825    }
2826
2827    /**
2828     * Used for backward compatibility to make sure any packages with
2829     * certificate chains get upgraded to the new style. {@code existingSigs}
2830     * will be in the old format (since they were stored on disk from before the
2831     * system upgrade) and {@code scannedSigs} will be in the newer format.
2832     */
2833    private int compareSignaturesCompat(PackageSignatures existingSigs,
2834            PackageParser.Package scannedPkg) {
2835        if (!isCompatSignatureUpdateNeeded(scannedPkg)) {
2836            return PackageManager.SIGNATURE_NO_MATCH;
2837        }
2838
2839        HashSet<Signature> existingSet = new HashSet<Signature>();
2840        for (Signature sig : existingSigs.mSignatures) {
2841            existingSet.add(sig);
2842        }
2843        HashSet<Signature> scannedCompatSet = new HashSet<Signature>();
2844        for (Signature sig : scannedPkg.mSignatures) {
2845            try {
2846                Signature[] chainSignatures = sig.getChainSignatures();
2847                for (Signature chainSig : chainSignatures) {
2848                    scannedCompatSet.add(chainSig);
2849                }
2850            } catch (CertificateEncodingException e) {
2851                scannedCompatSet.add(sig);
2852            }
2853        }
2854        /*
2855         * Make sure the expanded scanned set contains all signatures in the
2856         * existing one.
2857         */
2858        if (scannedCompatSet.equals(existingSet)) {
2859            // Migrate the old signatures to the new scheme.
2860            existingSigs.assignSignatures(scannedPkg.mSignatures);
2861            // The new KeySets will be re-added later in the scanning process.
2862            synchronized (mPackages) {
2863                mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName);
2864            }
2865            return PackageManager.SIGNATURE_MATCH;
2866        }
2867        return PackageManager.SIGNATURE_NO_MATCH;
2868    }
2869
2870    private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) {
2871        if (isExternal(scannedPkg)) {
2872            return mSettings.isExternalDatabaseVersionOlderThan(
2873                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
2874        } else {
2875            return mSettings.isInternalDatabaseVersionOlderThan(
2876                    DatabaseVersion.SIGNATURE_MALFORMED_RECOVER);
2877        }
2878    }
2879
2880    private int compareSignaturesRecover(PackageSignatures existingSigs,
2881            PackageParser.Package scannedPkg) {
2882        if (!isRecoverSignatureUpdateNeeded(scannedPkg)) {
2883            return PackageManager.SIGNATURE_NO_MATCH;
2884        }
2885
2886        String msg = null;
2887        try {
2888            if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) {
2889                logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for "
2890                        + scannedPkg.packageName);
2891                return PackageManager.SIGNATURE_MATCH;
2892            }
2893        } catch (CertificateException e) {
2894            msg = e.getMessage();
2895        }
2896
2897        logCriticalInfo(Log.INFO,
2898                "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg);
2899        return PackageManager.SIGNATURE_NO_MATCH;
2900    }
2901
2902    @Override
2903    public String[] getPackagesForUid(int uid) {
2904        uid = UserHandle.getAppId(uid);
2905        // reader
2906        synchronized (mPackages) {
2907            Object obj = mSettings.getUserIdLPr(uid);
2908            if (obj instanceof SharedUserSetting) {
2909                final SharedUserSetting sus = (SharedUserSetting) obj;
2910                final int N = sus.packages.size();
2911                final String[] res = new String[N];
2912                final Iterator<PackageSetting> it = sus.packages.iterator();
2913                int i = 0;
2914                while (it.hasNext()) {
2915                    res[i++] = it.next().name;
2916                }
2917                return res;
2918            } else if (obj instanceof PackageSetting) {
2919                final PackageSetting ps = (PackageSetting) obj;
2920                return new String[] { ps.name };
2921            }
2922        }
2923        return null;
2924    }
2925
2926    @Override
2927    public String getNameForUid(int uid) {
2928        // reader
2929        synchronized (mPackages) {
2930            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2931            if (obj instanceof SharedUserSetting) {
2932                final SharedUserSetting sus = (SharedUserSetting) obj;
2933                return sus.name + ":" + sus.userId;
2934            } else if (obj instanceof PackageSetting) {
2935                final PackageSetting ps = (PackageSetting) obj;
2936                return ps.name;
2937            }
2938        }
2939        return null;
2940    }
2941
2942    @Override
2943    public int getUidForSharedUser(String sharedUserName) {
2944        if(sharedUserName == null) {
2945            return -1;
2946        }
2947        // reader
2948        synchronized (mPackages) {
2949            final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, false);
2950            if (suid == null) {
2951                return -1;
2952            }
2953            return suid.userId;
2954        }
2955    }
2956
2957    @Override
2958    public int getFlagsForUid(int uid) {
2959        synchronized (mPackages) {
2960            Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid));
2961            if (obj instanceof SharedUserSetting) {
2962                final SharedUserSetting sus = (SharedUserSetting) obj;
2963                return sus.pkgFlags;
2964            } else if (obj instanceof PackageSetting) {
2965                final PackageSetting ps = (PackageSetting) obj;
2966                return ps.pkgFlags;
2967            }
2968        }
2969        return 0;
2970    }
2971
2972    @Override
2973    public boolean isUidPrivileged(int uid) {
2974        uid = UserHandle.getAppId(uid);
2975        // reader
2976        synchronized (mPackages) {
2977            Object obj = mSettings.getUserIdLPr(uid);
2978            if (obj instanceof SharedUserSetting) {
2979                final SharedUserSetting sus = (SharedUserSetting) obj;
2980                final Iterator<PackageSetting> it = sus.packages.iterator();
2981                while (it.hasNext()) {
2982                    if (it.next().isPrivileged()) {
2983                        return true;
2984                    }
2985                }
2986            } else if (obj instanceof PackageSetting) {
2987                final PackageSetting ps = (PackageSetting) obj;
2988                return ps.isPrivileged();
2989            }
2990        }
2991        return false;
2992    }
2993
2994    @Override
2995    public String[] getAppOpPermissionPackages(String permissionName) {
2996        synchronized (mPackages) {
2997            ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName);
2998            if (pkgs == null) {
2999                return null;
3000            }
3001            return pkgs.toArray(new String[pkgs.size()]);
3002        }
3003    }
3004
3005    @Override
3006    public ResolveInfo resolveIntent(Intent intent, String resolvedType,
3007            int flags, int userId) {
3008        if (!sUserManager.exists(userId)) return null;
3009        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "resolve intent");
3010        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3011        return chooseBestActivity(intent, resolvedType, flags, query, userId);
3012    }
3013
3014    @Override
3015    public void setLastChosenActivity(Intent intent, String resolvedType, int flags,
3016            IntentFilter filter, int match, ComponentName activity) {
3017        final int userId = UserHandle.getCallingUserId();
3018        if (DEBUG_PREFERRED) {
3019            Log.v(TAG, "setLastChosenActivity intent=" + intent
3020                + " resolvedType=" + resolvedType
3021                + " flags=" + flags
3022                + " filter=" + filter
3023                + " match=" + match
3024                + " activity=" + activity);
3025            filter.dump(new PrintStreamPrinter(System.out), "    ");
3026        }
3027        intent.setComponent(null);
3028        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3029        // Find any earlier preferred or last chosen entries and nuke them
3030        findPreferredActivity(intent, resolvedType,
3031                flags, query, 0, false, true, false, userId);
3032        // Add the new activity as the last chosen for this filter
3033        addPreferredActivityInternal(filter, match, null, activity, false, userId,
3034                "Setting last chosen");
3035    }
3036
3037    @Override
3038    public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) {
3039        final int userId = UserHandle.getCallingUserId();
3040        if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent);
3041        List<ResolveInfo> query = queryIntentActivities(intent, resolvedType, flags, userId);
3042        return findPreferredActivity(intent, resolvedType, flags, query, 0,
3043                false, false, false, userId);
3044    }
3045
3046    private ResolveInfo chooseBestActivity(Intent intent, String resolvedType,
3047            int flags, List<ResolveInfo> query, int userId) {
3048        if (query != null) {
3049            final int N = query.size();
3050            if (N == 1) {
3051                return query.get(0);
3052            } else if (N > 1) {
3053                final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0);
3054                // If there is more than one activity with the same priority,
3055                // then let the user decide between them.
3056                ResolveInfo r0 = query.get(0);
3057                ResolveInfo r1 = query.get(1);
3058                if (DEBUG_INTENT_MATCHING || debug) {
3059                    Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs "
3060                            + r1.activityInfo.name + "=" + r1.priority);
3061                }
3062                // If the first activity has a higher priority, or a different
3063                // default, then it is always desireable to pick it.
3064                if (r0.priority != r1.priority
3065                        || r0.preferredOrder != r1.preferredOrder
3066                        || r0.isDefault != r1.isDefault) {
3067                    return query.get(0);
3068                }
3069                // If we have saved a preference for a preferred activity for
3070                // this Intent, use that.
3071                ResolveInfo ri = findPreferredActivity(intent, resolvedType,
3072                        flags, query, r0.priority, true, false, debug, userId);
3073                if (ri != null) {
3074                    return ri;
3075                }
3076                if (userId != 0) {
3077                    ri = new ResolveInfo(mResolveInfo);
3078                    ri.activityInfo = new ActivityInfo(ri.activityInfo);
3079                    ri.activityInfo.applicationInfo = new ApplicationInfo(
3080                            ri.activityInfo.applicationInfo);
3081                    ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId,
3082                            UserHandle.getAppId(ri.activityInfo.applicationInfo.uid));
3083                    return ri;
3084                }
3085                return mResolveInfo;
3086            }
3087        }
3088        return null;
3089    }
3090
3091    private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType,
3092            int flags, List<ResolveInfo> query, boolean debug, int userId) {
3093        final int N = query.size();
3094        PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
3095                .get(userId);
3096        // Get the list of persistent preferred activities that handle the intent
3097        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities...");
3098        List<PersistentPreferredActivity> pprefs = ppir != null
3099                ? ppir.queryIntent(intent, resolvedType,
3100                        (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3101                : null;
3102        if (pprefs != null && pprefs.size() > 0) {
3103            final int M = pprefs.size();
3104            for (int i=0; i<M; i++) {
3105                final PersistentPreferredActivity ppa = pprefs.get(i);
3106                if (DEBUG_PREFERRED || debug) {
3107                    Slog.v(TAG, "Checking PersistentPreferredActivity ds="
3108                            + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>")
3109                            + "\n  component=" + ppa.mComponent);
3110                    ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3111                }
3112                final ActivityInfo ai = getActivityInfo(ppa.mComponent,
3113                        flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3114                if (DEBUG_PREFERRED || debug) {
3115                    Slog.v(TAG, "Found persistent preferred activity:");
3116                    if (ai != null) {
3117                        ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3118                    } else {
3119                        Slog.v(TAG, "  null");
3120                    }
3121                }
3122                if (ai == null) {
3123                    // This previously registered persistent preferred activity
3124                    // component is no longer known. Ignore it and do NOT remove it.
3125                    continue;
3126                }
3127                for (int j=0; j<N; j++) {
3128                    final ResolveInfo ri = query.get(j);
3129                    if (!ri.activityInfo.applicationInfo.packageName
3130                            .equals(ai.applicationInfo.packageName)) {
3131                        continue;
3132                    }
3133                    if (!ri.activityInfo.name.equals(ai.name)) {
3134                        continue;
3135                    }
3136                    //  Found a persistent preference that can handle the intent.
3137                    if (DEBUG_PREFERRED || debug) {
3138                        Slog.v(TAG, "Returning persistent preferred activity: " +
3139                                ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3140                    }
3141                    return ri;
3142                }
3143            }
3144        }
3145        return null;
3146    }
3147
3148    ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags,
3149            List<ResolveInfo> query, int priority, boolean always,
3150            boolean removeMatches, boolean debug, int userId) {
3151        if (!sUserManager.exists(userId)) return null;
3152        // writer
3153        synchronized (mPackages) {
3154            if (intent.getSelector() != null) {
3155                intent = intent.getSelector();
3156            }
3157            if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION);
3158
3159            // Try to find a matching persistent preferred activity.
3160            ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query,
3161                    debug, userId);
3162
3163            // If a persistent preferred activity matched, use it.
3164            if (pri != null) {
3165                return pri;
3166            }
3167
3168            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
3169            // Get the list of preferred activities that handle the intent
3170            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities...");
3171            List<PreferredActivity> prefs = pir != null
3172                    ? pir.queryIntent(intent, resolvedType,
3173                            (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId)
3174                    : null;
3175            if (prefs != null && prefs.size() > 0) {
3176                boolean changed = false;
3177                try {
3178                    // First figure out how good the original match set is.
3179                    // We will only allow preferred activities that came
3180                    // from the same match quality.
3181                    int match = 0;
3182
3183                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match...");
3184
3185                    final int N = query.size();
3186                    for (int j=0; j<N; j++) {
3187                        final ResolveInfo ri = query.get(j);
3188                        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo
3189                                + ": 0x" + Integer.toHexString(match));
3190                        if (ri.match > match) {
3191                            match = ri.match;
3192                        }
3193                    }
3194
3195                    if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x"
3196                            + Integer.toHexString(match));
3197
3198                    match &= IntentFilter.MATCH_CATEGORY_MASK;
3199                    final int M = prefs.size();
3200                    for (int i=0; i<M; i++) {
3201                        final PreferredActivity pa = prefs.get(i);
3202                        if (DEBUG_PREFERRED || debug) {
3203                            Slog.v(TAG, "Checking PreferredActivity ds="
3204                                    + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>")
3205                                    + "\n  component=" + pa.mPref.mComponent);
3206                            pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3207                        }
3208                        if (pa.mPref.mMatch != match) {
3209                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match "
3210                                    + Integer.toHexString(pa.mPref.mMatch));
3211                            continue;
3212                        }
3213                        // If it's not an "always" type preferred activity and that's what we're
3214                        // looking for, skip it.
3215                        if (always && !pa.mPref.mAlways) {
3216                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry");
3217                            continue;
3218                        }
3219                        final ActivityInfo ai = getActivityInfo(pa.mPref.mComponent,
3220                                flags | PackageManager.GET_DISABLED_COMPONENTS, userId);
3221                        if (DEBUG_PREFERRED || debug) {
3222                            Slog.v(TAG, "Found preferred activity:");
3223                            if (ai != null) {
3224                                ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), "  ");
3225                            } else {
3226                                Slog.v(TAG, "  null");
3227                            }
3228                        }
3229                        if (ai == null) {
3230                            // This previously registered preferred activity
3231                            // component is no longer known.  Most likely an update
3232                            // to the app was installed and in the new version this
3233                            // component no longer exists.  Clean it up by removing
3234                            // it from the preferred activities list, and skip it.
3235                            Slog.w(TAG, "Removing dangling preferred activity: "
3236                                    + pa.mPref.mComponent);
3237                            pir.removeFilter(pa);
3238                            changed = true;
3239                            continue;
3240                        }
3241                        for (int j=0; j<N; j++) {
3242                            final ResolveInfo ri = query.get(j);
3243                            if (!ri.activityInfo.applicationInfo.packageName
3244                                    .equals(ai.applicationInfo.packageName)) {
3245                                continue;
3246                            }
3247                            if (!ri.activityInfo.name.equals(ai.name)) {
3248                                continue;
3249                            }
3250
3251                            if (removeMatches) {
3252                                pir.removeFilter(pa);
3253                                changed = true;
3254                                if (DEBUG_PREFERRED) {
3255                                    Slog.v(TAG, "Removing match " + pa.mPref.mComponent);
3256                                }
3257                                break;
3258                            }
3259
3260                            // Okay we found a previously set preferred or last chosen app.
3261                            // If the result set is different from when this
3262                            // was created, we need to clear it and re-ask the
3263                            // user their preference, if we're looking for an "always" type entry.
3264                            if (always && !pa.mPref.sameSet(query, priority)) {
3265                                Slog.i(TAG, "Result set changed, dropping preferred activity for "
3266                                        + intent + " type " + resolvedType);
3267                                if (DEBUG_PREFERRED) {
3268                                    Slog.v(TAG, "Removing preferred activity since set changed "
3269                                            + pa.mPref.mComponent);
3270                                }
3271                                pir.removeFilter(pa);
3272                                // Re-add the filter as a "last chosen" entry (!always)
3273                                PreferredActivity lastChosen = new PreferredActivity(
3274                                        pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false);
3275                                pir.addFilter(lastChosen);
3276                                changed = true;
3277                                return null;
3278                            }
3279
3280                            // Yay! Either the set matched or we're looking for the last chosen
3281                            if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: "
3282                                    + ri.activityInfo.packageName + "/" + ri.activityInfo.name);
3283                            return ri;
3284                        }
3285                    }
3286                } finally {
3287                    if (changed) {
3288                        if (DEBUG_PREFERRED) {
3289                            Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions");
3290                        }
3291                        mSettings.writePackageRestrictionsLPr(userId);
3292                    }
3293                }
3294            }
3295        }
3296        if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return");
3297        return null;
3298    }
3299
3300    /*
3301     * Returns if intent can be forwarded from the sourceUserId to the targetUserId
3302     */
3303    @Override
3304    public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId,
3305            int targetUserId) {
3306        mContext.enforceCallingOrSelfPermission(
3307                android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
3308        List<CrossProfileIntentFilter> matches =
3309                getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId);
3310        if (matches != null) {
3311            int size = matches.size();
3312            for (int i = 0; i < size; i++) {
3313                if (matches.get(i).getTargetUserId() == targetUserId) return true;
3314            }
3315        }
3316        return false;
3317    }
3318
3319    private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent,
3320            String resolvedType, int userId) {
3321        CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId);
3322        if (resolver != null) {
3323            return resolver.queryIntent(intent, resolvedType, false, userId);
3324        }
3325        return null;
3326    }
3327
3328    @Override
3329    public List<ResolveInfo> queryIntentActivities(Intent intent,
3330            String resolvedType, int flags, int userId) {
3331        if (!sUserManager.exists(userId)) return Collections.emptyList();
3332        enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, "query intent activities");
3333        ComponentName comp = intent.getComponent();
3334        if (comp == null) {
3335            if (intent.getSelector() != null) {
3336                intent = intent.getSelector();
3337                comp = intent.getComponent();
3338            }
3339        }
3340
3341        if (comp != null) {
3342            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3343            final ActivityInfo ai = getActivityInfo(comp, flags, userId);
3344            if (ai != null) {
3345                final ResolveInfo ri = new ResolveInfo();
3346                ri.activityInfo = ai;
3347                list.add(ri);
3348            }
3349            return list;
3350        }
3351
3352        // reader
3353        synchronized (mPackages) {
3354            final String pkgName = intent.getPackage();
3355            if (pkgName == null) {
3356                List<CrossProfileIntentFilter> matchingFilters =
3357                        getMatchingCrossProfileIntentFilters(intent, resolvedType, userId);
3358                // Check for results that need to skip the current profile.
3359                ResolveInfo resolveInfo  = querySkipCurrentProfileIntents(matchingFilters, intent,
3360                        resolvedType, flags, userId);
3361                if (resolveInfo != null) {
3362                    List<ResolveInfo> result = new ArrayList<ResolveInfo>(1);
3363                    result.add(resolveInfo);
3364                    return result;
3365                }
3366                // Check for cross profile results.
3367                resolveInfo = queryCrossProfileIntents(
3368                        matchingFilters, intent, resolvedType, flags, userId);
3369
3370                // Check for results in the current profile.
3371                List<ResolveInfo> result = mActivities.queryIntent(
3372                        intent, resolvedType, flags, userId);
3373                if (resolveInfo != null) {
3374                    result.add(resolveInfo);
3375                    Collections.sort(result, mResolvePrioritySorter);
3376                }
3377                return result;
3378            }
3379            final PackageParser.Package pkg = mPackages.get(pkgName);
3380            if (pkg != null) {
3381                return mActivities.queryIntentForPackage(intent, resolvedType, flags,
3382                        pkg.activities, userId);
3383            }
3384            return new ArrayList<ResolveInfo>();
3385        }
3386    }
3387
3388    private ResolveInfo querySkipCurrentProfileIntents(
3389            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3390            int flags, int sourceUserId) {
3391        if (matchingFilters != null) {
3392            int size = matchingFilters.size();
3393            for (int i = 0; i < size; i ++) {
3394                CrossProfileIntentFilter filter = matchingFilters.get(i);
3395                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) {
3396                    // Checking if there are activities in the target user that can handle the
3397                    // intent.
3398                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3399                            flags, sourceUserId);
3400                    if (resolveInfo != null) {
3401                        return resolveInfo;
3402                    }
3403                }
3404            }
3405        }
3406        return null;
3407    }
3408
3409    // Return matching ResolveInfo if any for skip current profile intent filters.
3410    private ResolveInfo queryCrossProfileIntents(
3411            List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType,
3412            int flags, int sourceUserId) {
3413        if (matchingFilters != null) {
3414            // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and
3415            // match the same intent. For performance reasons, it is better not to
3416            // run queryIntent twice for the same userId
3417            SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray();
3418            int size = matchingFilters.size();
3419            for (int i = 0; i < size; i++) {
3420                CrossProfileIntentFilter filter = matchingFilters.get(i);
3421                int targetUserId = filter.getTargetUserId();
3422                if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) == 0
3423                        && !alreadyTriedUserIds.get(targetUserId)) {
3424                    // Checking if there are activities in the target user that can handle the
3425                    // intent.
3426                    ResolveInfo resolveInfo = checkTargetCanHandle(filter, intent, resolvedType,
3427                            flags, sourceUserId);
3428                    if (resolveInfo != null) return resolveInfo;
3429                    alreadyTriedUserIds.put(targetUserId, true);
3430                }
3431            }
3432        }
3433        return null;
3434    }
3435
3436    private ResolveInfo checkTargetCanHandle(CrossProfileIntentFilter filter, Intent intent,
3437            String resolvedType, int flags, int sourceUserId) {
3438        List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent,
3439                resolvedType, flags, filter.getTargetUserId());
3440        if (resultTargetUser != null && !resultTargetUser.isEmpty()) {
3441            return createForwardingResolveInfo(filter, sourceUserId, filter.getTargetUserId());
3442        }
3443        return null;
3444    }
3445
3446    private ResolveInfo createForwardingResolveInfo(IntentFilter filter,
3447            int sourceUserId, int targetUserId) {
3448        ResolveInfo forwardingResolveInfo = new ResolveInfo();
3449        String className;
3450        if (targetUserId == UserHandle.USER_OWNER) {
3451            className = FORWARD_INTENT_TO_USER_OWNER;
3452        } else {
3453            className = FORWARD_INTENT_TO_MANAGED_PROFILE;
3454        }
3455        ComponentName forwardingActivityComponentName = new ComponentName(
3456                mAndroidApplication.packageName, className);
3457        ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0,
3458                sourceUserId);
3459        if (targetUserId == UserHandle.USER_OWNER) {
3460            forwardingActivityInfo.showUserIcon = UserHandle.USER_OWNER;
3461            forwardingResolveInfo.noResourceId = true;
3462        }
3463        forwardingResolveInfo.activityInfo = forwardingActivityInfo;
3464        forwardingResolveInfo.priority = 0;
3465        forwardingResolveInfo.preferredOrder = 0;
3466        forwardingResolveInfo.match = 0;
3467        forwardingResolveInfo.isDefault = true;
3468        forwardingResolveInfo.filter = filter;
3469        forwardingResolveInfo.targetUserId = targetUserId;
3470        return forwardingResolveInfo;
3471    }
3472
3473    @Override
3474    public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
3475            Intent[] specifics, String[] specificTypes, Intent intent,
3476            String resolvedType, int flags, int userId) {
3477        if (!sUserManager.exists(userId)) return Collections.emptyList();
3478        enforceCrossUserPermission(Binder.getCallingUid(), userId, false,
3479                false, "query intent activity options");
3480        final String resultsAction = intent.getAction();
3481
3482        List<ResolveInfo> results = queryIntentActivities(intent, resolvedType, flags
3483                | PackageManager.GET_RESOLVED_FILTER, userId);
3484
3485        if (DEBUG_INTENT_MATCHING) {
3486            Log.v(TAG, "Query " + intent + ": " + results);
3487        }
3488
3489        int specificsPos = 0;
3490        int N;
3491
3492        // todo: note that the algorithm used here is O(N^2).  This
3493        // isn't a problem in our current environment, but if we start running
3494        // into situations where we have more than 5 or 10 matches then this
3495        // should probably be changed to something smarter...
3496
3497        // First we go through and resolve each of the specific items
3498        // that were supplied, taking care of removing any corresponding
3499        // duplicate items in the generic resolve list.
3500        if (specifics != null) {
3501            for (int i=0; i<specifics.length; i++) {
3502                final Intent sintent = specifics[i];
3503                if (sintent == null) {
3504                    continue;
3505                }
3506
3507                if (DEBUG_INTENT_MATCHING) {
3508                    Log.v(TAG, "Specific #" + i + ": " + sintent);
3509                }
3510
3511                String action = sintent.getAction();
3512                if (resultsAction != null && resultsAction.equals(action)) {
3513                    // If this action was explicitly requested, then don't
3514                    // remove things that have it.
3515                    action = null;
3516                }
3517
3518                ResolveInfo ri = null;
3519                ActivityInfo ai = null;
3520
3521                ComponentName comp = sintent.getComponent();
3522                if (comp == null) {
3523                    ri = resolveIntent(
3524                        sintent,
3525                        specificTypes != null ? specificTypes[i] : null,
3526                            flags, userId);
3527                    if (ri == null) {
3528                        continue;
3529                    }
3530                    if (ri == mResolveInfo) {
3531                        // ACK!  Must do something better with this.
3532                    }
3533                    ai = ri.activityInfo;
3534                    comp = new ComponentName(ai.applicationInfo.packageName,
3535                            ai.name);
3536                } else {
3537                    ai = getActivityInfo(comp, flags, userId);
3538                    if (ai == null) {
3539                        continue;
3540                    }
3541                }
3542
3543                // Look for any generic query activities that are duplicates
3544                // of this specific one, and remove them from the results.
3545                if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai);
3546                N = results.size();
3547                int j;
3548                for (j=specificsPos; j<N; j++) {
3549                    ResolveInfo sri = results.get(j);
3550                    if ((sri.activityInfo.name.equals(comp.getClassName())
3551                            && sri.activityInfo.applicationInfo.packageName.equals(
3552                                    comp.getPackageName()))
3553                        || (action != null && sri.filter.matchAction(action))) {
3554                        results.remove(j);
3555                        if (DEBUG_INTENT_MATCHING) Log.v(
3556                            TAG, "Removing duplicate item from " + j
3557                            + " due to specific " + specificsPos);
3558                        if (ri == null) {
3559                            ri = sri;
3560                        }
3561                        j--;
3562                        N--;
3563                    }
3564                }
3565
3566                // Add this specific item to its proper place.
3567                if (ri == null) {
3568                    ri = new ResolveInfo();
3569                    ri.activityInfo = ai;
3570                }
3571                results.add(specificsPos, ri);
3572                ri.specificIndex = i;
3573                specificsPos++;
3574            }
3575        }
3576
3577        // Now we go through the remaining generic results and remove any
3578        // duplicate actions that are found here.
3579        N = results.size();
3580        for (int i=specificsPos; i<N-1; i++) {
3581            final ResolveInfo rii = results.get(i);
3582            if (rii.filter == null) {
3583                continue;
3584            }
3585
3586            // Iterate over all of the actions of this result's intent
3587            // filter...  typically this should be just one.
3588            final Iterator<String> it = rii.filter.actionsIterator();
3589            if (it == null) {
3590                continue;
3591            }
3592            while (it.hasNext()) {
3593                final String action = it.next();
3594                if (resultsAction != null && resultsAction.equals(action)) {
3595                    // If this action was explicitly requested, then don't
3596                    // remove things that have it.
3597                    continue;
3598                }
3599                for (int j=i+1; j<N; j++) {
3600                    final ResolveInfo rij = results.get(j);
3601                    if (rij.filter != null && rij.filter.hasAction(action)) {
3602                        results.remove(j);
3603                        if (DEBUG_INTENT_MATCHING) Log.v(
3604                            TAG, "Removing duplicate item from " + j
3605                            + " due to action " + action + " at " + i);
3606                        j--;
3607                        N--;
3608                    }
3609                }
3610            }
3611
3612            // If the caller didn't request filter information, drop it now
3613            // so we don't have to marshall/unmarshall it.
3614            if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3615                rii.filter = null;
3616            }
3617        }
3618
3619        // Filter out the caller activity if so requested.
3620        if (caller != null) {
3621            N = results.size();
3622            for (int i=0; i<N; i++) {
3623                ActivityInfo ainfo = results.get(i).activityInfo;
3624                if (caller.getPackageName().equals(ainfo.applicationInfo.packageName)
3625                        && caller.getClassName().equals(ainfo.name)) {
3626                    results.remove(i);
3627                    break;
3628                }
3629            }
3630        }
3631
3632        // If the caller didn't request filter information,
3633        // drop them now so we don't have to
3634        // marshall/unmarshall it.
3635        if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) {
3636            N = results.size();
3637            for (int i=0; i<N; i++) {
3638                results.get(i).filter = null;
3639            }
3640        }
3641
3642        if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results);
3643        return results;
3644    }
3645
3646    @Override
3647    public List<ResolveInfo> queryIntentReceivers(Intent intent, String resolvedType, int flags,
3648            int userId) {
3649        if (!sUserManager.exists(userId)) return Collections.emptyList();
3650        ComponentName comp = intent.getComponent();
3651        if (comp == null) {
3652            if (intent.getSelector() != null) {
3653                intent = intent.getSelector();
3654                comp = intent.getComponent();
3655            }
3656        }
3657        if (comp != null) {
3658            List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3659            ActivityInfo ai = getReceiverInfo(comp, flags, userId);
3660            if (ai != null) {
3661                ResolveInfo ri = new ResolveInfo();
3662                ri.activityInfo = ai;
3663                list.add(ri);
3664            }
3665            return list;
3666        }
3667
3668        // reader
3669        synchronized (mPackages) {
3670            String pkgName = intent.getPackage();
3671            if (pkgName == null) {
3672                return mReceivers.queryIntent(intent, resolvedType, flags, userId);
3673            }
3674            final PackageParser.Package pkg = mPackages.get(pkgName);
3675            if (pkg != null) {
3676                return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers,
3677                        userId);
3678            }
3679            return null;
3680        }
3681    }
3682
3683    @Override
3684    public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) {
3685        List<ResolveInfo> query = queryIntentServices(intent, resolvedType, flags, userId);
3686        if (!sUserManager.exists(userId)) return null;
3687        if (query != null) {
3688            if (query.size() >= 1) {
3689                // If there is more than one service with the same priority,
3690                // just arbitrarily pick the first one.
3691                return query.get(0);
3692            }
3693        }
3694        return null;
3695    }
3696
3697    @Override
3698    public List<ResolveInfo> queryIntentServices(Intent intent, String resolvedType, int flags,
3699            int userId) {
3700        if (!sUserManager.exists(userId)) return Collections.emptyList();
3701        ComponentName comp = intent.getComponent();
3702        if (comp == null) {
3703            if (intent.getSelector() != null) {
3704                intent = intent.getSelector();
3705                comp = intent.getComponent();
3706            }
3707        }
3708        if (comp != null) {
3709            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3710            final ServiceInfo si = getServiceInfo(comp, flags, userId);
3711            if (si != null) {
3712                final ResolveInfo ri = new ResolveInfo();
3713                ri.serviceInfo = si;
3714                list.add(ri);
3715            }
3716            return list;
3717        }
3718
3719        // reader
3720        synchronized (mPackages) {
3721            String pkgName = intent.getPackage();
3722            if (pkgName == null) {
3723                return mServices.queryIntent(intent, resolvedType, flags, userId);
3724            }
3725            final PackageParser.Package pkg = mPackages.get(pkgName);
3726            if (pkg != null) {
3727                return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services,
3728                        userId);
3729            }
3730            return null;
3731        }
3732    }
3733
3734    @Override
3735    public List<ResolveInfo> queryIntentContentProviders(
3736            Intent intent, String resolvedType, int flags, int userId) {
3737        if (!sUserManager.exists(userId)) return Collections.emptyList();
3738        ComponentName comp = intent.getComponent();
3739        if (comp == null) {
3740            if (intent.getSelector() != null) {
3741                intent = intent.getSelector();
3742                comp = intent.getComponent();
3743            }
3744        }
3745        if (comp != null) {
3746            final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1);
3747            final ProviderInfo pi = getProviderInfo(comp, flags, userId);
3748            if (pi != null) {
3749                final ResolveInfo ri = new ResolveInfo();
3750                ri.providerInfo = pi;
3751                list.add(ri);
3752            }
3753            return list;
3754        }
3755
3756        // reader
3757        synchronized (mPackages) {
3758            String pkgName = intent.getPackage();
3759            if (pkgName == null) {
3760                return mProviders.queryIntent(intent, resolvedType, flags, userId);
3761            }
3762            final PackageParser.Package pkg = mPackages.get(pkgName);
3763            if (pkg != null) {
3764                return mProviders.queryIntentForPackage(
3765                        intent, resolvedType, flags, pkg.providers, userId);
3766            }
3767            return null;
3768        }
3769    }
3770
3771    @Override
3772    public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) {
3773        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3774
3775        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "get installed packages");
3776
3777        // writer
3778        synchronized (mPackages) {
3779            ArrayList<PackageInfo> list;
3780            if (listUninstalled) {
3781                list = new ArrayList<PackageInfo>(mSettings.mPackages.size());
3782                for (PackageSetting ps : mSettings.mPackages.values()) {
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                    if (pi != null) {
3790                        list.add(pi);
3791                    }
3792                }
3793            } else {
3794                list = new ArrayList<PackageInfo>(mPackages.size());
3795                for (PackageParser.Package p : mPackages.values()) {
3796                    PackageInfo pi = generatePackageInfo(p, flags, userId);
3797                    if (pi != null) {
3798                        list.add(pi);
3799                    }
3800                }
3801            }
3802
3803            return new ParceledListSlice<PackageInfo>(list);
3804        }
3805    }
3806
3807    private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps,
3808            String[] permissions, boolean[] tmp, int flags, int userId) {
3809        int numMatch = 0;
3810        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
3811        for (int i=0; i<permissions.length; i++) {
3812            if (gp.grantedPermissions.contains(permissions[i])) {
3813                tmp[i] = true;
3814                numMatch++;
3815            } else {
3816                tmp[i] = false;
3817            }
3818        }
3819        if (numMatch == 0) {
3820            return;
3821        }
3822        PackageInfo pi;
3823        if (ps.pkg != null) {
3824            pi = generatePackageInfo(ps.pkg, flags, userId);
3825        } else {
3826            pi = generatePackageInfoFromSettingsLPw(ps.name, flags, userId);
3827        }
3828        // The above might return null in cases of uninstalled apps or install-state
3829        // skew across users/profiles.
3830        if (pi != null) {
3831            if ((flags&PackageManager.GET_PERMISSIONS) == 0) {
3832                if (numMatch == permissions.length) {
3833                    pi.requestedPermissions = permissions;
3834                } else {
3835                    pi.requestedPermissions = new String[numMatch];
3836                    numMatch = 0;
3837                    for (int i=0; i<permissions.length; i++) {
3838                        if (tmp[i]) {
3839                            pi.requestedPermissions[numMatch] = permissions[i];
3840                            numMatch++;
3841                        }
3842                    }
3843                }
3844            }
3845            list.add(pi);
3846        }
3847    }
3848
3849    @Override
3850    public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions(
3851            String[] permissions, int flags, int userId) {
3852        if (!sUserManager.exists(userId)) return null;
3853        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3854
3855        // writer
3856        synchronized (mPackages) {
3857            ArrayList<PackageInfo> list = new ArrayList<PackageInfo>();
3858            boolean[] tmpBools = new boolean[permissions.length];
3859            if (listUninstalled) {
3860                for (PackageSetting ps : mSettings.mPackages.values()) {
3861                    addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId);
3862                }
3863            } else {
3864                for (PackageParser.Package pkg : mPackages.values()) {
3865                    PackageSetting ps = (PackageSetting)pkg.mExtras;
3866                    if (ps != null) {
3867                        addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags,
3868                                userId);
3869                    }
3870                }
3871            }
3872
3873            return new ParceledListSlice<PackageInfo>(list);
3874        }
3875    }
3876
3877    @Override
3878    public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) {
3879        if (!sUserManager.exists(userId)) return null;
3880        final boolean listUninstalled = (flags & PackageManager.GET_UNINSTALLED_PACKAGES) != 0;
3881
3882        // writer
3883        synchronized (mPackages) {
3884            ArrayList<ApplicationInfo> list;
3885            if (listUninstalled) {
3886                list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size());
3887                for (PackageSetting ps : mSettings.mPackages.values()) {
3888                    ApplicationInfo ai;
3889                    if (ps.pkg != null) {
3890                        ai = PackageParser.generateApplicationInfo(ps.pkg, flags,
3891                                ps.readUserState(userId), userId);
3892                    } else {
3893                        ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId);
3894                    }
3895                    if (ai != null) {
3896                        list.add(ai);
3897                    }
3898                }
3899            } else {
3900                list = new ArrayList<ApplicationInfo>(mPackages.size());
3901                for (PackageParser.Package p : mPackages.values()) {
3902                    if (p.mExtras != null) {
3903                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3904                                ((PackageSetting)p.mExtras).readUserState(userId), userId);
3905                        if (ai != null) {
3906                            list.add(ai);
3907                        }
3908                    }
3909                }
3910            }
3911
3912            return new ParceledListSlice<ApplicationInfo>(list);
3913        }
3914    }
3915
3916    public List<ApplicationInfo> getPersistentApplications(int flags) {
3917        final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>();
3918
3919        // reader
3920        synchronized (mPackages) {
3921            final Iterator<PackageParser.Package> i = mPackages.values().iterator();
3922            final int userId = UserHandle.getCallingUserId();
3923            while (i.hasNext()) {
3924                final PackageParser.Package p = i.next();
3925                if (p.applicationInfo != null
3926                        && (p.applicationInfo.flags&ApplicationInfo.FLAG_PERSISTENT) != 0
3927                        && (!mSafeMode || isSystemApp(p))) {
3928                    PackageSetting ps = mSettings.mPackages.get(p.packageName);
3929                    if (ps != null) {
3930                        ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags,
3931                                ps.readUserState(userId), userId);
3932                        if (ai != null) {
3933                            finalList.add(ai);
3934                        }
3935                    }
3936                }
3937            }
3938        }
3939
3940        return finalList;
3941    }
3942
3943    @Override
3944    public ProviderInfo resolveContentProvider(String name, int flags, int userId) {
3945        if (!sUserManager.exists(userId)) return null;
3946        // reader
3947        synchronized (mPackages) {
3948            final PackageParser.Provider provider = mProvidersByAuthority.get(name);
3949            PackageSetting ps = provider != null
3950                    ? mSettings.mPackages.get(provider.owner.packageName)
3951                    : null;
3952            return ps != null
3953                    && mSettings.isEnabledLPr(provider.info, flags, userId)
3954                    && (!mSafeMode || (provider.info.applicationInfo.flags
3955                            &ApplicationInfo.FLAG_SYSTEM) != 0)
3956                    ? PackageParser.generateProviderInfo(provider, flags,
3957                            ps.readUserState(userId), userId)
3958                    : null;
3959        }
3960    }
3961
3962    /**
3963     * @deprecated
3964     */
3965    @Deprecated
3966    public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) {
3967        // reader
3968        synchronized (mPackages) {
3969            final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority
3970                    .entrySet().iterator();
3971            final int userId = UserHandle.getCallingUserId();
3972            while (i.hasNext()) {
3973                Map.Entry<String, PackageParser.Provider> entry = i.next();
3974                PackageParser.Provider p = entry.getValue();
3975                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
3976
3977                if (ps != null && p.syncable
3978                        && (!mSafeMode || (p.info.applicationInfo.flags
3979                                &ApplicationInfo.FLAG_SYSTEM) != 0)) {
3980                    ProviderInfo info = PackageParser.generateProviderInfo(p, 0,
3981                            ps.readUserState(userId), userId);
3982                    if (info != null) {
3983                        outNames.add(entry.getKey());
3984                        outInfo.add(info);
3985                    }
3986                }
3987            }
3988        }
3989    }
3990
3991    @Override
3992    public List<ProviderInfo> queryContentProviders(String processName,
3993            int uid, int flags) {
3994        ArrayList<ProviderInfo> finalList = null;
3995        // reader
3996        synchronized (mPackages) {
3997            final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator();
3998            final int userId = processName != null ?
3999                    UserHandle.getUserId(uid) : UserHandle.getCallingUserId();
4000            while (i.hasNext()) {
4001                final PackageParser.Provider p = i.next();
4002                PackageSetting ps = mSettings.mPackages.get(p.owner.packageName);
4003                if (ps != null && p.info.authority != null
4004                        && (processName == null
4005                                || (p.info.processName.equals(processName)
4006                                        && UserHandle.isSameApp(p.info.applicationInfo.uid, uid)))
4007                        && mSettings.isEnabledLPr(p.info, flags, userId)
4008                        && (!mSafeMode
4009                                || (p.info.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0)) {
4010                    if (finalList == null) {
4011                        finalList = new ArrayList<ProviderInfo>(3);
4012                    }
4013                    ProviderInfo info = PackageParser.generateProviderInfo(p, flags,
4014                            ps.readUserState(userId), userId);
4015                    if (info != null) {
4016                        finalList.add(info);
4017                    }
4018                }
4019            }
4020        }
4021
4022        if (finalList != null) {
4023            Collections.sort(finalList, mProviderInitOrderSorter);
4024        }
4025
4026        return finalList;
4027    }
4028
4029    @Override
4030    public InstrumentationInfo getInstrumentationInfo(ComponentName name,
4031            int flags) {
4032        // reader
4033        synchronized (mPackages) {
4034            final PackageParser.Instrumentation i = mInstrumentation.get(name);
4035            return PackageParser.generateInstrumentationInfo(i, flags);
4036        }
4037    }
4038
4039    @Override
4040    public List<InstrumentationInfo> queryInstrumentation(String targetPackage,
4041            int flags) {
4042        ArrayList<InstrumentationInfo> finalList =
4043            new ArrayList<InstrumentationInfo>();
4044
4045        // reader
4046        synchronized (mPackages) {
4047            final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator();
4048            while (i.hasNext()) {
4049                final PackageParser.Instrumentation p = i.next();
4050                if (targetPackage == null
4051                        || targetPackage.equals(p.info.targetPackage)) {
4052                    InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p,
4053                            flags);
4054                    if (ii != null) {
4055                        finalList.add(ii);
4056                    }
4057                }
4058            }
4059        }
4060
4061        return finalList;
4062    }
4063
4064    private void createIdmapsForPackageLI(PackageParser.Package pkg) {
4065        HashMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName);
4066        if (overlays == null) {
4067            Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages");
4068            return;
4069        }
4070        for (PackageParser.Package opkg : overlays.values()) {
4071            // Not much to do if idmap fails: we already logged the error
4072            // and we certainly don't want to abort installation of pkg simply
4073            // because an overlay didn't fit properly. For these reasons,
4074            // ignore the return value of createIdmapForPackagePairLI.
4075            createIdmapForPackagePairLI(pkg, opkg);
4076        }
4077    }
4078
4079    private boolean createIdmapForPackagePairLI(PackageParser.Package pkg,
4080            PackageParser.Package opkg) {
4081        if (!opkg.mTrustedOverlay) {
4082            Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " +
4083                    opkg.baseCodePath + ": overlay not trusted");
4084            return false;
4085        }
4086        HashMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName);
4087        if (overlaySet == null) {
4088            Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " +
4089                    opkg.baseCodePath + " but target package has no known overlays");
4090            return false;
4091        }
4092        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4093        // TODO: generate idmap for split APKs
4094        if (mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid) != 0) {
4095            Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and "
4096                    + opkg.baseCodePath);
4097            return false;
4098        }
4099        PackageParser.Package[] overlayArray =
4100            overlaySet.values().toArray(new PackageParser.Package[0]);
4101        Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() {
4102            public int compare(PackageParser.Package p1, PackageParser.Package p2) {
4103                return p1.mOverlayPriority - p2.mOverlayPriority;
4104            }
4105        };
4106        Arrays.sort(overlayArray, cmp);
4107
4108        pkg.applicationInfo.resourceDirs = new String[overlayArray.length];
4109        int i = 0;
4110        for (PackageParser.Package p : overlayArray) {
4111            pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath;
4112        }
4113        return true;
4114    }
4115
4116    private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) {
4117        final File[] files = dir.listFiles();
4118        if (ArrayUtils.isEmpty(files)) {
4119            Log.d(TAG, "No files in app dir " + dir);
4120            return;
4121        }
4122
4123        if (DEBUG_PACKAGE_SCANNING) {
4124            Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags
4125                    + " flags=0x" + Integer.toHexString(parseFlags));
4126        }
4127
4128        for (File file : files) {
4129            final boolean isPackage = (isApkFile(file) || file.isDirectory())
4130                    && !PackageInstallerService.isStageName(file.getName());
4131            if (!isPackage) {
4132                // Ignore entries which are not packages
4133                continue;
4134            }
4135            try {
4136                scanPackageLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK,
4137                        scanFlags, currentTime, null);
4138            } catch (PackageManagerException e) {
4139                Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage());
4140
4141                // Delete invalid userdata apps
4142                if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 &&
4143                        e.error == PackageManager.INSTALL_FAILED_INVALID_APK) {
4144                    logCriticalInfo(Log.WARN, "Deleting invalid package at " + file);
4145                    if (file.isDirectory()) {
4146                        FileUtils.deleteContents(file);
4147                    }
4148                    file.delete();
4149                }
4150            }
4151        }
4152    }
4153
4154    private static File getSettingsProblemFile() {
4155        File dataDir = Environment.getDataDirectory();
4156        File systemDir = new File(dataDir, "system");
4157        File fname = new File(systemDir, "uiderrors.txt");
4158        return fname;
4159    }
4160
4161    static void reportSettingsProblem(int priority, String msg) {
4162        logCriticalInfo(priority, msg);
4163    }
4164
4165    static void logCriticalInfo(int priority, String msg) {
4166        Slog.println(priority, TAG, msg);
4167        EventLogTags.writePmCriticalInfo(msg);
4168        try {
4169            File fname = getSettingsProblemFile();
4170            FileOutputStream out = new FileOutputStream(fname, true);
4171            PrintWriter pw = new FastPrintWriter(out);
4172            SimpleDateFormat formatter = new SimpleDateFormat();
4173            String dateString = formatter.format(new Date(System.currentTimeMillis()));
4174            pw.println(dateString + ": " + msg);
4175            pw.close();
4176            FileUtils.setPermissions(
4177                    fname.toString(),
4178                    FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH,
4179                    -1, -1);
4180        } catch (java.io.IOException e) {
4181        }
4182    }
4183
4184    private void collectCertificatesLI(PackageParser pp, PackageSetting ps,
4185            PackageParser.Package pkg, File srcFile, int parseFlags)
4186            throws PackageManagerException {
4187        if (ps != null
4188                && ps.codePath.equals(srcFile)
4189                && ps.timeStamp == srcFile.lastModified()
4190                && !isCompatSignatureUpdateNeeded(pkg)
4191                && !isRecoverSignatureUpdateNeeded(pkg)) {
4192            long mSigningKeySetId = ps.keySetData.getProperSigningKeySet();
4193            if (ps.signatures.mSignatures != null
4194                    && ps.signatures.mSignatures.length != 0
4195                    && mSigningKeySetId != PackageKeySetData.KEYSET_UNASSIGNED) {
4196                // Optimization: reuse the existing cached certificates
4197                // if the package appears to be unchanged.
4198                pkg.mSignatures = ps.signatures.mSignatures;
4199                KeySetManagerService ksms = mSettings.mKeySetManagerService;
4200                synchronized (mPackages) {
4201                    pkg.mSigningKeys = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId);
4202                }
4203                return;
4204            }
4205
4206            Slog.w(TAG, "PackageSetting for " + ps.name
4207                    + " is missing signatures.  Collecting certs again to recover them.");
4208        } else {
4209            Log.i(TAG, srcFile.toString() + " changed; collecting certs");
4210        }
4211
4212        try {
4213            pp.collectCertificates(pkg, parseFlags);
4214            pp.collectManifestDigest(pkg);
4215        } catch (PackageParserException e) {
4216            throw PackageManagerException.from(e);
4217        }
4218    }
4219
4220    /*
4221     *  Scan a package and return the newly parsed package.
4222     *  Returns null in case of errors and the error code is stored in mLastScanError
4223     */
4224    private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags,
4225            long currentTime, UserHandle user) throws PackageManagerException {
4226        if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile);
4227        parseFlags |= mDefParseFlags;
4228        PackageParser pp = new PackageParser();
4229        pp.setSeparateProcesses(mSeparateProcesses);
4230        pp.setOnlyCoreApps(mOnlyCore);
4231        pp.setDisplayMetrics(mMetrics);
4232
4233        if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) {
4234            parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY;
4235        }
4236
4237        final PackageParser.Package pkg;
4238        try {
4239            pkg = pp.parsePackage(scanFile, parseFlags);
4240        } catch (PackageParserException e) {
4241            throw PackageManagerException.from(e);
4242        }
4243
4244        PackageSetting ps = null;
4245        PackageSetting updatedPkg;
4246        // reader
4247        synchronized (mPackages) {
4248            // Look to see if we already know about this package.
4249            String oldName = mSettings.mRenamedPackages.get(pkg.packageName);
4250            if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) {
4251                // This package has been renamed to its original name.  Let's
4252                // use that.
4253                ps = mSettings.peekPackageLPr(oldName);
4254            }
4255            // If there was no original package, see one for the real package name.
4256            if (ps == null) {
4257                ps = mSettings.peekPackageLPr(pkg.packageName);
4258            }
4259            // Check to see if this package could be hiding/updating a system
4260            // package.  Must look for it either under the original or real
4261            // package name depending on our state.
4262            updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName);
4263            if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg);
4264        }
4265        boolean updatedPkgBetter = false;
4266        // First check if this is a system package that may involve an update
4267        if (updatedPkg != null && (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
4268            if (ps != null && !ps.codePath.equals(scanFile)) {
4269                // The path has changed from what was last scanned...  check the
4270                // version of the new path against what we have stored to determine
4271                // what to do.
4272                if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath);
4273                if (pkg.mVersionCode < ps.versionCode) {
4274                    // The system package has been updated and the code path does not match
4275                    // Ignore entry. Skip it.
4276                    logCriticalInfo(Log.INFO, "Package " + ps.name + " at " + scanFile
4277                            + " ignored: updated version " + ps.versionCode
4278                            + " better than this " + pkg.mVersionCode);
4279                    if (!updatedPkg.codePath.equals(scanFile)) {
4280                        Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg : "
4281                                + ps.name + " changing from " + updatedPkg.codePathString
4282                                + " to " + scanFile);
4283                        updatedPkg.codePath = scanFile;
4284                        updatedPkg.codePathString = scanFile.toString();
4285                        // This is the point at which we know that the system-disk APK
4286                        // for this package has moved during a reboot (e.g. due to an OTA),
4287                        // so we need to reevaluate it for privilege policy.
4288                        if (locationIsPrivileged(scanFile)) {
4289                            updatedPkg.pkgFlags |= ApplicationInfo.FLAG_PRIVILEGED;
4290                        }
4291                    }
4292                    updatedPkg.pkg = pkg;
4293                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, null);
4294                } else {
4295                    // The current app on the system partition is better than
4296                    // what we have updated to on the data partition; switch
4297                    // back to the system partition version.
4298                    // At this point, its safely assumed that package installation for
4299                    // apps in system partition will go through. If not there won't be a working
4300                    // version of the app
4301                    // writer
4302                    synchronized (mPackages) {
4303                        // Just remove the loaded entries from package lists.
4304                        mPackages.remove(ps.name);
4305                    }
4306
4307                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4308                            + " reverting from " + ps.codePathString
4309                            + ": new version " + pkg.mVersionCode
4310                            + " better than installed " + ps.versionCode);
4311
4312                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4313                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4314                            getAppDexInstructionSets(ps));
4315                    synchronized (mInstallLock) {
4316                        args.cleanUpResourcesLI();
4317                    }
4318                    synchronized (mPackages) {
4319                        mSettings.enableSystemPackageLPw(ps.name);
4320                    }
4321                    updatedPkgBetter = true;
4322                }
4323            }
4324        }
4325
4326        if (updatedPkg != null) {
4327            // An updated system app will not have the PARSE_IS_SYSTEM flag set
4328            // initially
4329            parseFlags |= PackageParser.PARSE_IS_SYSTEM;
4330
4331            // An updated privileged app will not have the PARSE_IS_PRIVILEGED
4332            // flag set initially
4333            if ((updatedPkg.pkgFlags & ApplicationInfo.FLAG_PRIVILEGED) != 0) {
4334                parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
4335            }
4336        }
4337
4338        // Verify certificates against what was last scanned
4339        collectCertificatesLI(pp, ps, pkg, scanFile, parseFlags);
4340
4341        /*
4342         * A new system app appeared, but we already had a non-system one of the
4343         * same name installed earlier.
4344         */
4345        boolean shouldHideSystemApp = false;
4346        if (updatedPkg == null && ps != null
4347                && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) {
4348            /*
4349             * Check to make sure the signatures match first. If they don't,
4350             * wipe the installed application and its data.
4351             */
4352            if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures)
4353                    != PackageManager.SIGNATURE_MATCH) {
4354                logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but"
4355                        + " signatures don't match existing userdata copy; removing");
4356                deletePackageLI(pkg.packageName, null, true, null, null, 0, null, false);
4357                ps = null;
4358            } else {
4359                /*
4360                 * If the newly-added system app is an older version than the
4361                 * already installed version, hide it. It will be scanned later
4362                 * and re-added like an update.
4363                 */
4364                if (pkg.mVersionCode < ps.versionCode) {
4365                    shouldHideSystemApp = true;
4366                    logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile
4367                            + " but new version " + pkg.mVersionCode + " better than installed "
4368                            + ps.versionCode + "; hiding system");
4369                } else {
4370                    /*
4371                     * The newly found system app is a newer version that the
4372                     * one previously installed. Simply remove the
4373                     * already-installed application and replace it with our own
4374                     * while keeping the application data.
4375                     */
4376                    logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile
4377                            + " reverting from " + ps.codePathString + ": new version "
4378                            + pkg.mVersionCode + " better than installed " + ps.versionCode);
4379                    InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
4380                            ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
4381                            getAppDexInstructionSets(ps));
4382                    synchronized (mInstallLock) {
4383                        args.cleanUpResourcesLI();
4384                    }
4385                }
4386            }
4387        }
4388
4389        // The apk is forward locked (not public) if its code and resources
4390        // are kept in different files. (except for app in either system or
4391        // vendor path).
4392        // TODO grab this value from PackageSettings
4393        if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
4394            if (ps != null && !ps.codePath.equals(ps.resourcePath)) {
4395                parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
4396            }
4397        }
4398
4399        // TODO: extend to support forward-locked splits
4400        String resourcePath = null;
4401        String baseResourcePath = null;
4402        if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) {
4403            if (ps != null && ps.resourcePathString != null) {
4404                resourcePath = ps.resourcePathString;
4405                baseResourcePath = ps.resourcePathString;
4406            } else {
4407                // Should not happen at all. Just log an error.
4408                Slog.e(TAG, "Resource path not set for pkg : " + pkg.packageName);
4409            }
4410        } else {
4411            resourcePath = pkg.codePath;
4412            baseResourcePath = pkg.baseCodePath;
4413        }
4414
4415        // Set application objects path explicitly.
4416        pkg.applicationInfo.setCodePath(pkg.codePath);
4417        pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
4418        pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
4419        pkg.applicationInfo.setResourcePath(resourcePath);
4420        pkg.applicationInfo.setBaseResourcePath(baseResourcePath);
4421        pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
4422
4423        // Note that we invoke the following method only if we are about to unpack an application
4424        PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags
4425                | SCAN_UPDATE_SIGNATURE, currentTime, user);
4426
4427        /*
4428         * If the system app should be overridden by a previously installed
4429         * data, hide the system app now and let the /data/app scan pick it up
4430         * again.
4431         */
4432        if (shouldHideSystemApp) {
4433            synchronized (mPackages) {
4434                /*
4435                 * We have to grant systems permissions before we hide, because
4436                 * grantPermissions will assume the package update is trying to
4437                 * expand its permissions.
4438                 */
4439                grantPermissionsLPw(pkg, true, pkg.packageName);
4440                mSettings.disableSystemPackageLPw(pkg.packageName);
4441            }
4442        }
4443
4444        return scannedPkg;
4445    }
4446
4447    private static String fixProcessName(String defProcessName,
4448            String processName, int uid) {
4449        if (processName == null) {
4450            return defProcessName;
4451        }
4452        return processName;
4453    }
4454
4455    private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg)
4456            throws PackageManagerException {
4457        if (pkgSetting.signatures.mSignatures != null) {
4458            // Already existing package. Make sure signatures match
4459            boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures)
4460                    == PackageManager.SIGNATURE_MATCH;
4461            if (!match) {
4462                match = compareSignaturesCompat(pkgSetting.signatures, pkg)
4463                        == PackageManager.SIGNATURE_MATCH;
4464            }
4465            if (!match) {
4466                match = compareSignaturesRecover(pkgSetting.signatures, pkg)
4467                        == PackageManager.SIGNATURE_MATCH;
4468            }
4469            if (!match) {
4470                throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
4471                        + pkg.packageName + " signatures do not match the "
4472                        + "previously installed version; ignoring!");
4473            }
4474        }
4475
4476        // Check for shared user signatures
4477        if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) {
4478            // Already existing package. Make sure signatures match
4479            boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
4480                    pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
4481            if (!match) {
4482                match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg)
4483                        == PackageManager.SIGNATURE_MATCH;
4484            }
4485            if (!match) {
4486                match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg)
4487                        == PackageManager.SIGNATURE_MATCH;
4488            }
4489            if (!match) {
4490                throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
4491                        "Package " + pkg.packageName
4492                        + " has no signatures that match those in shared user "
4493                        + pkgSetting.sharedUser.name + "; ignoring!");
4494            }
4495        }
4496    }
4497
4498    /**
4499     * Enforces that only the system UID or root's UID can call a method exposed
4500     * via Binder.
4501     *
4502     * @param message used as message if SecurityException is thrown
4503     * @throws SecurityException if the caller is not system or root
4504     */
4505    private static final void enforceSystemOrRoot(String message) {
4506        final int uid = Binder.getCallingUid();
4507        if (uid != Process.SYSTEM_UID && uid != 0) {
4508            throw new SecurityException(message);
4509        }
4510    }
4511
4512    @Override
4513    public void performBootDexOpt() {
4514        enforceSystemOrRoot("Only the system can request dexopt be performed");
4515
4516        final HashSet<PackageParser.Package> pkgs;
4517        synchronized (mPackages) {
4518            pkgs = mDeferredDexOpt;
4519            mDeferredDexOpt = null;
4520        }
4521
4522        if (pkgs != null) {
4523            // Sort apps by importance for dexopt ordering. Important apps are given more priority
4524            // in case the device runs out of space.
4525            ArrayList<PackageParser.Package> sortedPkgs = new ArrayList<PackageParser.Package>();
4526            // Give priority to core apps.
4527            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4528                PackageParser.Package pkg = it.next();
4529                if (pkg.coreApp) {
4530                    if (DEBUG_DEXOPT) {
4531                        Log.i(TAG, "Adding core app " + sortedPkgs.size() + ": " + pkg.packageName);
4532                    }
4533                    sortedPkgs.add(pkg);
4534                    it.remove();
4535                }
4536            }
4537            // Give priority to system apps that listen for pre boot complete.
4538            Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
4539            HashSet<String> pkgNames = getPackageNamesForIntent(intent);
4540            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4541                PackageParser.Package pkg = it.next();
4542                if (pkgNames.contains(pkg.packageName)) {
4543                    if (DEBUG_DEXOPT) {
4544                        Log.i(TAG, "Adding pre boot system app " + sortedPkgs.size() + ": " + pkg.packageName);
4545                    }
4546                    sortedPkgs.add(pkg);
4547                    it.remove();
4548                }
4549            }
4550            // Give priority to system apps.
4551            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4552                PackageParser.Package pkg = it.next();
4553                if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
4554                    if (DEBUG_DEXOPT) {
4555                        Log.i(TAG, "Adding system app " + sortedPkgs.size() + ": " + pkg.packageName);
4556                    }
4557                    sortedPkgs.add(pkg);
4558                    it.remove();
4559                }
4560            }
4561            // Give priority to updated system apps.
4562            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4563                PackageParser.Package pkg = it.next();
4564                if (isUpdatedSystemApp(pkg)) {
4565                    if (DEBUG_DEXOPT) {
4566                        Log.i(TAG, "Adding updated system app " + sortedPkgs.size() + ": " + pkg.packageName);
4567                    }
4568                    sortedPkgs.add(pkg);
4569                    it.remove();
4570                }
4571            }
4572            // Give priority to apps that listen for boot complete.
4573            intent = new Intent(Intent.ACTION_BOOT_COMPLETED);
4574            pkgNames = getPackageNamesForIntent(intent);
4575            for (Iterator<PackageParser.Package> it = pkgs.iterator(); it.hasNext();) {
4576                PackageParser.Package pkg = it.next();
4577                if (pkgNames.contains(pkg.packageName)) {
4578                    if (DEBUG_DEXOPT) {
4579                        Log.i(TAG, "Adding boot app " + sortedPkgs.size() + ": " + pkg.packageName);
4580                    }
4581                    sortedPkgs.add(pkg);
4582                    it.remove();
4583                }
4584            }
4585            // Filter out packages that aren't recently used.
4586            filterRecentlyUsedApps(pkgs);
4587            // Add all remaining apps.
4588            for (PackageParser.Package pkg : pkgs) {
4589                if (DEBUG_DEXOPT) {
4590                    Log.i(TAG, "Adding app " + sortedPkgs.size() + ": " + pkg.packageName);
4591                }
4592                sortedPkgs.add(pkg);
4593            }
4594
4595            int i = 0;
4596            int total = sortedPkgs.size();
4597            File dataDir = Environment.getDataDirectory();
4598            long lowThreshold = StorageManager.from(mContext).getStorageLowBytes(dataDir);
4599            if (lowThreshold == 0) {
4600                throw new IllegalStateException("Invalid low memory threshold");
4601            }
4602            for (PackageParser.Package pkg : sortedPkgs) {
4603                long usableSpace = dataDir.getUsableSpace();
4604                if (usableSpace < lowThreshold) {
4605                    Log.w(TAG, "Not running dexopt on remaining apps due to low memory: " + usableSpace);
4606                    break;
4607                }
4608                performBootDexOpt(pkg, ++i, total);
4609            }
4610        }
4611    }
4612
4613    private void filterRecentlyUsedApps(HashSet<PackageParser.Package> pkgs) {
4614        // Filter out packages that aren't recently used.
4615        //
4616        // The exception is first boot of a non-eng device (aka !mLazyDexOpt), which
4617        // should do a full dexopt.
4618        if (mLazyDexOpt || (!isFirstBoot() && mPackageUsage.isHistoricalPackageUsageAvailable())) {
4619            // TODO: add a property to control this?
4620            long dexOptLRUThresholdInMinutes;
4621            if (mLazyDexOpt) {
4622                dexOptLRUThresholdInMinutes = 30; // only last 30 minutes of apps for eng builds.
4623            } else {
4624                dexOptLRUThresholdInMinutes = 7 * 24 * 60; // apps used in the 7 days for users.
4625            }
4626            long dexOptLRUThresholdInMills = dexOptLRUThresholdInMinutes * 60 * 1000;
4627
4628            int total = pkgs.size();
4629            int skipped = 0;
4630            long now = System.currentTimeMillis();
4631            for (Iterator<PackageParser.Package> i = pkgs.iterator(); i.hasNext();) {
4632                PackageParser.Package pkg = i.next();
4633                long then = pkg.mLastPackageUsageTimeInMills;
4634                if (then + dexOptLRUThresholdInMills < now) {
4635                    if (DEBUG_DEXOPT) {
4636                        Log.i(TAG, "Skipping dexopt of " + pkg.packageName + " last resumed: " +
4637                              ((then == 0) ? "never" : new Date(then)));
4638                    }
4639                    i.remove();
4640                    skipped++;
4641                }
4642            }
4643            if (DEBUG_DEXOPT) {
4644                Log.i(TAG, "Skipped optimizing " + skipped + " of " + total);
4645            }
4646        }
4647    }
4648
4649    private HashSet<String> getPackageNamesForIntent(Intent intent) {
4650        List<ResolveInfo> ris = null;
4651        try {
4652            ris = AppGlobals.getPackageManager().queryIntentReceivers(
4653                    intent, null, 0, UserHandle.USER_OWNER);
4654        } catch (RemoteException e) {
4655        }
4656        HashSet<String> pkgNames = new HashSet<String>();
4657        if (ris != null) {
4658            for (ResolveInfo ri : ris) {
4659                pkgNames.add(ri.activityInfo.packageName);
4660            }
4661        }
4662        return pkgNames;
4663    }
4664
4665    private void performBootDexOpt(PackageParser.Package pkg, int curr, int total) {
4666        if (DEBUG_DEXOPT) {
4667            Log.i(TAG, "Optimizing app " + curr + " of " + total + ": " + pkg.packageName);
4668        }
4669        if (!isFirstBoot()) {
4670            try {
4671                ActivityManagerNative.getDefault().showBootMessage(
4672                        mContext.getResources().getString(R.string.android_upgrading_apk,
4673                                curr, total), true);
4674            } catch (RemoteException e) {
4675            }
4676        }
4677        PackageParser.Package p = pkg;
4678        synchronized (mInstallLock) {
4679            performDexOptLI(p, null /* instruction sets */, false /* force dex */,
4680                            false /* defer */, true /* include dependencies */);
4681        }
4682    }
4683
4684    @Override
4685    public boolean performDexOptIfNeeded(String packageName, String instructionSet) {
4686        return performDexOpt(packageName, instructionSet, false);
4687    }
4688
4689    private static String getPrimaryInstructionSet(ApplicationInfo info) {
4690        if (info.primaryCpuAbi == null) {
4691            return getPreferredInstructionSet();
4692        }
4693
4694        return VMRuntime.getInstructionSet(info.primaryCpuAbi);
4695    }
4696
4697    public boolean performDexOpt(String packageName, String instructionSet, boolean backgroundDexopt) {
4698        boolean dexopt = mLazyDexOpt || backgroundDexopt;
4699        boolean updateUsage = !backgroundDexopt;  // Don't update usage if this is just a backgroundDexopt
4700        if (!dexopt && !updateUsage) {
4701            // We aren't going to dexopt or update usage, so bail early.
4702            return false;
4703        }
4704        PackageParser.Package p;
4705        final String targetInstructionSet;
4706        synchronized (mPackages) {
4707            p = mPackages.get(packageName);
4708            if (p == null) {
4709                return false;
4710            }
4711            if (updateUsage) {
4712                p.mLastPackageUsageTimeInMills = System.currentTimeMillis();
4713            }
4714            mPackageUsage.write(false);
4715            if (!dexopt) {
4716                // We aren't going to dexopt, so bail early.
4717                return false;
4718            }
4719
4720            targetInstructionSet = instructionSet != null ? instructionSet :
4721                    getPrimaryInstructionSet(p.applicationInfo);
4722            if (p.mDexOptPerformed.contains(targetInstructionSet)) {
4723                return false;
4724            }
4725        }
4726
4727        synchronized (mInstallLock) {
4728            final String[] instructionSets = new String[] { targetInstructionSet };
4729            return performDexOptLI(p, instructionSets, false /* force dex */, false /* defer */,
4730                    true /* include dependencies */) == DEX_OPT_PERFORMED;
4731        }
4732    }
4733
4734    public HashSet<String> getPackagesThatNeedDexOpt() {
4735        HashSet<String> pkgs = null;
4736        synchronized (mPackages) {
4737            for (PackageParser.Package p : mPackages.values()) {
4738                if (DEBUG_DEXOPT) {
4739                    Log.i(TAG, p.packageName + " mDexOptPerformed=" + p.mDexOptPerformed.toArray());
4740                }
4741                if (!p.mDexOptPerformed.isEmpty()) {
4742                    continue;
4743                }
4744                if (pkgs == null) {
4745                    pkgs = new HashSet<String>();
4746                }
4747                pkgs.add(p.packageName);
4748            }
4749        }
4750        return pkgs;
4751    }
4752
4753    public void shutdown() {
4754        mPackageUsage.write(true);
4755    }
4756
4757    private void performDexOptLibsLI(ArrayList<String> libs, String[] instructionSets,
4758             boolean forceDex, boolean defer, HashSet<String> done) {
4759        for (int i=0; i<libs.size(); i++) {
4760            PackageParser.Package libPkg;
4761            String libName;
4762            synchronized (mPackages) {
4763                libName = libs.get(i);
4764                SharedLibraryEntry lib = mSharedLibraries.get(libName);
4765                if (lib != null && lib.apk != null) {
4766                    libPkg = mPackages.get(lib.apk);
4767                } else {
4768                    libPkg = null;
4769                }
4770            }
4771            if (libPkg != null && !done.contains(libName)) {
4772                performDexOptLI(libPkg, instructionSets, forceDex, defer, done);
4773            }
4774        }
4775    }
4776
4777    static final int DEX_OPT_SKIPPED = 0;
4778    static final int DEX_OPT_PERFORMED = 1;
4779    static final int DEX_OPT_DEFERRED = 2;
4780    static final int DEX_OPT_FAILED = -1;
4781
4782    private int performDexOptLI(PackageParser.Package pkg, String[] targetInstructionSets,
4783            boolean forceDex, boolean defer, HashSet<String> done) {
4784        final String[] instructionSets = targetInstructionSets != null ?
4785                targetInstructionSets : getAppDexInstructionSets(pkg.applicationInfo);
4786
4787        if (done != null) {
4788            done.add(pkg.packageName);
4789            if (pkg.usesLibraries != null) {
4790                performDexOptLibsLI(pkg.usesLibraries, instructionSets, forceDex, defer, done);
4791            }
4792            if (pkg.usesOptionalLibraries != null) {
4793                performDexOptLibsLI(pkg.usesOptionalLibraries, instructionSets, forceDex, defer, done);
4794            }
4795        }
4796
4797        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) == 0) {
4798            return DEX_OPT_SKIPPED;
4799        }
4800
4801        final boolean vmSafeMode = (pkg.applicationInfo.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0;
4802
4803        final List<String> paths = pkg.getAllCodePathsExcludingResourceOnly();
4804        boolean performedDexOpt = false;
4805        // There are three basic cases here:
4806        // 1.) we need to dexopt, either because we are forced or it is needed
4807        // 2.) we are defering a needed dexopt
4808        // 3.) we are skipping an unneeded dexopt
4809        final String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
4810        for (String dexCodeInstructionSet : dexCodeInstructionSets) {
4811            if (!forceDex && pkg.mDexOptPerformed.contains(dexCodeInstructionSet)) {
4812                continue;
4813            }
4814
4815            for (String path : paths) {
4816                try {
4817                    // This will return DEXOPT_NEEDED if we either cannot find any odex file for this
4818                    // patckage or the one we find does not match the image checksum (i.e. it was
4819                    // compiled against an old image). It will return PATCHOAT_NEEDED if we can find a
4820                    // odex file and it matches the checksum of the image but not its base address,
4821                    // meaning we need to move it.
4822                    final byte isDexOptNeeded = DexFile.isDexOptNeededInternal(path,
4823                            pkg.packageName, dexCodeInstructionSet, defer);
4824                    if (forceDex || (!defer && isDexOptNeeded == DexFile.DEXOPT_NEEDED)) {
4825                        Log.i(TAG, "Running dexopt on: " + path + " pkg="
4826                                + pkg.applicationInfo.packageName + " isa=" + dexCodeInstructionSet
4827                                + " vmSafeMode=" + vmSafeMode);
4828                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4829                        final int ret = mInstaller.dexopt(path, sharedGid, !isForwardLocked(pkg),
4830                                pkg.packageName, dexCodeInstructionSet, vmSafeMode);
4831
4832                        if (ret < 0) {
4833                            // Don't bother running dexopt again if we failed, it will probably
4834                            // just result in an error again. Also, don't bother dexopting for other
4835                            // paths & ISAs.
4836                            return DEX_OPT_FAILED;
4837                        }
4838
4839                        performedDexOpt = true;
4840                    } else if (!defer && isDexOptNeeded == DexFile.PATCHOAT_NEEDED) {
4841                        Log.i(TAG, "Running patchoat on: " + pkg.applicationInfo.packageName);
4842                        final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid);
4843                        final int ret = mInstaller.patchoat(path, sharedGid, !isForwardLocked(pkg),
4844                                pkg.packageName, dexCodeInstructionSet);
4845
4846                        if (ret < 0) {
4847                            // Don't bother running patchoat again if we failed, it will probably
4848                            // just result in an error again. Also, don't bother dexopting for other
4849                            // paths & ISAs.
4850                            return DEX_OPT_FAILED;
4851                        }
4852
4853                        performedDexOpt = true;
4854                    }
4855
4856                    // We're deciding to defer a needed dexopt. Don't bother dexopting for other
4857                    // paths and instruction sets. We'll deal with them all together when we process
4858                    // our list of deferred dexopts.
4859                    if (defer && isDexOptNeeded != DexFile.UP_TO_DATE) {
4860                        if (mDeferredDexOpt == null) {
4861                            mDeferredDexOpt = new HashSet<PackageParser.Package>();
4862                        }
4863                        mDeferredDexOpt.add(pkg);
4864                        return DEX_OPT_DEFERRED;
4865                    }
4866                } catch (FileNotFoundException e) {
4867                    Slog.w(TAG, "Apk not found for dexopt: " + path);
4868                    return DEX_OPT_FAILED;
4869                } catch (IOException e) {
4870                    Slog.w(TAG, "IOException reading apk: " + path, e);
4871                    return DEX_OPT_FAILED;
4872                } catch (StaleDexCacheError e) {
4873                    Slog.w(TAG, "StaleDexCacheError when reading apk: " + path, e);
4874                    return DEX_OPT_FAILED;
4875                } catch (Exception e) {
4876                    Slog.w(TAG, "Exception when doing dexopt : ", e);
4877                    return DEX_OPT_FAILED;
4878                }
4879            }
4880
4881            // At this point we haven't failed dexopt and we haven't deferred dexopt. We must
4882            // either have either succeeded dexopt, or have had isDexOptNeededInternal tell us
4883            // it isn't required. We therefore mark that this package doesn't need dexopt unless
4884            // it's forced. performedDexOpt will tell us whether we performed dex-opt or skipped
4885            // it.
4886            pkg.mDexOptPerformed.add(dexCodeInstructionSet);
4887        }
4888
4889        // If we've gotten here, we're sure that no error occurred and that we haven't
4890        // deferred dex-opt. We've either dex-opted one more paths or instruction sets or
4891        // we've skipped all of them because they are up to date. In both cases this
4892        // package doesn't need dexopt any longer.
4893        return performedDexOpt ? DEX_OPT_PERFORMED : DEX_OPT_SKIPPED;
4894    }
4895
4896    private static String[] getAppDexInstructionSets(ApplicationInfo info) {
4897        if (info.primaryCpuAbi != null) {
4898            if (info.secondaryCpuAbi != null) {
4899                return new String[] {
4900                        VMRuntime.getInstructionSet(info.primaryCpuAbi),
4901                        VMRuntime.getInstructionSet(info.secondaryCpuAbi) };
4902            } else {
4903                return new String[] {
4904                        VMRuntime.getInstructionSet(info.primaryCpuAbi) };
4905            }
4906        }
4907
4908        return new String[] { getPreferredInstructionSet() };
4909    }
4910
4911    private static String[] getAppDexInstructionSets(PackageSetting ps) {
4912        if (ps.primaryCpuAbiString != null) {
4913            if (ps.secondaryCpuAbiString != null) {
4914                return new String[] {
4915                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString),
4916                        VMRuntime.getInstructionSet(ps.secondaryCpuAbiString) };
4917            } else {
4918                return new String[] {
4919                        VMRuntime.getInstructionSet(ps.primaryCpuAbiString) };
4920            }
4921        }
4922
4923        return new String[] { getPreferredInstructionSet() };
4924    }
4925
4926    private static String getPreferredInstructionSet() {
4927        if (sPreferredInstructionSet == null) {
4928            sPreferredInstructionSet = VMRuntime.getInstructionSet(Build.SUPPORTED_ABIS[0]);
4929        }
4930
4931        return sPreferredInstructionSet;
4932    }
4933
4934    private static List<String> getAllInstructionSets() {
4935        final String[] allAbis = Build.SUPPORTED_ABIS;
4936        final List<String> allInstructionSets = new ArrayList<String>(allAbis.length);
4937
4938        for (String abi : allAbis) {
4939            final String instructionSet = VMRuntime.getInstructionSet(abi);
4940            if (!allInstructionSets.contains(instructionSet)) {
4941                allInstructionSets.add(instructionSet);
4942            }
4943        }
4944
4945        return allInstructionSets;
4946    }
4947
4948    /**
4949     * Returns the instruction set that should be used to compile dex code. In the presence of
4950     * a native bridge this might be different than the one shared libraries use.
4951     */
4952    private static String getDexCodeInstructionSet(String sharedLibraryIsa) {
4953        String dexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + sharedLibraryIsa);
4954        return (dexCodeIsa.isEmpty() ? sharedLibraryIsa : dexCodeIsa);
4955    }
4956
4957    private static String[] getDexCodeInstructionSets(String[] instructionSets) {
4958        HashSet<String> dexCodeInstructionSets = new HashSet<String>(instructionSets.length);
4959        for (String instructionSet : instructionSets) {
4960            dexCodeInstructionSets.add(getDexCodeInstructionSet(instructionSet));
4961        }
4962        return dexCodeInstructionSets.toArray(new String[dexCodeInstructionSets.size()]);
4963    }
4964
4965    /**
4966     * Returns deduplicated list of supported instructions for dex code.
4967     */
4968    public static String[] getAllDexCodeInstructionSets() {
4969        String[] supportedInstructionSets = new String[Build.SUPPORTED_ABIS.length];
4970        for (int i = 0; i < supportedInstructionSets.length; i++) {
4971            String abi = Build.SUPPORTED_ABIS[i];
4972            supportedInstructionSets[i] = VMRuntime.getInstructionSet(abi);
4973        }
4974        return getDexCodeInstructionSets(supportedInstructionSets);
4975    }
4976
4977    @Override
4978    public void forceDexOpt(String packageName) {
4979        enforceSystemOrRoot("forceDexOpt");
4980
4981        PackageParser.Package pkg;
4982        synchronized (mPackages) {
4983            pkg = mPackages.get(packageName);
4984            if (pkg == null) {
4985                throw new IllegalArgumentException("Missing package: " + packageName);
4986            }
4987        }
4988
4989        synchronized (mInstallLock) {
4990            final String[] instructionSets = new String[] {
4991                    getPrimaryInstructionSet(pkg.applicationInfo) };
4992            final int res = performDexOptLI(pkg, instructionSets, true, false, true);
4993            if (res != DEX_OPT_PERFORMED) {
4994                throw new IllegalStateException("Failed to dexopt: " + res);
4995            }
4996        }
4997    }
4998
4999    private int performDexOptLI(PackageParser.Package pkg, String[] instructionSets,
5000                                boolean forceDex, boolean defer, boolean inclDependencies) {
5001        HashSet<String> done;
5002        if (inclDependencies && (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null)) {
5003            done = new HashSet<String>();
5004            done.add(pkg.packageName);
5005        } else {
5006            done = null;
5007        }
5008        return performDexOptLI(pkg, instructionSets,  forceDex, defer, done);
5009    }
5010
5011    private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) {
5012        if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) {
5013            Slog.w(TAG, "Unable to update from " + oldPkg.name
5014                    + " to " + newPkg.packageName
5015                    + ": old package not in system partition");
5016            return false;
5017        } else if (mPackages.get(oldPkg.name) != null) {
5018            Slog.w(TAG, "Unable to update from " + oldPkg.name
5019                    + " to " + newPkg.packageName
5020                    + ": old package still exists");
5021            return false;
5022        }
5023        return true;
5024    }
5025
5026    File getDataPathForUser(int userId) {
5027        return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId);
5028    }
5029
5030    private File getDataPathForPackage(String packageName, int userId) {
5031        /*
5032         * Until we fully support multiple users, return the directory we
5033         * previously would have. The PackageManagerTests will need to be
5034         * revised when this is changed back..
5035         */
5036        if (userId == 0) {
5037            return new File(mAppDataDir, packageName);
5038        } else {
5039            return new File(mUserAppDataDir.getAbsolutePath() + File.separator + userId
5040                + File.separator + packageName);
5041        }
5042    }
5043
5044    private int createDataDirsLI(String packageName, int uid, String seinfo) {
5045        int[] users = sUserManager.getUserIds();
5046        int res = mInstaller.install(packageName, uid, uid, seinfo);
5047        if (res < 0) {
5048            return res;
5049        }
5050        for (int user : users) {
5051            if (user != 0) {
5052                res = mInstaller.createUserData(packageName,
5053                        UserHandle.getUid(user, uid), user, seinfo);
5054                if (res < 0) {
5055                    return res;
5056                }
5057            }
5058        }
5059        return res;
5060    }
5061
5062    private int removeDataDirsLI(String packageName) {
5063        int[] users = sUserManager.getUserIds();
5064        int res = 0;
5065        for (int user : users) {
5066            int resInner = mInstaller.remove(packageName, user);
5067            if (resInner < 0) {
5068                res = resInner;
5069            }
5070        }
5071
5072        return res;
5073    }
5074
5075    private int deleteCodeCacheDirsLI(String packageName) {
5076        int[] users = sUserManager.getUserIds();
5077        int res = 0;
5078        for (int user : users) {
5079            int resInner = mInstaller.deleteCodeCacheFiles(packageName, user);
5080            if (resInner < 0) {
5081                res = resInner;
5082            }
5083        }
5084        return res;
5085    }
5086
5087    private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file,
5088            PackageParser.Package changingLib) {
5089        if (file.path != null) {
5090            usesLibraryFiles.add(file.path);
5091            return;
5092        }
5093        PackageParser.Package p = mPackages.get(file.apk);
5094        if (changingLib != null && changingLib.packageName.equals(file.apk)) {
5095            // If we are doing this while in the middle of updating a library apk,
5096            // then we need to make sure to use that new apk for determining the
5097            // dependencies here.  (We haven't yet finished committing the new apk
5098            // to the package manager state.)
5099            if (p == null || p.packageName.equals(changingLib.packageName)) {
5100                p = changingLib;
5101            }
5102        }
5103        if (p != null) {
5104            usesLibraryFiles.addAll(p.getAllCodePaths());
5105        }
5106    }
5107
5108    private void updateSharedLibrariesLPw(PackageParser.Package pkg,
5109            PackageParser.Package changingLib) throws PackageManagerException {
5110        if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) {
5111            final ArraySet<String> usesLibraryFiles = new ArraySet<>();
5112            int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0;
5113            for (int i=0; i<N; i++) {
5114                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i));
5115                if (file == null) {
5116                    throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY,
5117                            "Package " + pkg.packageName + " requires unavailable shared library "
5118                            + pkg.usesLibraries.get(i) + "; failing!");
5119                }
5120                addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5121            }
5122            N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0;
5123            for (int i=0; i<N; i++) {
5124                final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i));
5125                if (file == null) {
5126                    Slog.w(TAG, "Package " + pkg.packageName
5127                            + " desires unavailable shared library "
5128                            + pkg.usesOptionalLibraries.get(i) + "; ignoring!");
5129                } else {
5130                    addSharedLibraryLPw(usesLibraryFiles, file, changingLib);
5131                }
5132            }
5133            N = usesLibraryFiles.size();
5134            if (N > 0) {
5135                pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]);
5136            } else {
5137                pkg.usesLibraryFiles = null;
5138            }
5139        }
5140    }
5141
5142    private static boolean hasString(List<String> list, List<String> which) {
5143        if (list == null) {
5144            return false;
5145        }
5146        for (int i=list.size()-1; i>=0; i--) {
5147            for (int j=which.size()-1; j>=0; j--) {
5148                if (which.get(j).equals(list.get(i))) {
5149                    return true;
5150                }
5151            }
5152        }
5153        return false;
5154    }
5155
5156    private void updateAllSharedLibrariesLPw() {
5157        for (PackageParser.Package pkg : mPackages.values()) {
5158            try {
5159                updateSharedLibrariesLPw(pkg, null);
5160            } catch (PackageManagerException e) {
5161                Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5162            }
5163        }
5164    }
5165
5166    private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw(
5167            PackageParser.Package changingPkg) {
5168        ArrayList<PackageParser.Package> res = null;
5169        for (PackageParser.Package pkg : mPackages.values()) {
5170            if (hasString(pkg.usesLibraries, changingPkg.libraryNames)
5171                    || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) {
5172                if (res == null) {
5173                    res = new ArrayList<PackageParser.Package>();
5174                }
5175                res.add(pkg);
5176                try {
5177                    updateSharedLibrariesLPw(pkg, changingPkg);
5178                } catch (PackageManagerException e) {
5179                    Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage());
5180                }
5181            }
5182        }
5183        return res;
5184    }
5185
5186    /**
5187     * Derive the value of the {@code cpuAbiOverride} based on the provided
5188     * value and an optional stored value from the package settings.
5189     */
5190    private static String deriveAbiOverride(String abiOverride, PackageSetting settings) {
5191        String cpuAbiOverride = null;
5192
5193        if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) {
5194            cpuAbiOverride = null;
5195        } else if (abiOverride != null) {
5196            cpuAbiOverride = abiOverride;
5197        } else if (settings != null) {
5198            cpuAbiOverride = settings.cpuAbiOverrideString;
5199        }
5200
5201        return cpuAbiOverride;
5202    }
5203
5204    private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags,
5205            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5206        boolean success = false;
5207        try {
5208            final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags,
5209                    currentTime, user);
5210            success = true;
5211            return res;
5212        } finally {
5213            if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) {
5214                removeDataDirsLI(pkg.packageName);
5215            }
5216        }
5217    }
5218
5219    private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags,
5220            int scanFlags, long currentTime, UserHandle user) throws PackageManagerException {
5221        final File scanFile = new File(pkg.codePath);
5222        if (pkg.applicationInfo.getCodePath() == null ||
5223                pkg.applicationInfo.getResourcePath() == null) {
5224            // Bail out. The resource and code paths haven't been set.
5225            throw new PackageManagerException(INSTALL_FAILED_INVALID_APK,
5226                    "Code and resource paths haven't been set correctly");
5227        }
5228
5229        if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) {
5230            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM;
5231        } else {
5232            // Only allow system apps to be flagged as core apps.
5233            pkg.coreApp = false;
5234        }
5235
5236        if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) {
5237            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_PRIVILEGED;
5238        }
5239
5240        if (mCustomResolverComponentName != null &&
5241                mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) {
5242            setUpCustomResolverActivity(pkg);
5243        }
5244
5245        if (pkg.packageName.equals("android")) {
5246            synchronized (mPackages) {
5247                if (mAndroidApplication != null) {
5248                    Slog.w(TAG, "*************************************************");
5249                    Slog.w(TAG, "Core android package being redefined.  Skipping.");
5250                    Slog.w(TAG, " file=" + scanFile);
5251                    Slog.w(TAG, "*************************************************");
5252                    throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5253                            "Core android package being redefined.  Skipping.");
5254                }
5255
5256                // Set up information for our fall-back user intent resolution activity.
5257                mPlatformPackage = pkg;
5258                pkg.mVersionCode = mSdkVersion;
5259                mAndroidApplication = pkg.applicationInfo;
5260
5261                if (!mResolverReplaced) {
5262                    mResolveActivity.applicationInfo = mAndroidApplication;
5263                    mResolveActivity.name = ResolverActivity.class.getName();
5264                    mResolveActivity.packageName = mAndroidApplication.packageName;
5265                    mResolveActivity.processName = "system:ui";
5266                    mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
5267                    mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER;
5268                    mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS;
5269                    mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert;
5270                    mResolveActivity.exported = true;
5271                    mResolveActivity.enabled = true;
5272                    mResolveInfo.activityInfo = mResolveActivity;
5273                    mResolveInfo.priority = 0;
5274                    mResolveInfo.preferredOrder = 0;
5275                    mResolveInfo.match = 0;
5276                    mResolveComponentName = new ComponentName(
5277                            mAndroidApplication.packageName, mResolveActivity.name);
5278                }
5279            }
5280        }
5281
5282        if (DEBUG_PACKAGE_SCANNING) {
5283            if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5284                Log.d(TAG, "Scanning package " + pkg.packageName);
5285        }
5286
5287        if (mPackages.containsKey(pkg.packageName)
5288                || mSharedLibraries.containsKey(pkg.packageName)) {
5289            throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE,
5290                    "Application package " + pkg.packageName
5291                    + " already installed.  Skipping duplicate.");
5292        }
5293
5294        // Initialize package source and resource directories
5295        File destCodeFile = new File(pkg.applicationInfo.getCodePath());
5296        File destResourceFile = new File(pkg.applicationInfo.getResourcePath());
5297
5298        SharedUserSetting suid = null;
5299        PackageSetting pkgSetting = null;
5300
5301        if (!isSystemApp(pkg)) {
5302            // Only system apps can use these features.
5303            pkg.mOriginalPackages = null;
5304            pkg.mRealPackage = null;
5305            pkg.mAdoptPermissions = null;
5306        }
5307
5308        // writer
5309        synchronized (mPackages) {
5310            if (pkg.mSharedUserId != null) {
5311                suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, true);
5312                if (suid == null) {
5313                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5314                            "Creating application package " + pkg.packageName
5315                            + " for shared user failed");
5316                }
5317                if (DEBUG_PACKAGE_SCANNING) {
5318                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5319                        Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId
5320                                + "): packages=" + suid.packages);
5321                }
5322            }
5323
5324            // Check if we are renaming from an original package name.
5325            PackageSetting origPackage = null;
5326            String realName = null;
5327            if (pkg.mOriginalPackages != null) {
5328                // This package may need to be renamed to a previously
5329                // installed name.  Let's check on that...
5330                final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage);
5331                if (pkg.mOriginalPackages.contains(renamed)) {
5332                    // This package had originally been installed as the
5333                    // original name, and we have already taken care of
5334                    // transitioning to the new one.  Just update the new
5335                    // one to continue using the old name.
5336                    realName = pkg.mRealPackage;
5337                    if (!pkg.packageName.equals(renamed)) {
5338                        // Callers into this function may have already taken
5339                        // care of renaming the package; only do it here if
5340                        // it is not already done.
5341                        pkg.setPackageName(renamed);
5342                    }
5343
5344                } else {
5345                    for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) {
5346                        if ((origPackage = mSettings.peekPackageLPr(
5347                                pkg.mOriginalPackages.get(i))) != null) {
5348                            // We do have the package already installed under its
5349                            // original name...  should we use it?
5350                            if (!verifyPackageUpdateLPr(origPackage, pkg)) {
5351                                // New package is not compatible with original.
5352                                origPackage = null;
5353                                continue;
5354                            } else if (origPackage.sharedUser != null) {
5355                                // Make sure uid is compatible between packages.
5356                                if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) {
5357                                    Slog.w(TAG, "Unable to migrate data from " + origPackage.name
5358                                            + " to " + pkg.packageName + ": old uid "
5359                                            + origPackage.sharedUser.name
5360                                            + " differs from " + pkg.mSharedUserId);
5361                                    origPackage = null;
5362                                    continue;
5363                                }
5364                            } else {
5365                                if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package "
5366                                        + pkg.packageName + " to old name " + origPackage.name);
5367                            }
5368                            break;
5369                        }
5370                    }
5371                }
5372            }
5373
5374            if (mTransferedPackages.contains(pkg.packageName)) {
5375                Slog.w(TAG, "Package " + pkg.packageName
5376                        + " was transferred to another, but its .apk remains");
5377            }
5378
5379            // Just create the setting, don't add it yet. For already existing packages
5380            // the PkgSetting exists already and doesn't have to be created.
5381            pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile,
5382                    destResourceFile, pkg.applicationInfo.nativeLibraryRootDir,
5383                    pkg.applicationInfo.primaryCpuAbi,
5384                    pkg.applicationInfo.secondaryCpuAbi,
5385                    pkg.applicationInfo.flags, user, false);
5386            if (pkgSetting == null) {
5387                throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5388                        "Creating application package " + pkg.packageName + " failed");
5389            }
5390
5391            if (pkgSetting.origPackage != null) {
5392                // If we are first transitioning from an original package,
5393                // fix up the new package's name now.  We need to do this after
5394                // looking up the package under its new name, so getPackageLP
5395                // can take care of fiddling things correctly.
5396                pkg.setPackageName(origPackage.name);
5397
5398                // File a report about this.
5399                String msg = "New package " + pkgSetting.realName
5400                        + " renamed to replace old package " + pkgSetting.name;
5401                reportSettingsProblem(Log.WARN, msg);
5402
5403                // Make a note of it.
5404                mTransferedPackages.add(origPackage.name);
5405
5406                // No longer need to retain this.
5407                pkgSetting.origPackage = null;
5408            }
5409
5410            if (realName != null) {
5411                // Make a note of it.
5412                mTransferedPackages.add(pkg.packageName);
5413            }
5414
5415            if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) {
5416                pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
5417            }
5418
5419            if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5420                // Check all shared libraries and map to their actual file path.
5421                // We only do this here for apps not on a system dir, because those
5422                // are the only ones that can fail an install due to this.  We
5423                // will take care of the system apps by updating all of their
5424                // library paths after the scan is done.
5425                updateSharedLibrariesLPw(pkg, null);
5426            }
5427
5428            if (mFoundPolicyFile) {
5429                SELinuxMMAC.assignSeinfoValue(pkg);
5430            }
5431
5432            pkg.applicationInfo.uid = pkgSetting.appId;
5433            pkg.mExtras = pkgSetting;
5434            if (!pkgSetting.keySetData.isUsingUpgradeKeySets() || pkgSetting.sharedUser != null) {
5435                try {
5436                    verifySignaturesLP(pkgSetting, pkg);
5437                    // We just determined the app is signed correctly, so bring
5438                    // over the latest parsed certs.
5439                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5440                } catch (PackageManagerException e) {
5441                    if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) {
5442                        throw e;
5443                    }
5444                    // The signature has changed, but this package is in the system
5445                    // image...  let's recover!
5446                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5447                    // However...  if this package is part of a shared user, but it
5448                    // doesn't match the signature of the shared user, let's fail.
5449                    // What this means is that you can't change the signatures
5450                    // associated with an overall shared user, which doesn't seem all
5451                    // that unreasonable.
5452                    if (pkgSetting.sharedUser != null) {
5453                        if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures,
5454                                              pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) {
5455                            throw new PackageManagerException(
5456                                    INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
5457                                            "Signature mismatch for shared user : "
5458                                            + pkgSetting.sharedUser);
5459                        }
5460                    }
5461                    // File a report about this.
5462                    String msg = "System package " + pkg.packageName
5463                        + " signature changed; retaining data.";
5464                    reportSettingsProblem(Log.WARN, msg);
5465                }
5466            } else {
5467                if (!checkUpgradeKeySetLP(pkgSetting, pkg)) {
5468                    throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package "
5469                            + pkg.packageName + " upgrade keys do not match the "
5470                            + "previously installed version");
5471                } else {
5472                    // We just determined the app is signed correctly, so bring
5473                    // over the latest parsed certs.
5474                    pkgSetting.signatures.mSignatures = pkg.mSignatures;
5475                }
5476            }
5477            // Verify that this new package doesn't have any content providers
5478            // that conflict with existing packages.  Only do this if the
5479            // package isn't already installed, since we don't want to break
5480            // things that are installed.
5481            if ((scanFlags & SCAN_NEW_INSTALL) != 0) {
5482                final int N = pkg.providers.size();
5483                int i;
5484                for (i=0; i<N; i++) {
5485                    PackageParser.Provider p = pkg.providers.get(i);
5486                    if (p.info.authority != null) {
5487                        String names[] = p.info.authority.split(";");
5488                        for (int j = 0; j < names.length; j++) {
5489                            if (mProvidersByAuthority.containsKey(names[j])) {
5490                                PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
5491                                final String otherPackageName =
5492                                        ((other != null && other.getComponentName() != null) ?
5493                                                other.getComponentName().getPackageName() : "?");
5494                                throw new PackageManagerException(
5495                                        INSTALL_FAILED_CONFLICTING_PROVIDER,
5496                                                "Can't install because provider name " + names[j]
5497                                                + " (in package " + pkg.applicationInfo.packageName
5498                                                + ") is already used by " + otherPackageName);
5499                            }
5500                        }
5501                    }
5502                }
5503            }
5504
5505            if (pkg.mAdoptPermissions != null) {
5506                // This package wants to adopt ownership of permissions from
5507                // another package.
5508                for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) {
5509                    final String origName = pkg.mAdoptPermissions.get(i);
5510                    final PackageSetting orig = mSettings.peekPackageLPr(origName);
5511                    if (orig != null) {
5512                        if (verifyPackageUpdateLPr(orig, pkg)) {
5513                            Slog.i(TAG, "Adopting permissions from " + origName + " to "
5514                                    + pkg.packageName);
5515                            mSettings.transferPermissionsLPw(origName, pkg.packageName);
5516                        }
5517                    }
5518                }
5519            }
5520        }
5521
5522        final String pkgName = pkg.packageName;
5523
5524        final long scanFileTime = scanFile.lastModified();
5525        final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0;
5526        pkg.applicationInfo.processName = fixProcessName(
5527                pkg.applicationInfo.packageName,
5528                pkg.applicationInfo.processName,
5529                pkg.applicationInfo.uid);
5530
5531        File dataPath;
5532        if (mPlatformPackage == pkg) {
5533            // The system package is special.
5534            dataPath = new File(Environment.getDataDirectory(), "system");
5535
5536            pkg.applicationInfo.dataDir = dataPath.getPath();
5537
5538        } else {
5539            // This is a normal package, need to make its data directory.
5540            dataPath = getDataPathForPackage(pkg.packageName, 0);
5541
5542            boolean uidError = false;
5543            if (dataPath.exists()) {
5544                int currentUid = 0;
5545                try {
5546                    StructStat stat = Os.stat(dataPath.getPath());
5547                    currentUid = stat.st_uid;
5548                } catch (ErrnoException e) {
5549                    Slog.e(TAG, "Couldn't stat path " + dataPath.getPath(), e);
5550                }
5551
5552                // If we have mismatched owners for the data path, we have a problem.
5553                if (currentUid != pkg.applicationInfo.uid) {
5554                    boolean recovered = false;
5555                    if (currentUid == 0) {
5556                        // The directory somehow became owned by root.  Wow.
5557                        // This is probably because the system was stopped while
5558                        // installd was in the middle of messing with its libs
5559                        // directory.  Ask installd to fix that.
5560                        int ret = mInstaller.fixUid(pkgName, pkg.applicationInfo.uid,
5561                                pkg.applicationInfo.uid);
5562                        if (ret >= 0) {
5563                            recovered = true;
5564                            String msg = "Package " + pkg.packageName
5565                                    + " unexpectedly changed to uid 0; recovered to " +
5566                                    + pkg.applicationInfo.uid;
5567                            reportSettingsProblem(Log.WARN, msg);
5568                        }
5569                    }
5570                    if (!recovered && ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5571                            || (scanFlags&SCAN_BOOTING) != 0)) {
5572                        // If this is a system app, we can at least delete its
5573                        // current data so the application will still work.
5574                        int ret = removeDataDirsLI(pkgName);
5575                        if (ret >= 0) {
5576                            // TODO: Kill the processes first
5577                            // Old data gone!
5578                            String prefix = (parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0
5579                                    ? "System package " : "Third party package ";
5580                            String msg = prefix + pkg.packageName
5581                                    + " has changed from uid: "
5582                                    + currentUid + " to "
5583                                    + pkg.applicationInfo.uid + "; old data erased";
5584                            reportSettingsProblem(Log.WARN, msg);
5585                            recovered = true;
5586
5587                            // And now re-install the app.
5588                            ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5589                                                   pkg.applicationInfo.seinfo);
5590                            if (ret == -1) {
5591                                // Ack should not happen!
5592                                msg = prefix + pkg.packageName
5593                                        + " could not have data directory re-created after delete.";
5594                                reportSettingsProblem(Log.WARN, msg);
5595                                throw new PackageManagerException(
5596                                        INSTALL_FAILED_INSUFFICIENT_STORAGE, msg);
5597                            }
5598                        }
5599                        if (!recovered) {
5600                            mHasSystemUidErrors = true;
5601                        }
5602                    } else if (!recovered) {
5603                        // If we allow this install to proceed, we will be broken.
5604                        // Abort, abort!
5605                        throw new PackageManagerException(INSTALL_FAILED_UID_CHANGED,
5606                                "scanPackageLI");
5607                    }
5608                    if (!recovered) {
5609                        pkg.applicationInfo.dataDir = "/mismatched_uid/settings_"
5610                            + pkg.applicationInfo.uid + "/fs_"
5611                            + currentUid;
5612                        pkg.applicationInfo.nativeLibraryDir = pkg.applicationInfo.dataDir;
5613                        pkg.applicationInfo.nativeLibraryRootDir = pkg.applicationInfo.dataDir;
5614                        String msg = "Package " + pkg.packageName
5615                                + " has mismatched uid: "
5616                                + currentUid + " on disk, "
5617                                + pkg.applicationInfo.uid + " in settings";
5618                        // writer
5619                        synchronized (mPackages) {
5620                            mSettings.mReadMessages.append(msg);
5621                            mSettings.mReadMessages.append('\n');
5622                            uidError = true;
5623                            if (!pkgSetting.uidError) {
5624                                reportSettingsProblem(Log.ERROR, msg);
5625                            }
5626                        }
5627                    }
5628                }
5629                pkg.applicationInfo.dataDir = dataPath.getPath();
5630                if (mShouldRestoreconData) {
5631                    Slog.i(TAG, "SELinux relabeling of " + pkg.packageName + " issued.");
5632                    mInstaller.restoreconData(pkg.packageName, pkg.applicationInfo.seinfo,
5633                                pkg.applicationInfo.uid);
5634                }
5635            } else {
5636                if (DEBUG_PACKAGE_SCANNING) {
5637                    if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
5638                        Log.v(TAG, "Want this data dir: " + dataPath);
5639                }
5640                //invoke installer to do the actual installation
5641                int ret = createDataDirsLI(pkgName, pkg.applicationInfo.uid,
5642                                           pkg.applicationInfo.seinfo);
5643                if (ret < 0) {
5644                    // Error from installer
5645                    throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE,
5646                            "Unable to create data dirs [errorCode=" + ret + "]");
5647                }
5648
5649                if (dataPath.exists()) {
5650                    pkg.applicationInfo.dataDir = dataPath.getPath();
5651                } else {
5652                    Slog.w(TAG, "Unable to create data directory: " + dataPath);
5653                    pkg.applicationInfo.dataDir = null;
5654                }
5655            }
5656
5657            pkgSetting.uidError = uidError;
5658        }
5659
5660        final String path = scanFile.getPath();
5661        final String codePath = pkg.applicationInfo.getCodePath();
5662        final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting);
5663        if (isSystemApp(pkg) && !isUpdatedSystemApp(pkg)) {
5664            setBundledAppAbisAndRoots(pkg, pkgSetting);
5665
5666            // If we haven't found any native libraries for the app, check if it has
5667            // renderscript code. We'll need to force the app to 32 bit if it has
5668            // renderscript bitcode.
5669            if (pkg.applicationInfo.primaryCpuAbi == null
5670                    && pkg.applicationInfo.secondaryCpuAbi == null
5671                    && Build.SUPPORTED_64_BIT_ABIS.length >  0) {
5672                NativeLibraryHelper.Handle handle = null;
5673                try {
5674                    handle = NativeLibraryHelper.Handle.create(scanFile);
5675                    if (NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5676                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
5677                    }
5678                } catch (IOException ioe) {
5679                    Slog.w(TAG, "Error scanning system app : " + ioe);
5680                } finally {
5681                    IoUtils.closeQuietly(handle);
5682                }
5683            }
5684
5685            setNativeLibraryPaths(pkg);
5686        } else {
5687            // TODO: We can probably be smarter about this stuff. For installed apps,
5688            // we can calculate this information at install time once and for all. For
5689            // system apps, we can probably assume that this information doesn't change
5690            // after the first boot scan. As things stand, we do lots of unnecessary work.
5691
5692            // Give ourselves some initial paths; we'll come back for another
5693            // pass once we've determined ABI below.
5694            setNativeLibraryPaths(pkg);
5695
5696            final boolean isAsec = isForwardLocked(pkg) || isExternal(pkg);
5697            final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir;
5698            final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa;
5699
5700            NativeLibraryHelper.Handle handle = null;
5701            try {
5702                handle = NativeLibraryHelper.Handle.create(scanFile);
5703                // TODO(multiArch): This can be null for apps that didn't go through the
5704                // usual installation process. We can calculate it again, like we
5705                // do during install time.
5706                //
5707                // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally
5708                // unnecessary.
5709                final File nativeLibraryRoot = new File(nativeLibraryRootStr);
5710
5711                // Null out the abis so that they can be recalculated.
5712                pkg.applicationInfo.primaryCpuAbi = null;
5713                pkg.applicationInfo.secondaryCpuAbi = null;
5714                if (isMultiArch(pkg.applicationInfo)) {
5715                    // Warn if we've set an abiOverride for multi-lib packages..
5716                    // By definition, we need to copy both 32 and 64 bit libraries for
5717                    // such packages.
5718                    if (pkg.cpuAbiOverride != null
5719                            && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) {
5720                        Slog.w(TAG, "Ignoring abiOverride for multi arch application.");
5721                    }
5722
5723                    int abi32 = PackageManager.NO_NATIVE_LIBRARIES;
5724                    int abi64 = PackageManager.NO_NATIVE_LIBRARIES;
5725                    if (Build.SUPPORTED_32_BIT_ABIS.length > 0) {
5726                        if (isAsec) {
5727                            abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS);
5728                        } else {
5729                            abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5730                                    nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS,
5731                                    useIsaSpecificSubdirs);
5732                        }
5733                    }
5734
5735                    maybeThrowExceptionForMultiArchCopy(
5736                            "Error unpackaging 32 bit native libs for multiarch app.", abi32);
5737
5738                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0) {
5739                        if (isAsec) {
5740                            abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS);
5741                        } else {
5742                            abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5743                                    nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS,
5744                                    useIsaSpecificSubdirs);
5745                        }
5746                    }
5747
5748                    maybeThrowExceptionForMultiArchCopy(
5749                            "Error unpackaging 64 bit native libs for multiarch app.", abi64);
5750
5751                    if (abi64 >= 0) {
5752                        pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64];
5753                    }
5754
5755                    if (abi32 >= 0) {
5756                        final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32];
5757                        if (abi64 >= 0) {
5758                            pkg.applicationInfo.secondaryCpuAbi = abi;
5759                        } else {
5760                            pkg.applicationInfo.primaryCpuAbi = abi;
5761                        }
5762                    }
5763                } else {
5764                    String[] abiList = (cpuAbiOverride != null) ?
5765                            new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS;
5766
5767                    // Enable gross and lame hacks for apps that are built with old
5768                    // SDK tools. We must scan their APKs for renderscript bitcode and
5769                    // not launch them if it's present. Don't bother checking on devices
5770                    // that don't have 64 bit support.
5771                    boolean needsRenderScriptOverride = false;
5772                    if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null &&
5773                            NativeLibraryHelper.hasRenderscriptBitcode(handle)) {
5774                        abiList = Build.SUPPORTED_32_BIT_ABIS;
5775                        needsRenderScriptOverride = true;
5776                    }
5777
5778                    final int copyRet;
5779                    if (isAsec) {
5780                        copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList);
5781                    } else {
5782                        copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle,
5783                                nativeLibraryRoot, abiList, useIsaSpecificSubdirs);
5784                    }
5785
5786                    if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) {
5787                        throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5788                                "Error unpackaging native libs for app, errorCode=" + copyRet);
5789                    }
5790
5791                    if (copyRet >= 0) {
5792                        pkg.applicationInfo.primaryCpuAbi = abiList[copyRet];
5793                    } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) {
5794                        pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride;
5795                    } else if (needsRenderScriptOverride) {
5796                        pkg.applicationInfo.primaryCpuAbi = abiList[0];
5797                    }
5798                }
5799            } catch (IOException ioe) {
5800                Slog.e(TAG, "Unable to get canonical file " + ioe.toString());
5801            } finally {
5802                IoUtils.closeQuietly(handle);
5803            }
5804
5805            // Now that we've calculated the ABIs and determined if it's an internal app,
5806            // we will go ahead and populate the nativeLibraryPath.
5807            setNativeLibraryPaths(pkg);
5808
5809            if (DEBUG_INSTALL) Slog.i(TAG, "Linking native library dir for " + path);
5810            final int[] userIds = sUserManager.getUserIds();
5811            synchronized (mInstallLock) {
5812                // Create a native library symlink only if we have native libraries
5813                // and if the native libraries are 32 bit libraries. We do not provide
5814                // this symlink for 64 bit libraries.
5815                if (pkg.applicationInfo.primaryCpuAbi != null &&
5816                        !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
5817                    final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
5818                    for (int userId : userIds) {
5819                        if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
5820                            throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR,
5821                                    "Failed linking native library dir (user=" + userId + ")");
5822                        }
5823                    }
5824                }
5825            }
5826        }
5827
5828        // This is a special case for the "system" package, where the ABI is
5829        // dictated by the zygote configuration (and init.rc). We should keep track
5830        // of this ABI so that we can deal with "normal" applications that run under
5831        // the same UID correctly.
5832        if (mPlatformPackage == pkg) {
5833            pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ?
5834                    Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0];
5835        }
5836
5837        pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
5838        pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
5839        pkgSetting.cpuAbiOverrideString = cpuAbiOverride;
5840        // Copy the derived override back to the parsed package, so that we can
5841        // update the package settings accordingly.
5842        pkg.cpuAbiOverride = cpuAbiOverride;
5843
5844        if (DEBUG_ABI_SELECTION) {
5845            Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName
5846                    + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa="
5847                    + pkg.applicationInfo.nativeLibraryRootRequiresIsa);
5848        }
5849
5850        // Push the derived path down into PackageSettings so we know what to
5851        // clean up at uninstall time.
5852        pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir;
5853
5854        if (DEBUG_ABI_SELECTION) {
5855            Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" +
5856                    " primary=" + pkg.applicationInfo.primaryCpuAbi +
5857                    " secondary=" + pkg.applicationInfo.secondaryCpuAbi);
5858        }
5859
5860        if ((scanFlags&SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) {
5861            // We don't do this here during boot because we can do it all
5862            // at once after scanning all existing packages.
5863            //
5864            // We also do this *before* we perform dexopt on this package, so that
5865            // we can avoid redundant dexopts, and also to make sure we've got the
5866            // code and package path correct.
5867            adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages,
5868                    pkg, forceDex, (scanFlags & SCAN_DEFER_DEX) != 0);
5869        }
5870
5871        if ((scanFlags & SCAN_NO_DEX) == 0) {
5872            if (performDexOptLI(pkg, null /* instruction sets */, forceDex,
5873                    (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5874                throw new PackageManagerException(INSTALL_FAILED_DEXOPT, "scanPackageLI");
5875            }
5876        }
5877
5878        if (mFactoryTest && pkg.requestedPermissions.contains(
5879                android.Manifest.permission.FACTORY_TEST)) {
5880            pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST;
5881        }
5882
5883        ArrayList<PackageParser.Package> clientLibPkgs = null;
5884
5885        // writer
5886        synchronized (mPackages) {
5887            if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
5888                // Only system apps can add new shared libraries.
5889                if (pkg.libraryNames != null) {
5890                    for (int i=0; i<pkg.libraryNames.size(); i++) {
5891                        String name = pkg.libraryNames.get(i);
5892                        boolean allowed = false;
5893                        if (isUpdatedSystemApp(pkg)) {
5894                            // New library entries can only be added through the
5895                            // system image.  This is important to get rid of a lot
5896                            // of nasty edge cases: for example if we allowed a non-
5897                            // system update of the app to add a library, then uninstalling
5898                            // the update would make the library go away, and assumptions
5899                            // we made such as through app install filtering would now
5900                            // have allowed apps on the device which aren't compatible
5901                            // with it.  Better to just have the restriction here, be
5902                            // conservative, and create many fewer cases that can negatively
5903                            // impact the user experience.
5904                            final PackageSetting sysPs = mSettings
5905                                    .getDisabledSystemPkgLPr(pkg.packageName);
5906                            if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) {
5907                                for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) {
5908                                    if (name.equals(sysPs.pkg.libraryNames.get(j))) {
5909                                        allowed = true;
5910                                        allowed = true;
5911                                        break;
5912                                    }
5913                                }
5914                            }
5915                        } else {
5916                            allowed = true;
5917                        }
5918                        if (allowed) {
5919                            if (!mSharedLibraries.containsKey(name)) {
5920                                mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName));
5921                            } else if (!name.equals(pkg.packageName)) {
5922                                Slog.w(TAG, "Package " + pkg.packageName + " library "
5923                                        + name + " already exists; skipping");
5924                            }
5925                        } else {
5926                            Slog.w(TAG, "Package " + pkg.packageName + " declares lib "
5927                                    + name + " that is not declared on system image; skipping");
5928                        }
5929                    }
5930                    if ((scanFlags&SCAN_BOOTING) == 0) {
5931                        // If we are not booting, we need to update any applications
5932                        // that are clients of our shared library.  If we are booting,
5933                        // this will all be done once the scan is complete.
5934                        clientLibPkgs = updateAllSharedLibrariesLPw(pkg);
5935                    }
5936                }
5937            }
5938        }
5939
5940        // We also need to dexopt any apps that are dependent on this library.  Note that
5941        // if these fail, we should abort the install since installing the library will
5942        // result in some apps being broken.
5943        if (clientLibPkgs != null) {
5944            if ((scanFlags & SCAN_NO_DEX) == 0) {
5945                for (int i = 0; i < clientLibPkgs.size(); i++) {
5946                    PackageParser.Package clientPkg = clientLibPkgs.get(i);
5947                    if (performDexOptLI(clientPkg, null /* instruction sets */, forceDex,
5948                            (scanFlags & SCAN_DEFER_DEX) != 0, false) == DEX_OPT_FAILED) {
5949                        throw new PackageManagerException(INSTALL_FAILED_DEXOPT,
5950                                "scanPackageLI failed to dexopt clientLibPkgs");
5951                    }
5952                }
5953            }
5954        }
5955
5956        // Request the ActivityManager to kill the process(only for existing packages)
5957        // so that we do not end up in a confused state while the user is still using the older
5958        // version of the application while the new one gets installed.
5959        if ((scanFlags & SCAN_REPLACING) != 0) {
5960            killApplication(pkg.applicationInfo.packageName,
5961                        pkg.applicationInfo.uid, "update pkg");
5962        }
5963
5964        // Also need to kill any apps that are dependent on the library.
5965        if (clientLibPkgs != null) {
5966            for (int i=0; i<clientLibPkgs.size(); i++) {
5967                PackageParser.Package clientPkg = clientLibPkgs.get(i);
5968                killApplication(clientPkg.applicationInfo.packageName,
5969                        clientPkg.applicationInfo.uid, "update lib");
5970            }
5971        }
5972
5973        // writer
5974        synchronized (mPackages) {
5975            // We don't expect installation to fail beyond this point
5976
5977            // Add the new setting to mSettings
5978            mSettings.insertPackageSettingLPw(pkgSetting, pkg);
5979            // Add the new setting to mPackages
5980            mPackages.put(pkg.applicationInfo.packageName, pkg);
5981            // Make sure we don't accidentally delete its data.
5982            final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator();
5983            while (iter.hasNext()) {
5984                PackageCleanItem item = iter.next();
5985                if (pkgName.equals(item.packageName)) {
5986                    iter.remove();
5987                }
5988            }
5989
5990            // Take care of first install / last update times.
5991            if (currentTime != 0) {
5992                if (pkgSetting.firstInstallTime == 0) {
5993                    pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime;
5994                } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) {
5995                    pkgSetting.lastUpdateTime = currentTime;
5996                }
5997            } else if (pkgSetting.firstInstallTime == 0) {
5998                // We need *something*.  Take time time stamp of the file.
5999                pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime;
6000            } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) {
6001                if (scanFileTime != pkgSetting.timeStamp) {
6002                    // A package on the system image has changed; consider this
6003                    // to be an update.
6004                    pkgSetting.lastUpdateTime = scanFileTime;
6005                }
6006            }
6007
6008            // Add the package's KeySets to the global KeySetManagerService
6009            KeySetManagerService ksms = mSettings.mKeySetManagerService;
6010            try {
6011                // Old KeySetData no longer valid.
6012                ksms.removeAppKeySetDataLPw(pkg.packageName);
6013                ksms.addSigningKeySetToPackageLPw(pkg.packageName, pkg.mSigningKeys);
6014                if (pkg.mKeySetMapping != null) {
6015                    for (Map.Entry<String, ArraySet<PublicKey>> entry :
6016                            pkg.mKeySetMapping.entrySet()) {
6017                        if (entry.getValue() != null) {
6018                            ksms.addDefinedKeySetToPackageLPw(pkg.packageName,
6019                                                          entry.getValue(), entry.getKey());
6020                        }
6021                    }
6022                    if (pkg.mUpgradeKeySets != null) {
6023                        for (String upgradeAlias : pkg.mUpgradeKeySets) {
6024                            ksms.addUpgradeKeySetToPackageLPw(pkg.packageName, upgradeAlias);
6025                        }
6026                    }
6027                }
6028            } catch (NullPointerException e) {
6029                Slog.e(TAG, "Could not add KeySet to " + pkg.packageName, e);
6030            } catch (IllegalArgumentException e) {
6031                Slog.e(TAG, "Could not add KeySet to malformed package" + pkg.packageName, e);
6032            }
6033
6034            int N = pkg.providers.size();
6035            StringBuilder r = null;
6036            int i;
6037            for (i=0; i<N; i++) {
6038                PackageParser.Provider p = pkg.providers.get(i);
6039                p.info.processName = fixProcessName(pkg.applicationInfo.processName,
6040                        p.info.processName, pkg.applicationInfo.uid);
6041                mProviders.addProvider(p);
6042                p.syncable = p.info.isSyncable;
6043                if (p.info.authority != null) {
6044                    String names[] = p.info.authority.split(";");
6045                    p.info.authority = null;
6046                    for (int j = 0; j < names.length; j++) {
6047                        if (j == 1 && p.syncable) {
6048                            // We only want the first authority for a provider to possibly be
6049                            // syncable, so if we already added this provider using a different
6050                            // authority clear the syncable flag. We copy the provider before
6051                            // changing it because the mProviders object contains a reference
6052                            // to a provider that we don't want to change.
6053                            // Only do this for the second authority since the resulting provider
6054                            // object can be the same for all future authorities for this provider.
6055                            p = new PackageParser.Provider(p);
6056                            p.syncable = false;
6057                        }
6058                        if (!mProvidersByAuthority.containsKey(names[j])) {
6059                            mProvidersByAuthority.put(names[j], p);
6060                            if (p.info.authority == null) {
6061                                p.info.authority = names[j];
6062                            } else {
6063                                p.info.authority = p.info.authority + ";" + names[j];
6064                            }
6065                            if (DEBUG_PACKAGE_SCANNING) {
6066                                if ((parseFlags & PackageParser.PARSE_CHATTY) != 0)
6067                                    Log.d(TAG, "Registered content provider: " + names[j]
6068                                            + ", className = " + p.info.name + ", isSyncable = "
6069                                            + p.info.isSyncable);
6070                            }
6071                        } else {
6072                            PackageParser.Provider other = mProvidersByAuthority.get(names[j]);
6073                            Slog.w(TAG, "Skipping provider name " + names[j] +
6074                                    " (in package " + pkg.applicationInfo.packageName +
6075                                    "): name already used by "
6076                                    + ((other != null && other.getComponentName() != null)
6077                                            ? other.getComponentName().getPackageName() : "?"));
6078                        }
6079                    }
6080                }
6081                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6082                    if (r == null) {
6083                        r = new StringBuilder(256);
6084                    } else {
6085                        r.append(' ');
6086                    }
6087                    r.append(p.info.name);
6088                }
6089            }
6090            if (r != null) {
6091                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Providers: " + r);
6092            }
6093
6094            N = pkg.services.size();
6095            r = null;
6096            for (i=0; i<N; i++) {
6097                PackageParser.Service s = pkg.services.get(i);
6098                s.info.processName = fixProcessName(pkg.applicationInfo.processName,
6099                        s.info.processName, pkg.applicationInfo.uid);
6100                mServices.addService(s);
6101                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6102                    if (r == null) {
6103                        r = new StringBuilder(256);
6104                    } else {
6105                        r.append(' ');
6106                    }
6107                    r.append(s.info.name);
6108                }
6109            }
6110            if (r != null) {
6111                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Services: " + r);
6112            }
6113
6114            N = pkg.receivers.size();
6115            r = null;
6116            for (i=0; i<N; i++) {
6117                PackageParser.Activity a = pkg.receivers.get(i);
6118                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6119                        a.info.processName, pkg.applicationInfo.uid);
6120                mReceivers.addActivity(a, "receiver");
6121                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6122                    if (r == null) {
6123                        r = new StringBuilder(256);
6124                    } else {
6125                        r.append(' ');
6126                    }
6127                    r.append(a.info.name);
6128                }
6129            }
6130            if (r != null) {
6131                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Receivers: " + r);
6132            }
6133
6134            N = pkg.activities.size();
6135            r = null;
6136            for (i=0; i<N; i++) {
6137                PackageParser.Activity a = pkg.activities.get(i);
6138                a.info.processName = fixProcessName(pkg.applicationInfo.processName,
6139                        a.info.processName, pkg.applicationInfo.uid);
6140                mActivities.addActivity(a, "activity");
6141                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6142                    if (r == null) {
6143                        r = new StringBuilder(256);
6144                    } else {
6145                        r.append(' ');
6146                    }
6147                    r.append(a.info.name);
6148                }
6149            }
6150            if (r != null) {
6151                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Activities: " + r);
6152            }
6153
6154            N = pkg.permissionGroups.size();
6155            r = null;
6156            for (i=0; i<N; i++) {
6157                PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i);
6158                PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name);
6159                if (cur == null) {
6160                    mPermissionGroups.put(pg.info.name, pg);
6161                    if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6162                        if (r == null) {
6163                            r = new StringBuilder(256);
6164                        } else {
6165                            r.append(' ');
6166                        }
6167                        r.append(pg.info.name);
6168                    }
6169                } else {
6170                    Slog.w(TAG, "Permission group " + pg.info.name + " from package "
6171                            + pg.info.packageName + " ignored: original from "
6172                            + cur.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("DUP:");
6180                        r.append(pg.info.name);
6181                    }
6182                }
6183            }
6184            if (r != null) {
6185                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permission Groups: " + r);
6186            }
6187
6188            N = pkg.permissions.size();
6189            r = null;
6190            for (i=0; i<N; i++) {
6191                PackageParser.Permission p = pkg.permissions.get(i);
6192                HashMap<String, BasePermission> permissionMap =
6193                        p.tree ? mSettings.mPermissionTrees
6194                        : mSettings.mPermissions;
6195                p.group = mPermissionGroups.get(p.info.group);
6196                if (p.info.group == null || p.group != null) {
6197                    BasePermission bp = permissionMap.get(p.info.name);
6198
6199                    // Allow system apps to redefine non-system permissions
6200                    if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) {
6201                        final boolean currentOwnerIsSystem = (bp.perm != null
6202                                && isSystemApp(bp.perm.owner));
6203                        if (isSystemApp(p.owner)) {
6204                            if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) {
6205                                // It's a built-in permission and no owner, take ownership now
6206                                bp.packageSetting = pkgSetting;
6207                                bp.perm = p;
6208                                bp.uid = pkg.applicationInfo.uid;
6209                                bp.sourcePackage = p.info.packageName;
6210                            } else if (!currentOwnerIsSystem) {
6211                                String msg = "New decl " + p.owner + " of permission  "
6212                                        + p.info.name + " is system; overriding " + bp.sourcePackage;
6213                                reportSettingsProblem(Log.WARN, msg);
6214                                bp = null;
6215                            }
6216                        }
6217                    }
6218
6219                    if (bp == null) {
6220                        bp = new BasePermission(p.info.name, p.info.packageName,
6221                                BasePermission.TYPE_NORMAL);
6222                        permissionMap.put(p.info.name, bp);
6223                    }
6224
6225                    if (bp.perm == null) {
6226                        if (bp.sourcePackage == null
6227                                || bp.sourcePackage.equals(p.info.packageName)) {
6228                            BasePermission tree = findPermissionTreeLP(p.info.name);
6229                            if (tree == null
6230                                    || tree.sourcePackage.equals(p.info.packageName)) {
6231                                bp.packageSetting = pkgSetting;
6232                                bp.perm = p;
6233                                bp.uid = pkg.applicationInfo.uid;
6234                                bp.sourcePackage = p.info.packageName;
6235                                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6236                                    if (r == null) {
6237                                        r = new StringBuilder(256);
6238                                    } else {
6239                                        r.append(' ');
6240                                    }
6241                                    r.append(p.info.name);
6242                                }
6243                            } else {
6244                                Slog.w(TAG, "Permission " + p.info.name + " from package "
6245                                        + p.info.packageName + " ignored: base tree "
6246                                        + tree.name + " is from package "
6247                                        + tree.sourcePackage);
6248                            }
6249                        } else {
6250                            Slog.w(TAG, "Permission " + p.info.name + " from package "
6251                                    + p.info.packageName + " ignored: original from "
6252                                    + bp.sourcePackage);
6253                        }
6254                    } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6255                        if (r == null) {
6256                            r = new StringBuilder(256);
6257                        } else {
6258                            r.append(' ');
6259                        }
6260                        r.append("DUP:");
6261                        r.append(p.info.name);
6262                    }
6263                    if (bp.perm == p) {
6264                        bp.protectionLevel = p.info.protectionLevel;
6265                    }
6266                } else {
6267                    Slog.w(TAG, "Permission " + p.info.name + " from package "
6268                            + p.info.packageName + " ignored: no group "
6269                            + p.group);
6270                }
6271            }
6272            if (r != null) {
6273                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Permissions: " + r);
6274            }
6275
6276            N = pkg.instrumentation.size();
6277            r = null;
6278            for (i=0; i<N; i++) {
6279                PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6280                a.info.packageName = pkg.applicationInfo.packageName;
6281                a.info.sourceDir = pkg.applicationInfo.sourceDir;
6282                a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir;
6283                a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs;
6284                a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs;
6285                a.info.dataDir = pkg.applicationInfo.dataDir;
6286
6287                // TODO: Update instrumentation.nativeLibraryDir as well ? Does it
6288                // need other information about the application, like the ABI and what not ?
6289                a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir;
6290                mInstrumentation.put(a.getComponentName(), a);
6291                if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) {
6292                    if (r == null) {
6293                        r = new StringBuilder(256);
6294                    } else {
6295                        r.append(' ');
6296                    }
6297                    r.append(a.info.name);
6298                }
6299            }
6300            if (r != null) {
6301                if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, "  Instrumentation: " + r);
6302            }
6303
6304            if (pkg.protectedBroadcasts != null) {
6305                N = pkg.protectedBroadcasts.size();
6306                for (i=0; i<N; i++) {
6307                    mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i));
6308                }
6309            }
6310
6311            pkgSetting.setTimeStamp(scanFileTime);
6312
6313            // Create idmap files for pairs of (packages, overlay packages).
6314            // Note: "android", ie framework-res.apk, is handled by native layers.
6315            if (pkg.mOverlayTarget != null) {
6316                // This is an overlay package.
6317                if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) {
6318                    if (!mOverlays.containsKey(pkg.mOverlayTarget)) {
6319                        mOverlays.put(pkg.mOverlayTarget,
6320                                new HashMap<String, PackageParser.Package>());
6321                    }
6322                    HashMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget);
6323                    map.put(pkg.packageName, pkg);
6324                    PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget);
6325                    if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) {
6326                        throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE,
6327                                "scanPackageLI failed to createIdmap");
6328                    }
6329                }
6330            } else if (mOverlays.containsKey(pkg.packageName) &&
6331                    !pkg.packageName.equals("android")) {
6332                // This is a regular package, with one or more known overlay packages.
6333                createIdmapsForPackageLI(pkg);
6334            }
6335        }
6336
6337        return pkg;
6338    }
6339
6340    /**
6341     * Adjusts ABIs for a set of packages belonging to a shared user so that they all match.
6342     * i.e, so that all packages can be run inside a single process if required.
6343     *
6344     * Optionally, callers can pass in a parsed package via {@code newPackage} in which case
6345     * this function will either try and make the ABI for all packages in {@code packagesForUser}
6346     * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match
6347     * the ABI selected for {@code packagesForUser}. This variant is used when installing or
6348     * updating a package that belongs to a shared user.
6349     *
6350     * NOTE: We currently only match for the primary CPU abi string. Matching the secondary
6351     * adds unnecessary complexity.
6352     */
6353    private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser,
6354            PackageParser.Package scannedPackage, boolean forceDexOpt, boolean deferDexOpt) {
6355        String requiredInstructionSet = null;
6356        if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) {
6357            requiredInstructionSet = VMRuntime.getInstructionSet(
6358                     scannedPackage.applicationInfo.primaryCpuAbi);
6359        }
6360
6361        PackageSetting requirer = null;
6362        for (PackageSetting ps : packagesForUser) {
6363            // If packagesForUser contains scannedPackage, we skip it. This will happen
6364            // when scannedPackage is an update of an existing package. Without this check,
6365            // we will never be able to change the ABI of any package belonging to a shared
6366            // user, even if it's compatible with other packages.
6367            if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6368                if (ps.primaryCpuAbiString == null) {
6369                    continue;
6370                }
6371
6372                final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString);
6373                if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) {
6374                    // We have a mismatch between instruction sets (say arm vs arm64) warn about
6375                    // this but there's not much we can do.
6376                    String errorMessage = "Instruction set mismatch, "
6377                            + ((requirer == null) ? "[caller]" : requirer)
6378                            + " requires " + requiredInstructionSet + " whereas " + ps
6379                            + " requires " + instructionSet;
6380                    Slog.w(TAG, errorMessage);
6381                }
6382
6383                if (requiredInstructionSet == null) {
6384                    requiredInstructionSet = instructionSet;
6385                    requirer = ps;
6386                }
6387            }
6388        }
6389
6390        if (requiredInstructionSet != null) {
6391            String adjustedAbi;
6392            if (requirer != null) {
6393                // requirer != null implies that either scannedPackage was null or that scannedPackage
6394                // did not require an ABI, in which case we have to adjust scannedPackage to match
6395                // the ABI of the set (which is the same as requirer's ABI)
6396                adjustedAbi = requirer.primaryCpuAbiString;
6397                if (scannedPackage != null) {
6398                    scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi;
6399                }
6400            } else {
6401                // requirer == null implies that we're updating all ABIs in the set to
6402                // match scannedPackage.
6403                adjustedAbi =  scannedPackage.applicationInfo.primaryCpuAbi;
6404            }
6405
6406            for (PackageSetting ps : packagesForUser) {
6407                if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) {
6408                    if (ps.primaryCpuAbiString != null) {
6409                        continue;
6410                    }
6411
6412                    ps.primaryCpuAbiString = adjustedAbi;
6413                    if (ps.pkg != null && ps.pkg.applicationInfo != null) {
6414                        ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi;
6415                        Slog.i(TAG, "Adjusting ABI for : " + ps.name + " to " + adjustedAbi);
6416
6417                        if (performDexOptLI(ps.pkg, null /* instruction sets */, forceDexOpt,
6418                                deferDexOpt, true) == DEX_OPT_FAILED) {
6419                            ps.primaryCpuAbiString = null;
6420                            ps.pkg.applicationInfo.primaryCpuAbi = null;
6421                            return;
6422                        } else {
6423                            mInstaller.rmdex(ps.codePathString,
6424                                             getDexCodeInstructionSet(getPreferredInstructionSet()));
6425                        }
6426                    }
6427                }
6428            }
6429        }
6430    }
6431
6432    private void setUpCustomResolverActivity(PackageParser.Package pkg) {
6433        synchronized (mPackages) {
6434            mResolverReplaced = true;
6435            // Set up information for custom user intent resolution activity.
6436            mResolveActivity.applicationInfo = pkg.applicationInfo;
6437            mResolveActivity.name = mCustomResolverComponentName.getClassName();
6438            mResolveActivity.packageName = pkg.applicationInfo.packageName;
6439            mResolveActivity.processName = pkg.applicationInfo.packageName;
6440            mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE;
6441            mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS |
6442                    ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS;
6443            mResolveActivity.theme = 0;
6444            mResolveActivity.exported = true;
6445            mResolveActivity.enabled = true;
6446            mResolveInfo.activityInfo = mResolveActivity;
6447            mResolveInfo.priority = 0;
6448            mResolveInfo.preferredOrder = 0;
6449            mResolveInfo.match = 0;
6450            mResolveComponentName = mCustomResolverComponentName;
6451            Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " +
6452                    mResolveComponentName);
6453        }
6454    }
6455
6456    private static String calculateBundledApkRoot(final String codePathString) {
6457        final File codePath = new File(codePathString);
6458        final File codeRoot;
6459        if (FileUtils.contains(Environment.getRootDirectory(), codePath)) {
6460            codeRoot = Environment.getRootDirectory();
6461        } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) {
6462            codeRoot = Environment.getOemDirectory();
6463        } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) {
6464            codeRoot = Environment.getVendorDirectory();
6465        } else {
6466            // Unrecognized code path; take its top real segment as the apk root:
6467            // e.g. /something/app/blah.apk => /something
6468            try {
6469                File f = codePath.getCanonicalFile();
6470                File parent = f.getParentFile();    // non-null because codePath is a file
6471                File tmp;
6472                while ((tmp = parent.getParentFile()) != null) {
6473                    f = parent;
6474                    parent = tmp;
6475                }
6476                codeRoot = f;
6477                Slog.w(TAG, "Unrecognized code path "
6478                        + codePath + " - using " + codeRoot);
6479            } catch (IOException e) {
6480                // Can't canonicalize the code path -- shenanigans?
6481                Slog.w(TAG, "Can't canonicalize code path " + codePath);
6482                return Environment.getRootDirectory().getPath();
6483            }
6484        }
6485        return codeRoot.getPath();
6486    }
6487
6488    /**
6489     * Derive and set the location of native libraries for the given package,
6490     * which varies depending on where and how the package was installed.
6491     */
6492    private void setNativeLibraryPaths(PackageParser.Package pkg) {
6493        final ApplicationInfo info = pkg.applicationInfo;
6494        final String codePath = pkg.codePath;
6495        final File codeFile = new File(codePath);
6496        final boolean bundledApp = isSystemApp(info) && !isUpdatedSystemApp(info);
6497        final boolean asecApp = isForwardLocked(info) || isExternal(info);
6498
6499        info.nativeLibraryRootDir = null;
6500        info.nativeLibraryRootRequiresIsa = false;
6501        info.nativeLibraryDir = null;
6502        info.secondaryNativeLibraryDir = null;
6503
6504        if (isApkFile(codeFile)) {
6505            // Monolithic install
6506            if (bundledApp) {
6507                // If "/system/lib64/apkname" exists, assume that is the per-package
6508                // native library directory to use; otherwise use "/system/lib/apkname".
6509                final String apkRoot = calculateBundledApkRoot(info.sourceDir);
6510                final boolean is64Bit = VMRuntime.is64BitInstructionSet(
6511                        getPrimaryInstructionSet(info));
6512
6513                // This is a bundled system app so choose the path based on the ABI.
6514                // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this
6515                // is just the default path.
6516                final String apkName = deriveCodePathName(codePath);
6517                final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME;
6518                info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir,
6519                        apkName).getAbsolutePath();
6520
6521                if (info.secondaryCpuAbi != null) {
6522                    final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME;
6523                    info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot),
6524                            secondaryLibDir, apkName).getAbsolutePath();
6525                }
6526            } else if (asecApp) {
6527                info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME)
6528                        .getAbsolutePath();
6529            } else {
6530                final String apkName = deriveCodePathName(codePath);
6531                info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName)
6532                        .getAbsolutePath();
6533            }
6534
6535            info.nativeLibraryRootRequiresIsa = false;
6536            info.nativeLibraryDir = info.nativeLibraryRootDir;
6537        } else {
6538            // Cluster install
6539            info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath();
6540            info.nativeLibraryRootRequiresIsa = true;
6541
6542            info.nativeLibraryDir = new File(info.nativeLibraryRootDir,
6543                    getPrimaryInstructionSet(info)).getAbsolutePath();
6544
6545            if (info.secondaryCpuAbi != null) {
6546                info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir,
6547                        VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath();
6548            }
6549        }
6550    }
6551
6552    /**
6553     * Calculate the abis and roots for a bundled app. These can uniquely
6554     * be determined from the contents of the system partition, i.e whether
6555     * it contains 64 or 32 bit shared libraries etc. We do not validate any
6556     * of this information, and instead assume that the system was built
6557     * sensibly.
6558     */
6559    private void setBundledAppAbisAndRoots(PackageParser.Package pkg,
6560                                           PackageSetting pkgSetting) {
6561        final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath());
6562
6563        // If "/system/lib64/apkname" exists, assume that is the per-package
6564        // native library directory to use; otherwise use "/system/lib/apkname".
6565        final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir);
6566        setBundledAppAbi(pkg, apkRoot, apkName);
6567        // pkgSetting might be null during rescan following uninstall of updates
6568        // to a bundled app, so accommodate that possibility.  The settings in
6569        // that case will be established later from the parsed package.
6570        //
6571        // If the settings aren't null, sync them up with what we've just derived.
6572        // note that apkRoot isn't stored in the package settings.
6573        if (pkgSetting != null) {
6574            pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi;
6575            pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi;
6576        }
6577    }
6578
6579    /**
6580     * Deduces the ABI of a bundled app and sets the relevant fields on the
6581     * parsed pkg object.
6582     *
6583     * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem}
6584     *        under which system libraries are installed.
6585     * @param apkName the name of the installed package.
6586     */
6587    private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) {
6588        final File codeFile = new File(pkg.codePath);
6589
6590        final boolean has64BitLibs;
6591        final boolean has32BitLibs;
6592        if (isApkFile(codeFile)) {
6593            // Monolithic install
6594            has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists();
6595            has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists();
6596        } else {
6597            // Cluster install
6598            final File rootDir = new File(codeFile, LIB_DIR_NAME);
6599            if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS)
6600                    && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) {
6601                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]);
6602                has64BitLibs = (new File(rootDir, isa)).exists();
6603            } else {
6604                has64BitLibs = false;
6605            }
6606            if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS)
6607                    && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) {
6608                final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]);
6609                has32BitLibs = (new File(rootDir, isa)).exists();
6610            } else {
6611                has32BitLibs = false;
6612            }
6613        }
6614
6615        if (has64BitLibs && !has32BitLibs) {
6616            // The package has 64 bit libs, but not 32 bit libs. Its primary
6617            // ABI should be 64 bit. We can safely assume here that the bundled
6618            // native libraries correspond to the most preferred ABI in the list.
6619
6620            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6621            pkg.applicationInfo.secondaryCpuAbi = null;
6622        } else if (has32BitLibs && !has64BitLibs) {
6623            // The package has 32 bit libs but not 64 bit libs. Its primary
6624            // ABI should be 32 bit.
6625
6626            pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6627            pkg.applicationInfo.secondaryCpuAbi = null;
6628        } else if (has32BitLibs && has64BitLibs) {
6629            // The application has both 64 and 32 bit bundled libraries. We check
6630            // here that the app declares multiArch support, and warn if it doesn't.
6631            //
6632            // We will be lenient here and record both ABIs. The primary will be the
6633            // ABI that's higher on the list, i.e, a device that's configured to prefer
6634            // 64 bit apps will see a 64 bit primary ABI,
6635
6636            if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) {
6637                Slog.e(TAG, "Package: " + pkg + " has multiple bundled libs, but is not multiarch.");
6638            }
6639
6640            if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) {
6641                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6642                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6643            } else {
6644                pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0];
6645                pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0];
6646            }
6647        } else {
6648            pkg.applicationInfo.primaryCpuAbi = null;
6649            pkg.applicationInfo.secondaryCpuAbi = null;
6650        }
6651    }
6652
6653    private void killApplication(String pkgName, int appId, String reason) {
6654        // Request the ActivityManager to kill the process(only for existing packages)
6655        // so that we do not end up in a confused state while the user is still using the older
6656        // version of the application while the new one gets installed.
6657        IActivityManager am = ActivityManagerNative.getDefault();
6658        if (am != null) {
6659            try {
6660                am.killApplicationWithAppId(pkgName, appId, reason);
6661            } catch (RemoteException e) {
6662            }
6663        }
6664    }
6665
6666    void removePackageLI(PackageSetting ps, boolean chatty) {
6667        if (DEBUG_INSTALL) {
6668            if (chatty)
6669                Log.d(TAG, "Removing package " + ps.name);
6670        }
6671
6672        // writer
6673        synchronized (mPackages) {
6674            mPackages.remove(ps.name);
6675            final PackageParser.Package pkg = ps.pkg;
6676            if (pkg != null) {
6677                cleanPackageDataStructuresLILPw(pkg, chatty);
6678            }
6679        }
6680    }
6681
6682    void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) {
6683        if (DEBUG_INSTALL) {
6684            if (chatty)
6685                Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName);
6686        }
6687
6688        // writer
6689        synchronized (mPackages) {
6690            mPackages.remove(pkg.applicationInfo.packageName);
6691            cleanPackageDataStructuresLILPw(pkg, chatty);
6692        }
6693    }
6694
6695    void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) {
6696        int N = pkg.providers.size();
6697        StringBuilder r = null;
6698        int i;
6699        for (i=0; i<N; i++) {
6700            PackageParser.Provider p = pkg.providers.get(i);
6701            mProviders.removeProvider(p);
6702            if (p.info.authority == null) {
6703
6704                /* There was another ContentProvider with this authority when
6705                 * this app was installed so this authority is null,
6706                 * Ignore it as we don't have to unregister the provider.
6707                 */
6708                continue;
6709            }
6710            String names[] = p.info.authority.split(";");
6711            for (int j = 0; j < names.length; j++) {
6712                if (mProvidersByAuthority.get(names[j]) == p) {
6713                    mProvidersByAuthority.remove(names[j]);
6714                    if (DEBUG_REMOVE) {
6715                        if (chatty)
6716                            Log.d(TAG, "Unregistered content provider: " + names[j]
6717                                    + ", className = " + p.info.name + ", isSyncable = "
6718                                    + p.info.isSyncable);
6719                    }
6720                }
6721            }
6722            if (DEBUG_REMOVE && chatty) {
6723                if (r == null) {
6724                    r = new StringBuilder(256);
6725                } else {
6726                    r.append(' ');
6727                }
6728                r.append(p.info.name);
6729            }
6730        }
6731        if (r != null) {
6732            if (DEBUG_REMOVE) Log.d(TAG, "  Providers: " + r);
6733        }
6734
6735        N = pkg.services.size();
6736        r = null;
6737        for (i=0; i<N; i++) {
6738            PackageParser.Service s = pkg.services.get(i);
6739            mServices.removeService(s);
6740            if (chatty) {
6741                if (r == null) {
6742                    r = new StringBuilder(256);
6743                } else {
6744                    r.append(' ');
6745                }
6746                r.append(s.info.name);
6747            }
6748        }
6749        if (r != null) {
6750            if (DEBUG_REMOVE) Log.d(TAG, "  Services: " + r);
6751        }
6752
6753        N = pkg.receivers.size();
6754        r = null;
6755        for (i=0; i<N; i++) {
6756            PackageParser.Activity a = pkg.receivers.get(i);
6757            mReceivers.removeActivity(a, "receiver");
6758            if (DEBUG_REMOVE && chatty) {
6759                if (r == null) {
6760                    r = new StringBuilder(256);
6761                } else {
6762                    r.append(' ');
6763                }
6764                r.append(a.info.name);
6765            }
6766        }
6767        if (r != null) {
6768            if (DEBUG_REMOVE) Log.d(TAG, "  Receivers: " + r);
6769        }
6770
6771        N = pkg.activities.size();
6772        r = null;
6773        for (i=0; i<N; i++) {
6774            PackageParser.Activity a = pkg.activities.get(i);
6775            mActivities.removeActivity(a, "activity");
6776            if (DEBUG_REMOVE && chatty) {
6777                if (r == null) {
6778                    r = new StringBuilder(256);
6779                } else {
6780                    r.append(' ');
6781                }
6782                r.append(a.info.name);
6783            }
6784        }
6785        if (r != null) {
6786            if (DEBUG_REMOVE) Log.d(TAG, "  Activities: " + r);
6787        }
6788
6789        N = pkg.permissions.size();
6790        r = null;
6791        for (i=0; i<N; i++) {
6792            PackageParser.Permission p = pkg.permissions.get(i);
6793            BasePermission bp = mSettings.mPermissions.get(p.info.name);
6794            if (bp == null) {
6795                bp = mSettings.mPermissionTrees.get(p.info.name);
6796            }
6797            if (bp != null && bp.perm == p) {
6798                bp.perm = null;
6799                if (DEBUG_REMOVE && chatty) {
6800                    if (r == null) {
6801                        r = new StringBuilder(256);
6802                    } else {
6803                        r.append(' ');
6804                    }
6805                    r.append(p.info.name);
6806                }
6807            }
6808            if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6809                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(p.info.name);
6810                if (appOpPerms != null) {
6811                    appOpPerms.remove(pkg.packageName);
6812                }
6813            }
6814        }
6815        if (r != null) {
6816            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6817        }
6818
6819        N = pkg.requestedPermissions.size();
6820        r = null;
6821        for (i=0; i<N; i++) {
6822            String perm = pkg.requestedPermissions.get(i);
6823            BasePermission bp = mSettings.mPermissions.get(perm);
6824            if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
6825                ArraySet<String> appOpPerms = mAppOpPermissionPackages.get(perm);
6826                if (appOpPerms != null) {
6827                    appOpPerms.remove(pkg.packageName);
6828                    if (appOpPerms.isEmpty()) {
6829                        mAppOpPermissionPackages.remove(perm);
6830                    }
6831                }
6832            }
6833        }
6834        if (r != null) {
6835            if (DEBUG_REMOVE) Log.d(TAG, "  Permissions: " + r);
6836        }
6837
6838        N = pkg.instrumentation.size();
6839        r = null;
6840        for (i=0; i<N; i++) {
6841            PackageParser.Instrumentation a = pkg.instrumentation.get(i);
6842            mInstrumentation.remove(a.getComponentName());
6843            if (DEBUG_REMOVE && chatty) {
6844                if (r == null) {
6845                    r = new StringBuilder(256);
6846                } else {
6847                    r.append(' ');
6848                }
6849                r.append(a.info.name);
6850            }
6851        }
6852        if (r != null) {
6853            if (DEBUG_REMOVE) Log.d(TAG, "  Instrumentation: " + r);
6854        }
6855
6856        r = null;
6857        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) {
6858            // Only system apps can hold shared libraries.
6859            if (pkg.libraryNames != null) {
6860                for (i=0; i<pkg.libraryNames.size(); i++) {
6861                    String name = pkg.libraryNames.get(i);
6862                    SharedLibraryEntry cur = mSharedLibraries.get(name);
6863                    if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) {
6864                        mSharedLibraries.remove(name);
6865                        if (DEBUG_REMOVE && chatty) {
6866                            if (r == null) {
6867                                r = new StringBuilder(256);
6868                            } else {
6869                                r.append(' ');
6870                            }
6871                            r.append(name);
6872                        }
6873                    }
6874                }
6875            }
6876        }
6877        if (r != null) {
6878            if (DEBUG_REMOVE) Log.d(TAG, "  Libraries: " + r);
6879        }
6880    }
6881
6882    private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) {
6883        for (int i=pkgInfo.permissions.size()-1; i>=0; i--) {
6884            if (pkgInfo.permissions.get(i).info.name.equals(perm)) {
6885                return true;
6886            }
6887        }
6888        return false;
6889    }
6890
6891    static final int UPDATE_PERMISSIONS_ALL = 1<<0;
6892    static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1;
6893    static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2;
6894
6895    private void updatePermissionsLPw(String changingPkg,
6896            PackageParser.Package pkgInfo, int flags) {
6897        // Make sure there are no dangling permission trees.
6898        Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator();
6899        while (it.hasNext()) {
6900            final BasePermission bp = it.next();
6901            if (bp.packageSetting == null) {
6902                // We may not yet have parsed the package, so just see if
6903                // we still know about its settings.
6904                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6905            }
6906            if (bp.packageSetting == null) {
6907                Slog.w(TAG, "Removing dangling permission tree: " + bp.name
6908                        + " from package " + bp.sourcePackage);
6909                it.remove();
6910            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6911                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6912                    Slog.i(TAG, "Removing old permission tree: " + bp.name
6913                            + " from package " + bp.sourcePackage);
6914                    flags |= UPDATE_PERMISSIONS_ALL;
6915                    it.remove();
6916                }
6917            }
6918        }
6919
6920        // Make sure all dynamic permissions have been assigned to a package,
6921        // and make sure there are no dangling permissions.
6922        it = mSettings.mPermissions.values().iterator();
6923        while (it.hasNext()) {
6924            final BasePermission bp = it.next();
6925            if (bp.type == BasePermission.TYPE_DYNAMIC) {
6926                if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name="
6927                        + bp.name + " pkg=" + bp.sourcePackage
6928                        + " info=" + bp.pendingInfo);
6929                if (bp.packageSetting == null && bp.pendingInfo != null) {
6930                    final BasePermission tree = findPermissionTreeLP(bp.name);
6931                    if (tree != null && tree.perm != null) {
6932                        bp.packageSetting = tree.packageSetting;
6933                        bp.perm = new PackageParser.Permission(tree.perm.owner,
6934                                new PermissionInfo(bp.pendingInfo));
6935                        bp.perm.info.packageName = tree.perm.info.packageName;
6936                        bp.perm.info.name = bp.name;
6937                        bp.uid = tree.uid;
6938                    }
6939                }
6940            }
6941            if (bp.packageSetting == null) {
6942                // We may not yet have parsed the package, so just see if
6943                // we still know about its settings.
6944                bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage);
6945            }
6946            if (bp.packageSetting == null) {
6947                Slog.w(TAG, "Removing dangling permission: " + bp.name
6948                        + " from package " + bp.sourcePackage);
6949                it.remove();
6950            } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) {
6951                if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) {
6952                    Slog.i(TAG, "Removing old permission: " + bp.name
6953                            + " from package " + bp.sourcePackage);
6954                    flags |= UPDATE_PERMISSIONS_ALL;
6955                    it.remove();
6956                }
6957            }
6958        }
6959
6960        // Now update the permissions for all packages, in particular
6961        // replace the granted permissions of the system packages.
6962        if ((flags&UPDATE_PERMISSIONS_ALL) != 0) {
6963            for (PackageParser.Package pkg : mPackages.values()) {
6964                if (pkg != pkgInfo) {
6965                    grantPermissionsLPw(pkg, (flags&UPDATE_PERMISSIONS_REPLACE_ALL) != 0,
6966                            changingPkg);
6967                }
6968            }
6969        }
6970
6971        if (pkgInfo != null) {
6972            grantPermissionsLPw(pkgInfo, (flags&UPDATE_PERMISSIONS_REPLACE_PKG) != 0, changingPkg);
6973        }
6974    }
6975
6976    private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace,
6977            String packageOfInterest) {
6978        final PackageSetting ps = (PackageSetting) pkg.mExtras;
6979        if (ps == null) {
6980            return;
6981        }
6982        final GrantedPermissions gp = ps.sharedUser != null ? ps.sharedUser : ps;
6983        HashSet<String> origPermissions = gp.grantedPermissions;
6984        boolean changedPermission = false;
6985
6986        if (replace) {
6987            ps.permissionsFixed = false;
6988            if (gp == ps) {
6989                origPermissions = new HashSet<String>(gp.grantedPermissions);
6990                gp.grantedPermissions.clear();
6991                gp.gids = mGlobalGids;
6992            }
6993        }
6994
6995        if (gp.gids == null) {
6996            gp.gids = mGlobalGids;
6997        }
6998
6999        final int N = pkg.requestedPermissions.size();
7000        for (int i=0; i<N; i++) {
7001            final String name = pkg.requestedPermissions.get(i);
7002            final boolean required = pkg.requestedPermissionsRequired.get(i);
7003            final BasePermission bp = mSettings.mPermissions.get(name);
7004            if (DEBUG_INSTALL) {
7005                if (gp != ps) {
7006                    Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp);
7007                }
7008            }
7009
7010            if (bp == null || bp.packageSetting == null) {
7011                if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7012                    Slog.w(TAG, "Unknown permission " + name
7013                            + " in package " + pkg.packageName);
7014                }
7015                continue;
7016            }
7017
7018            final String perm = bp.name;
7019            boolean allowed;
7020            boolean allowedSig = false;
7021            if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) {
7022                // Keep track of app op permissions.
7023                ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name);
7024                if (pkgs == null) {
7025                    pkgs = new ArraySet<>();
7026                    mAppOpPermissionPackages.put(bp.name, pkgs);
7027                }
7028                pkgs.add(pkg.packageName);
7029            }
7030            final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE;
7031            if (level == PermissionInfo.PROTECTION_NORMAL
7032                    || level == PermissionInfo.PROTECTION_DANGEROUS) {
7033                // We grant a normal or dangerous permission if any of the following
7034                // are true:
7035                // 1) The permission is required
7036                // 2) The permission is optional, but was granted in the past
7037                // 3) The permission is optional, but was requested by an
7038                //    app in /system (not /data)
7039                //
7040                // Otherwise, reject the permission.
7041                allowed = (required || origPermissions.contains(perm)
7042                        || (isSystemApp(ps) && !isUpdatedSystemApp(ps)));
7043            } else if (bp.packageSetting == null) {
7044                // This permission is invalid; skip it.
7045                allowed = false;
7046            } else if (level == PermissionInfo.PROTECTION_SIGNATURE) {
7047                allowed = grantSignaturePermission(perm, pkg, bp, origPermissions);
7048                if (allowed) {
7049                    allowedSig = true;
7050                }
7051            } else {
7052                allowed = false;
7053            }
7054            if (DEBUG_INSTALL) {
7055                if (gp != ps) {
7056                    Log.i(TAG, "Package " + pkg.packageName + " granting " + perm);
7057                }
7058            }
7059            if (allowed) {
7060                if (!isSystemApp(ps) && ps.permissionsFixed) {
7061                    // If this is an existing, non-system package, then
7062                    // we can't add any new permissions to it.
7063                    if (!allowedSig && !gp.grantedPermissions.contains(perm)) {
7064                        // Except...  if this is a permission that was added
7065                        // to the platform (note: need to only do this when
7066                        // updating the platform).
7067                        allowed = isNewPlatformPermissionForPackage(perm, pkg);
7068                    }
7069                }
7070                if (allowed) {
7071                    if (!gp.grantedPermissions.contains(perm)) {
7072                        changedPermission = true;
7073                        gp.grantedPermissions.add(perm);
7074                        gp.gids = appendInts(gp.gids, bp.gids);
7075                    } else if (!ps.haveGids) {
7076                        gp.gids = appendInts(gp.gids, bp.gids);
7077                    }
7078                } else {
7079                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7080                        Slog.w(TAG, "Not granting permission " + perm
7081                                + " to package " + pkg.packageName
7082                                + " because it was previously installed without");
7083                    }
7084                }
7085            } else {
7086                if (gp.grantedPermissions.remove(perm)) {
7087                    changedPermission = true;
7088                    gp.gids = removeInts(gp.gids, bp.gids);
7089                    Slog.i(TAG, "Un-granting permission " + perm
7090                            + " from package " + pkg.packageName
7091                            + " (protectionLevel=" + bp.protectionLevel
7092                            + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7093                            + ")");
7094                } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) {
7095                    // Don't print warning for app op permissions, since it is fine for them
7096                    // not to be granted, there is a UI for the user to decide.
7097                    if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) {
7098                        Slog.w(TAG, "Not granting permission " + perm
7099                                + " to package " + pkg.packageName
7100                                + " (protectionLevel=" + bp.protectionLevel
7101                                + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags)
7102                                + ")");
7103                    }
7104                }
7105            }
7106        }
7107
7108        if ((changedPermission || replace) && !ps.permissionsFixed &&
7109                !isSystemApp(ps) || isUpdatedSystemApp(ps)){
7110            // This is the first that we have heard about this package, so the
7111            // permissions we have now selected are fixed until explicitly
7112            // changed.
7113            ps.permissionsFixed = true;
7114        }
7115        ps.haveGids = true;
7116    }
7117
7118    private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) {
7119        boolean allowed = false;
7120        final int NP = PackageParser.NEW_PERMISSIONS.length;
7121        for (int ip=0; ip<NP; ip++) {
7122            final PackageParser.NewPermissionInfo npi
7123                    = PackageParser.NEW_PERMISSIONS[ip];
7124            if (npi.name.equals(perm)
7125                    && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) {
7126                allowed = true;
7127                Log.i(TAG, "Auto-granting " + perm + " to old pkg "
7128                        + pkg.packageName);
7129                break;
7130            }
7131        }
7132        return allowed;
7133    }
7134
7135    private boolean grantSignaturePermission(String perm, PackageParser.Package pkg,
7136                                          BasePermission bp, HashSet<String> origPermissions) {
7137        boolean allowed;
7138        allowed = (compareSignatures(
7139                bp.packageSetting.signatures.mSignatures, pkg.mSignatures)
7140                        == PackageManager.SIGNATURE_MATCH)
7141                || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures)
7142                        == PackageManager.SIGNATURE_MATCH);
7143        if (!allowed && (bp.protectionLevel
7144                & PermissionInfo.PROTECTION_FLAG_SYSTEM) != 0) {
7145            if (isSystemApp(pkg)) {
7146                // For updated system applications, a system permission
7147                // is granted only if it had been defined by the original application.
7148                if (isUpdatedSystemApp(pkg)) {
7149                    final PackageSetting sysPs = mSettings
7150                            .getDisabledSystemPkgLPr(pkg.packageName);
7151                    final GrantedPermissions origGp = sysPs.sharedUser != null
7152                            ? sysPs.sharedUser : sysPs;
7153
7154                    if (origGp.grantedPermissions.contains(perm)) {
7155                        // If the original was granted this permission, we take
7156                        // that grant decision as read and propagate it to the
7157                        // update.
7158                        allowed = true;
7159                    } else {
7160                        // The system apk may have been updated with an older
7161                        // version of the one on the data partition, but which
7162                        // granted a new system permission that it didn't have
7163                        // before.  In this case we do want to allow the app to
7164                        // now get the new permission if the ancestral apk is
7165                        // privileged to get it.
7166                        if (sysPs.pkg != null && sysPs.isPrivileged()) {
7167                            for (int j=0;
7168                                    j<sysPs.pkg.requestedPermissions.size(); j++) {
7169                                if (perm.equals(
7170                                        sysPs.pkg.requestedPermissions.get(j))) {
7171                                    allowed = true;
7172                                    break;
7173                                }
7174                            }
7175                        }
7176                    }
7177                } else {
7178                    allowed = isPrivilegedApp(pkg);
7179                }
7180            }
7181        }
7182        if (!allowed && (bp.protectionLevel
7183                & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) {
7184            // For development permissions, a development permission
7185            // is granted only if it was already granted.
7186            allowed = origPermissions.contains(perm);
7187        }
7188        return allowed;
7189    }
7190
7191    final class ActivityIntentResolver
7192            extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> {
7193        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7194                boolean defaultOnly, int userId) {
7195            if (!sUserManager.exists(userId)) return null;
7196            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7197            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7198        }
7199
7200        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7201                int userId) {
7202            if (!sUserManager.exists(userId)) return null;
7203            mFlags = flags;
7204            return super.queryIntent(intent, resolvedType,
7205                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7206        }
7207
7208        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7209                int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) {
7210            if (!sUserManager.exists(userId)) return null;
7211            if (packageActivities == null) {
7212                return null;
7213            }
7214            mFlags = flags;
7215            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7216            final int N = packageActivities.size();
7217            ArrayList<PackageParser.ActivityIntentInfo[]> listCut =
7218                new ArrayList<PackageParser.ActivityIntentInfo[]>(N);
7219
7220            ArrayList<PackageParser.ActivityIntentInfo> intentFilters;
7221            for (int i = 0; i < N; ++i) {
7222                intentFilters = packageActivities.get(i).intents;
7223                if (intentFilters != null && intentFilters.size() > 0) {
7224                    PackageParser.ActivityIntentInfo[] array =
7225                            new PackageParser.ActivityIntentInfo[intentFilters.size()];
7226                    intentFilters.toArray(array);
7227                    listCut.add(array);
7228                }
7229            }
7230            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7231        }
7232
7233        public final void addActivity(PackageParser.Activity a, String type) {
7234            final boolean systemApp = isSystemApp(a.info.applicationInfo);
7235            mActivities.put(a.getComponentName(), a);
7236            if (DEBUG_SHOW_INFO)
7237                Log.v(
7238                TAG, "  " + type + " " +
7239                (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":");
7240            if (DEBUG_SHOW_INFO)
7241                Log.v(TAG, "    Class=" + a.info.name);
7242            final int NI = a.intents.size();
7243            for (int j=0; j<NI; j++) {
7244                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7245                if (!systemApp && intent.getPriority() > 0 && "activity".equals(type)) {
7246                    intent.setPriority(0);
7247                    Log.w(TAG, "Package " + a.info.applicationInfo.packageName + " has activity "
7248                            + a.className + " with priority > 0, forcing to 0");
7249                }
7250                if (DEBUG_SHOW_INFO) {
7251                    Log.v(TAG, "    IntentFilter:");
7252                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7253                }
7254                if (!intent.debugCheck()) {
7255                    Log.w(TAG, "==> For Activity " + a.info.name);
7256                }
7257                addFilter(intent);
7258            }
7259        }
7260
7261        public final void removeActivity(PackageParser.Activity a, String type) {
7262            mActivities.remove(a.getComponentName());
7263            if (DEBUG_SHOW_INFO) {
7264                Log.v(TAG, "  " + type + " "
7265                        + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel
7266                                : a.info.name) + ":");
7267                Log.v(TAG, "    Class=" + a.info.name);
7268            }
7269            final int NI = a.intents.size();
7270            for (int j=0; j<NI; j++) {
7271                PackageParser.ActivityIntentInfo intent = a.intents.get(j);
7272                if (DEBUG_SHOW_INFO) {
7273                    Log.v(TAG, "    IntentFilter:");
7274                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7275                }
7276                removeFilter(intent);
7277            }
7278        }
7279
7280        @Override
7281        protected boolean allowFilterResult(
7282                PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) {
7283            ActivityInfo filterAi = filter.activity.info;
7284            for (int i=dest.size()-1; i>=0; i--) {
7285                ActivityInfo destAi = dest.get(i).activityInfo;
7286                if (destAi.name == filterAi.name
7287                        && destAi.packageName == filterAi.packageName) {
7288                    return false;
7289                }
7290            }
7291            return true;
7292        }
7293
7294        @Override
7295        protected ActivityIntentInfo[] newArray(int size) {
7296            return new ActivityIntentInfo[size];
7297        }
7298
7299        @Override
7300        protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) {
7301            if (!sUserManager.exists(userId)) return true;
7302            PackageParser.Package p = filter.activity.owner;
7303            if (p != null) {
7304                PackageSetting ps = (PackageSetting)p.mExtras;
7305                if (ps != null) {
7306                    // System apps are never considered stopped for purposes of
7307                    // filtering, because there may be no way for the user to
7308                    // actually re-launch them.
7309                    return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0
7310                            && ps.getStopped(userId);
7311                }
7312            }
7313            return false;
7314        }
7315
7316        @Override
7317        protected boolean isPackageForFilter(String packageName,
7318                PackageParser.ActivityIntentInfo info) {
7319            return packageName.equals(info.activity.owner.packageName);
7320        }
7321
7322        @Override
7323        protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info,
7324                int match, int userId) {
7325            if (!sUserManager.exists(userId)) return null;
7326            if (!mSettings.isEnabledLPr(info.activity.info, mFlags, userId)) {
7327                return null;
7328            }
7329            final PackageParser.Activity activity = info.activity;
7330            if (mSafeMode && (activity.info.applicationInfo.flags
7331                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7332                return null;
7333            }
7334            PackageSetting ps = (PackageSetting) activity.owner.mExtras;
7335            if (ps == null) {
7336                return null;
7337            }
7338            ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags,
7339                    ps.readUserState(userId), userId);
7340            if (ai == null) {
7341                return null;
7342            }
7343            final ResolveInfo res = new ResolveInfo();
7344            res.activityInfo = ai;
7345            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7346                res.filter = info;
7347            }
7348            res.priority = info.getPriority();
7349            res.preferredOrder = activity.owner.mPreferredOrder;
7350            //System.out.println("Result: " + res.activityInfo.className +
7351            //                   " = " + res.priority);
7352            res.match = match;
7353            res.isDefault = info.hasDefault;
7354            res.labelRes = info.labelRes;
7355            res.nonLocalizedLabel = info.nonLocalizedLabel;
7356            if (userNeedsBadging(userId)) {
7357                res.noResourceId = true;
7358            } else {
7359                res.icon = info.icon;
7360            }
7361            res.system = isSystemApp(res.activityInfo.applicationInfo);
7362            return res;
7363        }
7364
7365        @Override
7366        protected void sortResults(List<ResolveInfo> results) {
7367            Collections.sort(results, mResolvePrioritySorter);
7368        }
7369
7370        @Override
7371        protected void dumpFilter(PrintWriter out, String prefix,
7372                PackageParser.ActivityIntentInfo filter) {
7373            out.print(prefix); out.print(
7374                    Integer.toHexString(System.identityHashCode(filter.activity)));
7375                    out.print(' ');
7376                    filter.activity.printComponentShortName(out);
7377                    out.print(" filter ");
7378                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7379        }
7380
7381//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7382//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7383//            final List<ResolveInfo> retList = Lists.newArrayList();
7384//            while (i.hasNext()) {
7385//                final ResolveInfo resolveInfo = i.next();
7386//                if (isEnabledLP(resolveInfo.activityInfo)) {
7387//                    retList.add(resolveInfo);
7388//                }
7389//            }
7390//            return retList;
7391//        }
7392
7393        // Keys are String (activity class name), values are Activity.
7394        private final HashMap<ComponentName, PackageParser.Activity> mActivities
7395                = new HashMap<ComponentName, PackageParser.Activity>();
7396        private int mFlags;
7397    }
7398
7399    private final class ServiceIntentResolver
7400            extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> {
7401        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7402                boolean defaultOnly, int userId) {
7403            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7404            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7405        }
7406
7407        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7408                int userId) {
7409            if (!sUserManager.exists(userId)) return null;
7410            mFlags = flags;
7411            return super.queryIntent(intent, resolvedType,
7412                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7413        }
7414
7415        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7416                int flags, ArrayList<PackageParser.Service> packageServices, int userId) {
7417            if (!sUserManager.exists(userId)) return null;
7418            if (packageServices == null) {
7419                return null;
7420            }
7421            mFlags = flags;
7422            final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0;
7423            final int N = packageServices.size();
7424            ArrayList<PackageParser.ServiceIntentInfo[]> listCut =
7425                new ArrayList<PackageParser.ServiceIntentInfo[]>(N);
7426
7427            ArrayList<PackageParser.ServiceIntentInfo> intentFilters;
7428            for (int i = 0; i < N; ++i) {
7429                intentFilters = packageServices.get(i).intents;
7430                if (intentFilters != null && intentFilters.size() > 0) {
7431                    PackageParser.ServiceIntentInfo[] array =
7432                            new PackageParser.ServiceIntentInfo[intentFilters.size()];
7433                    intentFilters.toArray(array);
7434                    listCut.add(array);
7435                }
7436            }
7437            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7438        }
7439
7440        public final void addService(PackageParser.Service s) {
7441            mServices.put(s.getComponentName(), s);
7442            if (DEBUG_SHOW_INFO) {
7443                Log.v(TAG, "  "
7444                        + (s.info.nonLocalizedLabel != null
7445                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7446                Log.v(TAG, "    Class=" + s.info.name);
7447            }
7448            final int NI = s.intents.size();
7449            int j;
7450            for (j=0; j<NI; j++) {
7451                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7452                if (DEBUG_SHOW_INFO) {
7453                    Log.v(TAG, "    IntentFilter:");
7454                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7455                }
7456                if (!intent.debugCheck()) {
7457                    Log.w(TAG, "==> For Service " + s.info.name);
7458                }
7459                addFilter(intent);
7460            }
7461        }
7462
7463        public final void removeService(PackageParser.Service s) {
7464            mServices.remove(s.getComponentName());
7465            if (DEBUG_SHOW_INFO) {
7466                Log.v(TAG, "  " + (s.info.nonLocalizedLabel != null
7467                        ? s.info.nonLocalizedLabel : s.info.name) + ":");
7468                Log.v(TAG, "    Class=" + s.info.name);
7469            }
7470            final int NI = s.intents.size();
7471            int j;
7472            for (j=0; j<NI; j++) {
7473                PackageParser.ServiceIntentInfo intent = s.intents.get(j);
7474                if (DEBUG_SHOW_INFO) {
7475                    Log.v(TAG, "    IntentFilter:");
7476                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7477                }
7478                removeFilter(intent);
7479            }
7480        }
7481
7482        @Override
7483        protected boolean allowFilterResult(
7484                PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) {
7485            ServiceInfo filterSi = filter.service.info;
7486            for (int i=dest.size()-1; i>=0; i--) {
7487                ServiceInfo destAi = dest.get(i).serviceInfo;
7488                if (destAi.name == filterSi.name
7489                        && destAi.packageName == filterSi.packageName) {
7490                    return false;
7491                }
7492            }
7493            return true;
7494        }
7495
7496        @Override
7497        protected PackageParser.ServiceIntentInfo[] newArray(int size) {
7498            return new PackageParser.ServiceIntentInfo[size];
7499        }
7500
7501        @Override
7502        protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) {
7503            if (!sUserManager.exists(userId)) return true;
7504            PackageParser.Package p = filter.service.owner;
7505            if (p != null) {
7506                PackageSetting ps = (PackageSetting)p.mExtras;
7507                if (ps != null) {
7508                    // System apps are never considered stopped for purposes of
7509                    // filtering, because there may be no way for the user to
7510                    // actually re-launch them.
7511                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7512                            && ps.getStopped(userId);
7513                }
7514            }
7515            return false;
7516        }
7517
7518        @Override
7519        protected boolean isPackageForFilter(String packageName,
7520                PackageParser.ServiceIntentInfo info) {
7521            return packageName.equals(info.service.owner.packageName);
7522        }
7523
7524        @Override
7525        protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter,
7526                int match, int userId) {
7527            if (!sUserManager.exists(userId)) return null;
7528            final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter;
7529            if (!mSettings.isEnabledLPr(info.service.info, mFlags, userId)) {
7530                return null;
7531            }
7532            final PackageParser.Service service = info.service;
7533            if (mSafeMode && (service.info.applicationInfo.flags
7534                    &ApplicationInfo.FLAG_SYSTEM) == 0) {
7535                return null;
7536            }
7537            PackageSetting ps = (PackageSetting) service.owner.mExtras;
7538            if (ps == null) {
7539                return null;
7540            }
7541            ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags,
7542                    ps.readUserState(userId), userId);
7543            if (si == null) {
7544                return null;
7545            }
7546            final ResolveInfo res = new ResolveInfo();
7547            res.serviceInfo = si;
7548            if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) {
7549                res.filter = filter;
7550            }
7551            res.priority = info.getPriority();
7552            res.preferredOrder = service.owner.mPreferredOrder;
7553            //System.out.println("Result: " + res.activityInfo.className +
7554            //                   " = " + res.priority);
7555            res.match = match;
7556            res.isDefault = info.hasDefault;
7557            res.labelRes = info.labelRes;
7558            res.nonLocalizedLabel = info.nonLocalizedLabel;
7559            res.icon = info.icon;
7560            res.system = isSystemApp(res.serviceInfo.applicationInfo);
7561            return res;
7562        }
7563
7564        @Override
7565        protected void sortResults(List<ResolveInfo> results) {
7566            Collections.sort(results, mResolvePrioritySorter);
7567        }
7568
7569        @Override
7570        protected void dumpFilter(PrintWriter out, String prefix,
7571                PackageParser.ServiceIntentInfo filter) {
7572            out.print(prefix); out.print(
7573                    Integer.toHexString(System.identityHashCode(filter.service)));
7574                    out.print(' ');
7575                    filter.service.printComponentShortName(out);
7576                    out.print(" filter ");
7577                    out.println(Integer.toHexString(System.identityHashCode(filter)));
7578        }
7579
7580//        List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) {
7581//            final Iterator<ResolveInfo> i = resolveInfoList.iterator();
7582//            final List<ResolveInfo> retList = Lists.newArrayList();
7583//            while (i.hasNext()) {
7584//                final ResolveInfo resolveInfo = (ResolveInfo) i;
7585//                if (isEnabledLP(resolveInfo.serviceInfo)) {
7586//                    retList.add(resolveInfo);
7587//                }
7588//            }
7589//            return retList;
7590//        }
7591
7592        // Keys are String (activity class name), values are Activity.
7593        private final HashMap<ComponentName, PackageParser.Service> mServices
7594                = new HashMap<ComponentName, PackageParser.Service>();
7595        private int mFlags;
7596    };
7597
7598    private final class ProviderIntentResolver
7599            extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> {
7600        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType,
7601                boolean defaultOnly, int userId) {
7602            mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0;
7603            return super.queryIntent(intent, resolvedType, defaultOnly, userId);
7604        }
7605
7606        public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags,
7607                int userId) {
7608            if (!sUserManager.exists(userId))
7609                return null;
7610            mFlags = flags;
7611            return super.queryIntent(intent, resolvedType,
7612                    (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId);
7613        }
7614
7615        public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType,
7616                int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) {
7617            if (!sUserManager.exists(userId))
7618                return null;
7619            if (packageProviders == null) {
7620                return null;
7621            }
7622            mFlags = flags;
7623            final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0;
7624            final int N = packageProviders.size();
7625            ArrayList<PackageParser.ProviderIntentInfo[]> listCut =
7626                    new ArrayList<PackageParser.ProviderIntentInfo[]>(N);
7627
7628            ArrayList<PackageParser.ProviderIntentInfo> intentFilters;
7629            for (int i = 0; i < N; ++i) {
7630                intentFilters = packageProviders.get(i).intents;
7631                if (intentFilters != null && intentFilters.size() > 0) {
7632                    PackageParser.ProviderIntentInfo[] array =
7633                            new PackageParser.ProviderIntentInfo[intentFilters.size()];
7634                    intentFilters.toArray(array);
7635                    listCut.add(array);
7636                }
7637            }
7638            return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId);
7639        }
7640
7641        public final void addProvider(PackageParser.Provider p) {
7642            if (mProviders.containsKey(p.getComponentName())) {
7643                Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring");
7644                return;
7645            }
7646
7647            mProviders.put(p.getComponentName(), p);
7648            if (DEBUG_SHOW_INFO) {
7649                Log.v(TAG, "  "
7650                        + (p.info.nonLocalizedLabel != null
7651                                ? p.info.nonLocalizedLabel : p.info.name) + ":");
7652                Log.v(TAG, "    Class=" + p.info.name);
7653            }
7654            final int NI = p.intents.size();
7655            int j;
7656            for (j = 0; j < NI; j++) {
7657                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7658                if (DEBUG_SHOW_INFO) {
7659                    Log.v(TAG, "    IntentFilter:");
7660                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7661                }
7662                if (!intent.debugCheck()) {
7663                    Log.w(TAG, "==> For Provider " + p.info.name);
7664                }
7665                addFilter(intent);
7666            }
7667        }
7668
7669        public final void removeProvider(PackageParser.Provider p) {
7670            mProviders.remove(p.getComponentName());
7671            if (DEBUG_SHOW_INFO) {
7672                Log.v(TAG, "  " + (p.info.nonLocalizedLabel != null
7673                        ? p.info.nonLocalizedLabel : p.info.name) + ":");
7674                Log.v(TAG, "    Class=" + p.info.name);
7675            }
7676            final int NI = p.intents.size();
7677            int j;
7678            for (j = 0; j < NI; j++) {
7679                PackageParser.ProviderIntentInfo intent = p.intents.get(j);
7680                if (DEBUG_SHOW_INFO) {
7681                    Log.v(TAG, "    IntentFilter:");
7682                    intent.dump(new LogPrinter(Log.VERBOSE, TAG), "      ");
7683                }
7684                removeFilter(intent);
7685            }
7686        }
7687
7688        @Override
7689        protected boolean allowFilterResult(
7690                PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) {
7691            ProviderInfo filterPi = filter.provider.info;
7692            for (int i = dest.size() - 1; i >= 0; i--) {
7693                ProviderInfo destPi = dest.get(i).providerInfo;
7694                if (destPi.name == filterPi.name
7695                        && destPi.packageName == filterPi.packageName) {
7696                    return false;
7697                }
7698            }
7699            return true;
7700        }
7701
7702        @Override
7703        protected PackageParser.ProviderIntentInfo[] newArray(int size) {
7704            return new PackageParser.ProviderIntentInfo[size];
7705        }
7706
7707        @Override
7708        protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) {
7709            if (!sUserManager.exists(userId))
7710                return true;
7711            PackageParser.Package p = filter.provider.owner;
7712            if (p != null) {
7713                PackageSetting ps = (PackageSetting) p.mExtras;
7714                if (ps != null) {
7715                    // System apps are never considered stopped for purposes of
7716                    // filtering, because there may be no way for the user to
7717                    // actually re-launch them.
7718                    return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0
7719                            && ps.getStopped(userId);
7720                }
7721            }
7722            return false;
7723        }
7724
7725        @Override
7726        protected boolean isPackageForFilter(String packageName,
7727                PackageParser.ProviderIntentInfo info) {
7728            return packageName.equals(info.provider.owner.packageName);
7729        }
7730
7731        @Override
7732        protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter,
7733                int match, int userId) {
7734            if (!sUserManager.exists(userId))
7735                return null;
7736            final PackageParser.ProviderIntentInfo info = filter;
7737            if (!mSettings.isEnabledLPr(info.provider.info, mFlags, userId)) {
7738                return null;
7739            }
7740            final PackageParser.Provider provider = info.provider;
7741            if (mSafeMode && (provider.info.applicationInfo.flags
7742                    & ApplicationInfo.FLAG_SYSTEM) == 0) {
7743                return null;
7744            }
7745            PackageSetting ps = (PackageSetting) provider.owner.mExtras;
7746            if (ps == null) {
7747                return null;
7748            }
7749            ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags,
7750                    ps.readUserState(userId), userId);
7751            if (pi == null) {
7752                return null;
7753            }
7754            final ResolveInfo res = new ResolveInfo();
7755            res.providerInfo = pi;
7756            if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) {
7757                res.filter = filter;
7758            }
7759            res.priority = info.getPriority();
7760            res.preferredOrder = provider.owner.mPreferredOrder;
7761            res.match = match;
7762            res.isDefault = info.hasDefault;
7763            res.labelRes = info.labelRes;
7764            res.nonLocalizedLabel = info.nonLocalizedLabel;
7765            res.icon = info.icon;
7766            res.system = isSystemApp(res.providerInfo.applicationInfo);
7767            return res;
7768        }
7769
7770        @Override
7771        protected void sortResults(List<ResolveInfo> results) {
7772            Collections.sort(results, mResolvePrioritySorter);
7773        }
7774
7775        @Override
7776        protected void dumpFilter(PrintWriter out, String prefix,
7777                PackageParser.ProviderIntentInfo filter) {
7778            out.print(prefix);
7779            out.print(
7780                    Integer.toHexString(System.identityHashCode(filter.provider)));
7781            out.print(' ');
7782            filter.provider.printComponentShortName(out);
7783            out.print(" filter ");
7784            out.println(Integer.toHexString(System.identityHashCode(filter)));
7785        }
7786
7787        private final HashMap<ComponentName, PackageParser.Provider> mProviders
7788                = new HashMap<ComponentName, PackageParser.Provider>();
7789        private int mFlags;
7790    };
7791
7792    private static final Comparator<ResolveInfo> mResolvePrioritySorter =
7793            new Comparator<ResolveInfo>() {
7794        public int compare(ResolveInfo r1, ResolveInfo r2) {
7795            int v1 = r1.priority;
7796            int v2 = r2.priority;
7797            //System.out.println("Comparing: q1=" + q1 + " q2=" + q2);
7798            if (v1 != v2) {
7799                return (v1 > v2) ? -1 : 1;
7800            }
7801            v1 = r1.preferredOrder;
7802            v2 = r2.preferredOrder;
7803            if (v1 != v2) {
7804                return (v1 > v2) ? -1 : 1;
7805            }
7806            if (r1.isDefault != r2.isDefault) {
7807                return r1.isDefault ? -1 : 1;
7808            }
7809            v1 = r1.match;
7810            v2 = r2.match;
7811            //System.out.println("Comparing: m1=" + m1 + " m2=" + m2);
7812            if (v1 != v2) {
7813                return (v1 > v2) ? -1 : 1;
7814            }
7815            if (r1.system != r2.system) {
7816                return r1.system ? -1 : 1;
7817            }
7818            return 0;
7819        }
7820    };
7821
7822    private static final Comparator<ProviderInfo> mProviderInitOrderSorter =
7823            new Comparator<ProviderInfo>() {
7824        public int compare(ProviderInfo p1, ProviderInfo p2) {
7825            final int v1 = p1.initOrder;
7826            final int v2 = p2.initOrder;
7827            return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0);
7828        }
7829    };
7830
7831    static final void sendPackageBroadcast(String action, String pkg,
7832            Bundle extras, String targetPkg, IIntentReceiver finishedReceiver,
7833            int[] userIds) {
7834        IActivityManager am = ActivityManagerNative.getDefault();
7835        if (am != null) {
7836            try {
7837                if (userIds == null) {
7838                    userIds = am.getRunningUserIds();
7839                }
7840                for (int id : userIds) {
7841                    final Intent intent = new Intent(action,
7842                            pkg != null ? Uri.fromParts("package", pkg, null) : null);
7843                    if (extras != null) {
7844                        intent.putExtras(extras);
7845                    }
7846                    if (targetPkg != null) {
7847                        intent.setPackage(targetPkg);
7848                    }
7849                    // Modify the UID when posting to other users
7850                    int uid = intent.getIntExtra(Intent.EXTRA_UID, -1);
7851                    if (uid > 0 && UserHandle.getUserId(uid) != id) {
7852                        uid = UserHandle.getUid(id, UserHandle.getAppId(uid));
7853                        intent.putExtra(Intent.EXTRA_UID, uid);
7854                    }
7855                    intent.putExtra(Intent.EXTRA_USER_HANDLE, id);
7856                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
7857                    if (DEBUG_BROADCASTS) {
7858                        RuntimeException here = new RuntimeException("here");
7859                        here.fillInStackTrace();
7860                        Slog.d(TAG, "Sending to user " + id + ": "
7861                                + intent.toShortString(false, true, false, false)
7862                                + " " + intent.getExtras(), here);
7863                    }
7864                    am.broadcastIntent(null, intent, null, finishedReceiver,
7865                            0, null, null, null, android.app.AppOpsManager.OP_NONE,
7866                            finishedReceiver != null, false, id);
7867                }
7868            } catch (RemoteException ex) {
7869            }
7870        }
7871    }
7872
7873    /**
7874     * Check if the external storage media is available. This is true if there
7875     * is a mounted external storage medium or if the external storage is
7876     * emulated.
7877     */
7878    private boolean isExternalMediaAvailable() {
7879        return mMediaMounted || Environment.isExternalStorageEmulated();
7880    }
7881
7882    @Override
7883    public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) {
7884        // writer
7885        synchronized (mPackages) {
7886            if (!isExternalMediaAvailable()) {
7887                // If the external storage is no longer mounted at this point,
7888                // the caller may not have been able to delete all of this
7889                // packages files and can not delete any more.  Bail.
7890                return null;
7891            }
7892            final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned;
7893            if (lastPackage != null) {
7894                pkgs.remove(lastPackage);
7895            }
7896            if (pkgs.size() > 0) {
7897                return pkgs.get(0);
7898            }
7899        }
7900        return null;
7901    }
7902
7903    void schedulePackageCleaning(String packageName, int userId, boolean andCode) {
7904        final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE,
7905                userId, andCode ? 1 : 0, packageName);
7906        if (mSystemReady) {
7907            msg.sendToTarget();
7908        } else {
7909            if (mPostSystemReadyMessages == null) {
7910                mPostSystemReadyMessages = new ArrayList<>();
7911            }
7912            mPostSystemReadyMessages.add(msg);
7913        }
7914    }
7915
7916    void startCleaningPackages() {
7917        // reader
7918        synchronized (mPackages) {
7919            if (!isExternalMediaAvailable()) {
7920                return;
7921            }
7922            if (mSettings.mPackagesToBeCleaned.isEmpty()) {
7923                return;
7924            }
7925        }
7926        Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE);
7927        intent.setComponent(DEFAULT_CONTAINER_COMPONENT);
7928        IActivityManager am = ActivityManagerNative.getDefault();
7929        if (am != null) {
7930            try {
7931                am.startService(null, intent, null, UserHandle.USER_OWNER);
7932            } catch (RemoteException e) {
7933            }
7934        }
7935    }
7936
7937    @Override
7938    public void installPackage(String originPath, IPackageInstallObserver2 observer,
7939            int installFlags, String installerPackageName, VerificationParams verificationParams,
7940            String packageAbiOverride) {
7941        installPackageAsUser(originPath, observer, installFlags, installerPackageName, verificationParams,
7942                packageAbiOverride, UserHandle.getCallingUserId());
7943    }
7944
7945    @Override
7946    public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer,
7947            int installFlags, String installerPackageName, VerificationParams verificationParams,
7948            String packageAbiOverride, int userId) {
7949        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null);
7950
7951        final int callingUid = Binder.getCallingUid();
7952        enforceCrossUserPermission(callingUid, userId, true, true, "installPackageAsUser");
7953
7954        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
7955            try {
7956                if (observer != null) {
7957                    observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null);
7958                }
7959            } catch (RemoteException re) {
7960            }
7961            return;
7962        }
7963
7964        if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) {
7965            installFlags |= PackageManager.INSTALL_FROM_ADB;
7966
7967        } else {
7968            // Caller holds INSTALL_PACKAGES permission, so we're less strict
7969            // about installerPackageName.
7970
7971            installFlags &= ~PackageManager.INSTALL_FROM_ADB;
7972            installFlags &= ~PackageManager.INSTALL_ALL_USERS;
7973        }
7974
7975        UserHandle user;
7976        if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) {
7977            user = UserHandle.ALL;
7978        } else {
7979            user = new UserHandle(userId);
7980        }
7981
7982        verificationParams.setInstallerUid(callingUid);
7983
7984        final File originFile = new File(originPath);
7985        final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile);
7986
7987        final Message msg = mHandler.obtainMessage(INIT_COPY);
7988        msg.obj = new InstallParams(origin, observer, installFlags,
7989                installerPackageName, verificationParams, user, packageAbiOverride);
7990        mHandler.sendMessage(msg);
7991    }
7992
7993    void installStage(String packageName, File stagedDir, String stagedCid,
7994            IPackageInstallObserver2 observer, PackageInstaller.SessionParams params,
7995            String installerPackageName, int installerUid, UserHandle user) {
7996        final VerificationParams verifParams = new VerificationParams(null, params.originatingUri,
7997                params.referrerUri, installerUid, null);
7998
7999        final OriginInfo origin;
8000        if (stagedDir != null) {
8001            origin = OriginInfo.fromStagedFile(stagedDir);
8002        } else {
8003            origin = OriginInfo.fromStagedContainer(stagedCid);
8004        }
8005
8006        final Message msg = mHandler.obtainMessage(INIT_COPY);
8007        msg.obj = new InstallParams(origin, observer, params.installFlags,
8008                installerPackageName, verifParams, user, params.abiOverride);
8009        mHandler.sendMessage(msg);
8010    }
8011
8012    private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, int userId) {
8013        Bundle extras = new Bundle(1);
8014        extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, pkgSetting.appId));
8015
8016        sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED,
8017                packageName, extras, null, null, new int[] {userId});
8018        try {
8019            IActivityManager am = ActivityManagerNative.getDefault();
8020            final boolean isSystem =
8021                    isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting);
8022            if (isSystem && am.isUserRunning(userId, false)) {
8023                // The just-installed/enabled app is bundled on the system, so presumed
8024                // to be able to run automatically without needing an explicit launch.
8025                // Send it a BOOT_COMPLETED if it would ordinarily have gotten one.
8026                Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED)
8027                        .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES)
8028                        .setPackage(packageName);
8029                am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null,
8030                        android.app.AppOpsManager.OP_NONE, false, false, userId);
8031            }
8032        } catch (RemoteException e) {
8033            // shouldn't happen
8034            Slog.w(TAG, "Unable to bootstrap installed package", e);
8035        }
8036    }
8037
8038    @Override
8039    public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
8040            int userId) {
8041        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8042        PackageSetting pkgSetting;
8043        final int uid = Binder.getCallingUid();
8044        enforceCrossUserPermission(uid, userId, true, true,
8045                "setApplicationHiddenSetting for user " + userId);
8046
8047        if (hidden && isPackageDeviceAdmin(packageName, userId)) {
8048            Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin");
8049            return false;
8050        }
8051
8052        long callingId = Binder.clearCallingIdentity();
8053        try {
8054            boolean sendAdded = false;
8055            boolean sendRemoved = false;
8056            // writer
8057            synchronized (mPackages) {
8058                pkgSetting = mSettings.mPackages.get(packageName);
8059                if (pkgSetting == null) {
8060                    return false;
8061                }
8062                if (pkgSetting.getHidden(userId) != hidden) {
8063                    pkgSetting.setHidden(hidden, userId);
8064                    mSettings.writePackageRestrictionsLPr(userId);
8065                    if (hidden) {
8066                        sendRemoved = true;
8067                    } else {
8068                        sendAdded = true;
8069                    }
8070                }
8071            }
8072            if (sendAdded) {
8073                sendPackageAddedForUser(packageName, pkgSetting, userId);
8074                return true;
8075            }
8076            if (sendRemoved) {
8077                killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId),
8078                        "hiding pkg");
8079                sendApplicationHiddenForUser(packageName, pkgSetting, userId);
8080            }
8081        } finally {
8082            Binder.restoreCallingIdentity(callingId);
8083        }
8084        return false;
8085    }
8086
8087    private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting,
8088            int userId) {
8089        final PackageRemovedInfo info = new PackageRemovedInfo();
8090        info.removedPackage = packageName;
8091        info.removedUsers = new int[] {userId};
8092        info.uid = UserHandle.getUid(userId, pkgSetting.appId);
8093        info.sendBroadcast(false, false, false);
8094    }
8095
8096    /**
8097     * Returns true if application is not found or there was an error. Otherwise it returns
8098     * the hidden state of the package for the given user.
8099     */
8100    @Override
8101    public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) {
8102        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null);
8103        enforceCrossUserPermission(Binder.getCallingUid(), userId, true,
8104                false, "getApplicationHidden for user " + userId);
8105        PackageSetting pkgSetting;
8106        long callingId = Binder.clearCallingIdentity();
8107        try {
8108            // writer
8109            synchronized (mPackages) {
8110                pkgSetting = mSettings.mPackages.get(packageName);
8111                if (pkgSetting == null) {
8112                    return true;
8113                }
8114                return pkgSetting.getHidden(userId);
8115            }
8116        } finally {
8117            Binder.restoreCallingIdentity(callingId);
8118        }
8119    }
8120
8121    /**
8122     * @hide
8123     */
8124    @Override
8125    public int installExistingPackageAsUser(String packageName, int userId) {
8126        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES,
8127                null);
8128        PackageSetting pkgSetting;
8129        final int uid = Binder.getCallingUid();
8130        enforceCrossUserPermission(uid, userId, true, true, "installExistingPackage for user "
8131                + userId);
8132        if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) {
8133            return PackageManager.INSTALL_FAILED_USER_RESTRICTED;
8134        }
8135
8136        long callingId = Binder.clearCallingIdentity();
8137        try {
8138            boolean sendAdded = false;
8139            Bundle extras = new Bundle(1);
8140
8141            // writer
8142            synchronized (mPackages) {
8143                pkgSetting = mSettings.mPackages.get(packageName);
8144                if (pkgSetting == null) {
8145                    return PackageManager.INSTALL_FAILED_INVALID_URI;
8146                }
8147                if (!pkgSetting.getInstalled(userId)) {
8148                    pkgSetting.setInstalled(true, userId);
8149                    pkgSetting.setHidden(false, userId);
8150                    mSettings.writePackageRestrictionsLPr(userId);
8151                    sendAdded = true;
8152                }
8153            }
8154
8155            if (sendAdded) {
8156                sendPackageAddedForUser(packageName, pkgSetting, userId);
8157            }
8158        } finally {
8159            Binder.restoreCallingIdentity(callingId);
8160        }
8161
8162        return PackageManager.INSTALL_SUCCEEDED;
8163    }
8164
8165    boolean isUserRestricted(int userId, String restrictionKey) {
8166        Bundle restrictions = sUserManager.getUserRestrictions(userId);
8167        if (restrictions.getBoolean(restrictionKey, false)) {
8168            Log.w(TAG, "User is restricted: " + restrictionKey);
8169            return true;
8170        }
8171        return false;
8172    }
8173
8174    @Override
8175    public void verifyPendingInstall(int id, int verificationCode) throws RemoteException {
8176        mContext.enforceCallingOrSelfPermission(
8177                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8178                "Only package verification agents can verify applications");
8179
8180        final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8181        final PackageVerificationResponse response = new PackageVerificationResponse(
8182                verificationCode, Binder.getCallingUid());
8183        msg.arg1 = id;
8184        msg.obj = response;
8185        mHandler.sendMessage(msg);
8186    }
8187
8188    @Override
8189    public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
8190            long millisecondsToDelay) {
8191        mContext.enforceCallingOrSelfPermission(
8192                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
8193                "Only package verification agents can extend verification timeouts");
8194
8195        final PackageVerificationState state = mPendingVerification.get(id);
8196        final PackageVerificationResponse response = new PackageVerificationResponse(
8197                verificationCodeAtTimeout, Binder.getCallingUid());
8198
8199        if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) {
8200            millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT;
8201        }
8202        if (millisecondsToDelay < 0) {
8203            millisecondsToDelay = 0;
8204        }
8205        if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW)
8206                && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) {
8207            verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT;
8208        }
8209
8210        if ((state != null) && !state.timeoutExtended()) {
8211            state.extendTimeout();
8212
8213            final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED);
8214            msg.arg1 = id;
8215            msg.obj = response;
8216            mHandler.sendMessageDelayed(msg, millisecondsToDelay);
8217        }
8218    }
8219
8220    private void broadcastPackageVerified(int verificationId, Uri packageUri,
8221            int verificationCode, UserHandle user) {
8222        final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED);
8223        intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE);
8224        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8225        intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
8226        intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode);
8227
8228        mContext.sendBroadcastAsUser(intent, user,
8229                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT);
8230    }
8231
8232    private ComponentName matchComponentForVerifier(String packageName,
8233            List<ResolveInfo> receivers) {
8234        ActivityInfo targetReceiver = null;
8235
8236        final int NR = receivers.size();
8237        for (int i = 0; i < NR; i++) {
8238            final ResolveInfo info = receivers.get(i);
8239            if (info.activityInfo == null) {
8240                continue;
8241            }
8242
8243            if (packageName.equals(info.activityInfo.packageName)) {
8244                targetReceiver = info.activityInfo;
8245                break;
8246            }
8247        }
8248
8249        if (targetReceiver == null) {
8250            return null;
8251        }
8252
8253        return new ComponentName(targetReceiver.packageName, targetReceiver.name);
8254    }
8255
8256    private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo,
8257            List<ResolveInfo> receivers, final PackageVerificationState verificationState) {
8258        if (pkgInfo.verifiers.length == 0) {
8259            return null;
8260        }
8261
8262        final int N = pkgInfo.verifiers.length;
8263        final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1);
8264        for (int i = 0; i < N; i++) {
8265            final VerifierInfo verifierInfo = pkgInfo.verifiers[i];
8266
8267            final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName,
8268                    receivers);
8269            if (comp == null) {
8270                continue;
8271            }
8272
8273            final int verifierUid = getUidForVerifier(verifierInfo);
8274            if (verifierUid == -1) {
8275                continue;
8276            }
8277
8278            if (DEBUG_VERIFY) {
8279                Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName
8280                        + " with the correct signature");
8281            }
8282            sufficientVerifiers.add(comp);
8283            verificationState.addSufficientVerifier(verifierUid);
8284        }
8285
8286        return sufficientVerifiers;
8287    }
8288
8289    private int getUidForVerifier(VerifierInfo verifierInfo) {
8290        synchronized (mPackages) {
8291            final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName);
8292            if (pkg == null) {
8293                return -1;
8294            } else if (pkg.mSignatures.length != 1) {
8295                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8296                        + " has more than one signature; ignoring");
8297                return -1;
8298            }
8299
8300            /*
8301             * If the public key of the package's signature does not match
8302             * our expected public key, then this is a different package and
8303             * we should skip.
8304             */
8305
8306            final byte[] expectedPublicKey;
8307            try {
8308                final Signature verifierSig = pkg.mSignatures[0];
8309                final PublicKey publicKey = verifierSig.getPublicKey();
8310                expectedPublicKey = publicKey.getEncoded();
8311            } catch (CertificateException e) {
8312                return -1;
8313            }
8314
8315            final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded();
8316
8317            if (!Arrays.equals(actualPublicKey, expectedPublicKey)) {
8318                Slog.i(TAG, "Verifier package " + verifierInfo.packageName
8319                        + " does not have the expected public key; ignoring");
8320                return -1;
8321            }
8322
8323            return pkg.applicationInfo.uid;
8324        }
8325    }
8326
8327    @Override
8328    public void finishPackageInstall(int token) {
8329        enforceSystemOrRoot("Only the system is allowed to finish installs");
8330
8331        if (DEBUG_INSTALL) {
8332            Slog.v(TAG, "BM finishing package install for " + token);
8333        }
8334
8335        final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8336        mHandler.sendMessage(msg);
8337    }
8338
8339    /**
8340     * Get the verification agent timeout.
8341     *
8342     * @return verification timeout in milliseconds
8343     */
8344    private long getVerificationTimeout() {
8345        return android.provider.Settings.Global.getLong(mContext.getContentResolver(),
8346                android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT,
8347                DEFAULT_VERIFICATION_TIMEOUT);
8348    }
8349
8350    /**
8351     * Get the default verification agent response code.
8352     *
8353     * @return default verification response code
8354     */
8355    private int getDefaultVerificationResponse() {
8356        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8357                android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE,
8358                DEFAULT_VERIFICATION_RESPONSE);
8359    }
8360
8361    /**
8362     * Check whether or not package verification has been enabled.
8363     *
8364     * @return true if verification should be performed
8365     */
8366    private boolean isVerificationEnabled(int userId, int installFlags) {
8367        if (!DEFAULT_VERIFY_ENABLE) {
8368            return false;
8369        }
8370
8371        boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS);
8372
8373        // Check if installing from ADB
8374        if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) {
8375            // Do not run verification in a test harness environment
8376            if (ActivityManager.isRunningInTestHarness()) {
8377                return false;
8378            }
8379            if (ensureVerifyAppsEnabled) {
8380                return true;
8381            }
8382            // Check if the developer does not want package verification for ADB installs
8383            if (android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8384                    android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) {
8385                return false;
8386            }
8387        }
8388
8389        if (ensureVerifyAppsEnabled) {
8390            return true;
8391        }
8392
8393        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8394                android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1;
8395    }
8396
8397    /**
8398     * Get the "allow unknown sources" setting.
8399     *
8400     * @return the current "allow unknown sources" setting
8401     */
8402    private int getUnknownSourcesSettings() {
8403        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
8404                android.provider.Settings.Global.INSTALL_NON_MARKET_APPS,
8405                -1);
8406    }
8407
8408    @Override
8409    public void setInstallerPackageName(String targetPackage, String installerPackageName) {
8410        final int uid = Binder.getCallingUid();
8411        // writer
8412        synchronized (mPackages) {
8413            PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage);
8414            if (targetPackageSetting == null) {
8415                throw new IllegalArgumentException("Unknown target package: " + targetPackage);
8416            }
8417
8418            PackageSetting installerPackageSetting;
8419            if (installerPackageName != null) {
8420                installerPackageSetting = mSettings.mPackages.get(installerPackageName);
8421                if (installerPackageSetting == null) {
8422                    throw new IllegalArgumentException("Unknown installer package: "
8423                            + installerPackageName);
8424                }
8425            } else {
8426                installerPackageSetting = null;
8427            }
8428
8429            Signature[] callerSignature;
8430            Object obj = mSettings.getUserIdLPr(uid);
8431            if (obj != null) {
8432                if (obj instanceof SharedUserSetting) {
8433                    callerSignature = ((SharedUserSetting)obj).signatures.mSignatures;
8434                } else if (obj instanceof PackageSetting) {
8435                    callerSignature = ((PackageSetting)obj).signatures.mSignatures;
8436                } else {
8437                    throw new SecurityException("Bad object " + obj + " for uid " + uid);
8438                }
8439            } else {
8440                throw new SecurityException("Unknown calling uid " + uid);
8441            }
8442
8443            // Verify: can't set installerPackageName to a package that is
8444            // not signed with the same cert as the caller.
8445            if (installerPackageSetting != null) {
8446                if (compareSignatures(callerSignature,
8447                        installerPackageSetting.signatures.mSignatures)
8448                        != PackageManager.SIGNATURE_MATCH) {
8449                    throw new SecurityException(
8450                            "Caller does not have same cert as new installer package "
8451                            + installerPackageName);
8452                }
8453            }
8454
8455            // Verify: if target already has an installer package, it must
8456            // be signed with the same cert as the caller.
8457            if (targetPackageSetting.installerPackageName != null) {
8458                PackageSetting setting = mSettings.mPackages.get(
8459                        targetPackageSetting.installerPackageName);
8460                // If the currently set package isn't valid, then it's always
8461                // okay to change it.
8462                if (setting != null) {
8463                    if (compareSignatures(callerSignature,
8464                            setting.signatures.mSignatures)
8465                            != PackageManager.SIGNATURE_MATCH) {
8466                        throw new SecurityException(
8467                                "Caller does not have same cert as old installer package "
8468                                + targetPackageSetting.installerPackageName);
8469                    }
8470                }
8471            }
8472
8473            // Okay!
8474            targetPackageSetting.installerPackageName = installerPackageName;
8475            scheduleWriteSettingsLocked();
8476        }
8477    }
8478
8479    private void processPendingInstall(final InstallArgs args, final int currentStatus) {
8480        // Queue up an async operation since the package installation may take a little while.
8481        mHandler.post(new Runnable() {
8482            public void run() {
8483                mHandler.removeCallbacks(this);
8484                 // Result object to be returned
8485                PackageInstalledInfo res = new PackageInstalledInfo();
8486                res.returnCode = currentStatus;
8487                res.uid = -1;
8488                res.pkg = null;
8489                res.removedInfo = new PackageRemovedInfo();
8490                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
8491                    args.doPreInstall(res.returnCode);
8492                    synchronized (mInstallLock) {
8493                        installPackageLI(args, res);
8494                    }
8495                    args.doPostInstall(res.returnCode, res.uid);
8496                }
8497
8498                // A restore should be performed at this point if (a) the install
8499                // succeeded, (b) the operation is not an update, and (c) the new
8500                // package has not opted out of backup participation.
8501                final boolean update = res.removedInfo.removedPackage != null;
8502                final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags;
8503                boolean doRestore = !update
8504                        && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0);
8505
8506                // Set up the post-install work request bookkeeping.  This will be used
8507                // and cleaned up by the post-install event handling regardless of whether
8508                // there's a restore pass performed.  Token values are >= 1.
8509                int token;
8510                if (mNextInstallToken < 0) mNextInstallToken = 1;
8511                token = mNextInstallToken++;
8512
8513                PostInstallData data = new PostInstallData(args, res);
8514                mRunningInstalls.put(token, data);
8515                if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token);
8516
8517                if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) {
8518                    // Pass responsibility to the Backup Manager.  It will perform a
8519                    // restore if appropriate, then pass responsibility back to the
8520                    // Package Manager to run the post-install observer callbacks
8521                    // and broadcasts.
8522                    IBackupManager bm = IBackupManager.Stub.asInterface(
8523                            ServiceManager.getService(Context.BACKUP_SERVICE));
8524                    if (bm != null) {
8525                        if (DEBUG_INSTALL) Log.v(TAG, "token " + token
8526                                + " to BM for possible restore");
8527                        try {
8528                            bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token);
8529                        } catch (RemoteException e) {
8530                            // can't happen; the backup manager is local
8531                        } catch (Exception e) {
8532                            Slog.e(TAG, "Exception trying to enqueue restore", e);
8533                            doRestore = false;
8534                        }
8535                    } else {
8536                        Slog.e(TAG, "Backup Manager not found!");
8537                        doRestore = false;
8538                    }
8539                }
8540
8541                if (!doRestore) {
8542                    // No restore possible, or the Backup Manager was mysteriously not
8543                    // available -- just fire the post-install work request directly.
8544                    if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token);
8545                    Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0);
8546                    mHandler.sendMessage(msg);
8547                }
8548            }
8549        });
8550    }
8551
8552    private abstract class HandlerParams {
8553        private static final int MAX_RETRIES = 4;
8554
8555        /**
8556         * Number of times startCopy() has been attempted and had a non-fatal
8557         * error.
8558         */
8559        private int mRetries = 0;
8560
8561        /** User handle for the user requesting the information or installation. */
8562        private final UserHandle mUser;
8563
8564        HandlerParams(UserHandle user) {
8565            mUser = user;
8566        }
8567
8568        UserHandle getUser() {
8569            return mUser;
8570        }
8571
8572        final boolean startCopy() {
8573            boolean res;
8574            try {
8575                if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this);
8576
8577                if (++mRetries > MAX_RETRIES) {
8578                    Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up");
8579                    mHandler.sendEmptyMessage(MCS_GIVE_UP);
8580                    handleServiceError();
8581                    return false;
8582                } else {
8583                    handleStartCopy();
8584                    res = true;
8585                }
8586            } catch (RemoteException e) {
8587                if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT");
8588                mHandler.sendEmptyMessage(MCS_RECONNECT);
8589                res = false;
8590            }
8591            handleReturnCode();
8592            return res;
8593        }
8594
8595        final void serviceError() {
8596            if (DEBUG_INSTALL) Slog.i(TAG, "serviceError");
8597            handleServiceError();
8598            handleReturnCode();
8599        }
8600
8601        abstract void handleStartCopy() throws RemoteException;
8602        abstract void handleServiceError();
8603        abstract void handleReturnCode();
8604    }
8605
8606    class MeasureParams extends HandlerParams {
8607        private final PackageStats mStats;
8608        private boolean mSuccess;
8609
8610        private final IPackageStatsObserver mObserver;
8611
8612        public MeasureParams(PackageStats stats, IPackageStatsObserver observer) {
8613            super(new UserHandle(stats.userHandle));
8614            mObserver = observer;
8615            mStats = stats;
8616        }
8617
8618        @Override
8619        public String toString() {
8620            return "MeasureParams{"
8621                + Integer.toHexString(System.identityHashCode(this))
8622                + " " + mStats.packageName + "}";
8623        }
8624
8625        @Override
8626        void handleStartCopy() throws RemoteException {
8627            synchronized (mInstallLock) {
8628                mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats);
8629            }
8630
8631            if (mSuccess) {
8632                final boolean mounted;
8633                if (Environment.isExternalStorageEmulated()) {
8634                    mounted = true;
8635                } else {
8636                    final String status = Environment.getExternalStorageState();
8637                    mounted = (Environment.MEDIA_MOUNTED.equals(status)
8638                            || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status));
8639                }
8640
8641                if (mounted) {
8642                    final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle);
8643
8644                    mStats.externalCacheSize = calculateDirectorySize(mContainerService,
8645                            userEnv.buildExternalStorageAppCacheDirs(mStats.packageName));
8646
8647                    mStats.externalDataSize = calculateDirectorySize(mContainerService,
8648                            userEnv.buildExternalStorageAppDataDirs(mStats.packageName));
8649
8650                    // Always subtract cache size, since it's a subdirectory
8651                    mStats.externalDataSize -= mStats.externalCacheSize;
8652
8653                    mStats.externalMediaSize = calculateDirectorySize(mContainerService,
8654                            userEnv.buildExternalStorageAppMediaDirs(mStats.packageName));
8655
8656                    mStats.externalObbSize = calculateDirectorySize(mContainerService,
8657                            userEnv.buildExternalStorageAppObbDirs(mStats.packageName));
8658                }
8659            }
8660        }
8661
8662        @Override
8663        void handleReturnCode() {
8664            if (mObserver != null) {
8665                try {
8666                    mObserver.onGetStatsCompleted(mStats, mSuccess);
8667                } catch (RemoteException e) {
8668                    Slog.i(TAG, "Observer no longer exists.");
8669                }
8670            }
8671        }
8672
8673        @Override
8674        void handleServiceError() {
8675            Slog.e(TAG, "Could not measure application " + mStats.packageName
8676                            + " external storage");
8677        }
8678    }
8679
8680    private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths)
8681            throws RemoteException {
8682        long result = 0;
8683        for (File path : paths) {
8684            result += mcs.calculateDirectorySize(path.getAbsolutePath());
8685        }
8686        return result;
8687    }
8688
8689    private static void clearDirectory(IMediaContainerService mcs, File[] paths) {
8690        for (File path : paths) {
8691            try {
8692                mcs.clearDirectory(path.getAbsolutePath());
8693            } catch (RemoteException e) {
8694            }
8695        }
8696    }
8697
8698    static class OriginInfo {
8699        /**
8700         * Location where install is coming from, before it has been
8701         * copied/renamed into place. This could be a single monolithic APK
8702         * file, or a cluster directory. This location may be untrusted.
8703         */
8704        final File file;
8705        final String cid;
8706
8707        /**
8708         * Flag indicating that {@link #file} or {@link #cid} has already been
8709         * staged, meaning downstream users don't need to defensively copy the
8710         * contents.
8711         */
8712        final boolean staged;
8713
8714        /**
8715         * Flag indicating that {@link #file} or {@link #cid} is an already
8716         * installed app that is being moved.
8717         */
8718        final boolean existing;
8719
8720        final String resolvedPath;
8721        final File resolvedFile;
8722
8723        static OriginInfo fromNothing() {
8724            return new OriginInfo(null, null, false, false);
8725        }
8726
8727        static OriginInfo fromUntrustedFile(File file) {
8728            return new OriginInfo(file, null, false, false);
8729        }
8730
8731        static OriginInfo fromExistingFile(File file) {
8732            return new OriginInfo(file, null, false, true);
8733        }
8734
8735        static OriginInfo fromStagedFile(File file) {
8736            return new OriginInfo(file, null, true, false);
8737        }
8738
8739        static OriginInfo fromStagedContainer(String cid) {
8740            return new OriginInfo(null, cid, true, false);
8741        }
8742
8743        private OriginInfo(File file, String cid, boolean staged, boolean existing) {
8744            this.file = file;
8745            this.cid = cid;
8746            this.staged = staged;
8747            this.existing = existing;
8748
8749            if (cid != null) {
8750                resolvedPath = PackageHelper.getSdDir(cid);
8751                resolvedFile = new File(resolvedPath);
8752            } else if (file != null) {
8753                resolvedPath = file.getAbsolutePath();
8754                resolvedFile = file;
8755            } else {
8756                resolvedPath = null;
8757                resolvedFile = null;
8758            }
8759        }
8760    }
8761
8762    class InstallParams extends HandlerParams {
8763        final OriginInfo origin;
8764        final IPackageInstallObserver2 observer;
8765        int installFlags;
8766        final String installerPackageName;
8767        final VerificationParams verificationParams;
8768        private InstallArgs mArgs;
8769        private int mRet;
8770        final String packageAbiOverride;
8771
8772        InstallParams(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
8773                String installerPackageName, VerificationParams verificationParams, UserHandle user,
8774                String packageAbiOverride) {
8775            super(user);
8776            this.origin = origin;
8777            this.observer = observer;
8778            this.installFlags = installFlags;
8779            this.installerPackageName = installerPackageName;
8780            this.verificationParams = verificationParams;
8781            this.packageAbiOverride = packageAbiOverride;
8782        }
8783
8784        @Override
8785        public String toString() {
8786            return "InstallParams{" + Integer.toHexString(System.identityHashCode(this))
8787                    + " file=" + origin.file + " cid=" + origin.cid + "}";
8788        }
8789
8790        public ManifestDigest getManifestDigest() {
8791            if (verificationParams == null) {
8792                return null;
8793            }
8794            return verificationParams.getManifestDigest();
8795        }
8796
8797        private int installLocationPolicy(PackageInfoLite pkgLite) {
8798            String packageName = pkgLite.packageName;
8799            int installLocation = pkgLite.installLocation;
8800            boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8801            // reader
8802            synchronized (mPackages) {
8803                PackageParser.Package pkg = mPackages.get(packageName);
8804                if (pkg != null) {
8805                    if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
8806                        // Check for downgrading.
8807                        if ((installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) == 0) {
8808                            if (pkgLite.versionCode < pkg.mVersionCode) {
8809                                Slog.w(TAG, "Can't install update of " + packageName
8810                                        + " update version " + pkgLite.versionCode
8811                                        + " is older than installed version "
8812                                        + pkg.mVersionCode);
8813                                return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE;
8814                            }
8815                        }
8816                        // Check for updated system application.
8817                        if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) {
8818                            if (onSd) {
8819                                Slog.w(TAG, "Cannot install update to system app on sdcard");
8820                                return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION;
8821                            }
8822                            return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8823                        } else {
8824                            if (onSd) {
8825                                // Install flag overrides everything.
8826                                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8827                            }
8828                            // If current upgrade specifies particular preference
8829                            if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) {
8830                                // Application explicitly specified internal.
8831                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8832                            } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) {
8833                                // App explictly prefers external. Let policy decide
8834                            } else {
8835                                // Prefer previous location
8836                                if (isExternal(pkg)) {
8837                                    return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8838                                }
8839                                return PackageHelper.RECOMMEND_INSTALL_INTERNAL;
8840                            }
8841                        }
8842                    } else {
8843                        // Invalid install. Return error code
8844                        return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS;
8845                    }
8846                }
8847            }
8848            // All the special cases have been taken care of.
8849            // Return result based on recommended install location.
8850            if (onSd) {
8851                return PackageHelper.RECOMMEND_INSTALL_EXTERNAL;
8852            }
8853            return pkgLite.recommendedInstallLocation;
8854        }
8855
8856        /*
8857         * Invoke remote method to get package information and install
8858         * location values. Override install location based on default
8859         * policy if needed and then create install arguments based
8860         * on the install location.
8861         */
8862        public void handleStartCopy() throws RemoteException {
8863            int ret = PackageManager.INSTALL_SUCCEEDED;
8864
8865            // If we're already staged, we've firmly committed to an install location
8866            if (origin.staged) {
8867                if (origin.file != null) {
8868                    installFlags |= PackageManager.INSTALL_INTERNAL;
8869                    installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8870                } else if (origin.cid != null) {
8871                    installFlags |= PackageManager.INSTALL_EXTERNAL;
8872                    installFlags &= ~PackageManager.INSTALL_INTERNAL;
8873                } else {
8874                    throw new IllegalStateException("Invalid stage location");
8875                }
8876            }
8877
8878            final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
8879            final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0;
8880
8881            PackageInfoLite pkgLite = null;
8882
8883            if (onInt && onSd) {
8884                // Check if both bits are set.
8885                Slog.w(TAG, "Conflicting flags specified for installing on both internal and external");
8886                ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8887            } else {
8888                pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags,
8889                        packageAbiOverride);
8890
8891                /*
8892                 * If we have too little free space, try to free cache
8893                 * before giving up.
8894                 */
8895                if (!origin.staged && pkgLite.recommendedInstallLocation
8896                        == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8897                    // TODO: focus freeing disk space on the target device
8898                    final StorageManager storage = StorageManager.from(mContext);
8899                    final long lowThreshold = storage.getStorageLowBytes(
8900                            Environment.getDataDirectory());
8901
8902                    final long sizeBytes = mContainerService.calculateInstalledSize(
8903                            origin.resolvedPath, isForwardLocked(), packageAbiOverride);
8904
8905                    if (mInstaller.freeCache(sizeBytes + lowThreshold) >= 0) {
8906                        pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath,
8907                                installFlags, packageAbiOverride);
8908                    }
8909
8910                    /*
8911                     * The cache free must have deleted the file we
8912                     * downloaded to install.
8913                     *
8914                     * TODO: fix the "freeCache" call to not delete
8915                     *       the file we care about.
8916                     */
8917                    if (pkgLite.recommendedInstallLocation
8918                            == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8919                        pkgLite.recommendedInstallLocation
8920                            = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE;
8921                    }
8922                }
8923            }
8924
8925            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8926                int loc = pkgLite.recommendedInstallLocation;
8927                if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) {
8928                    ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION;
8929                } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) {
8930                    ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS;
8931                } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) {
8932                    ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
8933                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) {
8934                    ret = PackageManager.INSTALL_FAILED_INVALID_APK;
8935                } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) {
8936                    ret = PackageManager.INSTALL_FAILED_INVALID_URI;
8937                } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) {
8938                    ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE;
8939                } else {
8940                    // Override with defaults if needed.
8941                    loc = installLocationPolicy(pkgLite);
8942                    if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) {
8943                        ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE;
8944                    } else if (!onSd && !onInt) {
8945                        // Override install location with flags
8946                        if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) {
8947                            // Set the flag to install on external media.
8948                            installFlags |= PackageManager.INSTALL_EXTERNAL;
8949                            installFlags &= ~PackageManager.INSTALL_INTERNAL;
8950                        } else {
8951                            // Make sure the flag for installing on external
8952                            // media is unset
8953                            installFlags |= PackageManager.INSTALL_INTERNAL;
8954                            installFlags &= ~PackageManager.INSTALL_EXTERNAL;
8955                        }
8956                    }
8957                }
8958            }
8959
8960            final InstallArgs args = createInstallArgs(this);
8961            mArgs = args;
8962
8963            if (ret == PackageManager.INSTALL_SUCCEEDED) {
8964                 /*
8965                 * ADB installs appear as UserHandle.USER_ALL, and can only be performed by
8966                 * UserHandle.USER_OWNER, so use the package verifier for UserHandle.USER_OWNER.
8967                 */
8968                int userIdentifier = getUser().getIdentifier();
8969                if (userIdentifier == UserHandle.USER_ALL
8970                        && ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0)) {
8971                    userIdentifier = UserHandle.USER_OWNER;
8972                }
8973
8974                /*
8975                 * Determine if we have any installed package verifiers. If we
8976                 * do, then we'll defer to them to verify the packages.
8977                 */
8978                final int requiredUid = mRequiredVerifierPackage == null ? -1
8979                        : getPackageUid(mRequiredVerifierPackage, userIdentifier);
8980                if (!origin.existing && requiredUid != -1
8981                        && isVerificationEnabled(userIdentifier, installFlags)) {
8982                    final Intent verification = new Intent(
8983                            Intent.ACTION_PACKAGE_NEEDS_VERIFICATION);
8984                    verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)),
8985                            PACKAGE_MIME_TYPE);
8986                    verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
8987
8988                    final List<ResolveInfo> receivers = queryIntentReceivers(verification,
8989                            PACKAGE_MIME_TYPE, PackageManager.GET_DISABLED_COMPONENTS,
8990                            0 /* TODO: Which userId? */);
8991
8992                    if (DEBUG_VERIFY) {
8993                        Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent "
8994                                + verification.toString() + " with " + pkgLite.verifiers.length
8995                                + " optional verifiers");
8996                    }
8997
8998                    final int verificationId = mPendingVerificationToken++;
8999
9000                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId);
9001
9002                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE,
9003                            installerPackageName);
9004
9005                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS,
9006                            installFlags);
9007
9008                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME,
9009                            pkgLite.packageName);
9010
9011                    verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE,
9012                            pkgLite.versionCode);
9013
9014                    if (verificationParams != null) {
9015                        if (verificationParams.getVerificationURI() != null) {
9016                           verification.putExtra(PackageManager.EXTRA_VERIFICATION_URI,
9017                                 verificationParams.getVerificationURI());
9018                        }
9019                        if (verificationParams.getOriginatingURI() != null) {
9020                            verification.putExtra(Intent.EXTRA_ORIGINATING_URI,
9021                                  verificationParams.getOriginatingURI());
9022                        }
9023                        if (verificationParams.getReferrer() != null) {
9024                            verification.putExtra(Intent.EXTRA_REFERRER,
9025                                  verificationParams.getReferrer());
9026                        }
9027                        if (verificationParams.getOriginatingUid() >= 0) {
9028                            verification.putExtra(Intent.EXTRA_ORIGINATING_UID,
9029                                  verificationParams.getOriginatingUid());
9030                        }
9031                        if (verificationParams.getInstallerUid() >= 0) {
9032                            verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID,
9033                                  verificationParams.getInstallerUid());
9034                        }
9035                    }
9036
9037                    final PackageVerificationState verificationState = new PackageVerificationState(
9038                            requiredUid, args);
9039
9040                    mPendingVerification.append(verificationId, verificationState);
9041
9042                    final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite,
9043                            receivers, verificationState);
9044
9045                    /*
9046                     * If any sufficient verifiers were listed in the package
9047                     * manifest, attempt to ask them.
9048                     */
9049                    if (sufficientVerifiers != null) {
9050                        final int N = sufficientVerifiers.size();
9051                        if (N == 0) {
9052                            Slog.i(TAG, "Additional verifiers required, but none installed.");
9053                            ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE;
9054                        } else {
9055                            for (int i = 0; i < N; i++) {
9056                                final ComponentName verifierComponent = sufficientVerifiers.get(i);
9057
9058                                final Intent sufficientIntent = new Intent(verification);
9059                                sufficientIntent.setComponent(verifierComponent);
9060
9061                                mContext.sendBroadcastAsUser(sufficientIntent, getUser());
9062                            }
9063                        }
9064                    }
9065
9066                    final ComponentName requiredVerifierComponent = matchComponentForVerifier(
9067                            mRequiredVerifierPackage, receivers);
9068                    if (ret == PackageManager.INSTALL_SUCCEEDED
9069                            && mRequiredVerifierPackage != null) {
9070                        /*
9071                         * Send the intent to the required verification agent,
9072                         * but only start the verification timeout after the
9073                         * target BroadcastReceivers have run.
9074                         */
9075                        verification.setComponent(requiredVerifierComponent);
9076                        mContext.sendOrderedBroadcastAsUser(verification, getUser(),
9077                                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
9078                                new BroadcastReceiver() {
9079                                    @Override
9080                                    public void onReceive(Context context, Intent intent) {
9081                                        final Message msg = mHandler
9082                                                .obtainMessage(CHECK_PENDING_VERIFICATION);
9083                                        msg.arg1 = verificationId;
9084                                        mHandler.sendMessageDelayed(msg, getVerificationTimeout());
9085                                    }
9086                                }, null, 0, null, null);
9087
9088                        /*
9089                         * We don't want the copy to proceed until verification
9090                         * succeeds, so null out this field.
9091                         */
9092                        mArgs = null;
9093                    }
9094                } else {
9095                    /*
9096                     * No package verification is enabled, so immediately start
9097                     * the remote call to initiate copy using temporary file.
9098                     */
9099                    ret = args.copyApk(mContainerService, true);
9100                }
9101            }
9102
9103            mRet = ret;
9104        }
9105
9106        @Override
9107        void handleReturnCode() {
9108            // If mArgs is null, then MCS couldn't be reached. When it
9109            // reconnects, it will try again to install. At that point, this
9110            // will succeed.
9111            if (mArgs != null) {
9112                processPendingInstall(mArgs, mRet);
9113            }
9114        }
9115
9116        @Override
9117        void handleServiceError() {
9118            mArgs = createInstallArgs(this);
9119            mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9120        }
9121
9122        public boolean isForwardLocked() {
9123            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9124        }
9125    }
9126
9127    /**
9128     * Used during creation of InstallArgs
9129     *
9130     * @param installFlags package installation flags
9131     * @return true if should be installed on external storage
9132     */
9133    private static boolean installOnSd(int installFlags) {
9134        if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) {
9135            return false;
9136        }
9137        if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) {
9138            return true;
9139        }
9140        return false;
9141    }
9142
9143    /**
9144     * Used during creation of InstallArgs
9145     *
9146     * @param installFlags package installation flags
9147     * @return true if should be installed as forward locked
9148     */
9149    private static boolean installForwardLocked(int installFlags) {
9150        return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9151    }
9152
9153    private InstallArgs createInstallArgs(InstallParams params) {
9154        if (installOnSd(params.installFlags) || params.isForwardLocked()) {
9155            return new AsecInstallArgs(params);
9156        } else {
9157            return new FileInstallArgs(params);
9158        }
9159    }
9160
9161    /**
9162     * Create args that describe an existing installed package. Typically used
9163     * when cleaning up old installs, or used as a move source.
9164     */
9165    private InstallArgs createInstallArgsForExisting(int installFlags, String codePath,
9166            String resourcePath, String nativeLibraryRoot, String[] instructionSets) {
9167        final boolean isInAsec;
9168        if (installOnSd(installFlags)) {
9169            /* Apps on SD card are always in ASEC containers. */
9170            isInAsec = true;
9171        } else if (installForwardLocked(installFlags)
9172                && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) {
9173            /*
9174             * Forward-locked apps are only in ASEC containers if they're the
9175             * new style
9176             */
9177            isInAsec = true;
9178        } else {
9179            isInAsec = false;
9180        }
9181
9182        if (isInAsec) {
9183            return new AsecInstallArgs(codePath, instructionSets,
9184                    installOnSd(installFlags), installForwardLocked(installFlags));
9185        } else {
9186            return new FileInstallArgs(codePath, resourcePath, nativeLibraryRoot,
9187                    instructionSets);
9188        }
9189    }
9190
9191    static abstract class InstallArgs {
9192        /** @see InstallParams#origin */
9193        final OriginInfo origin;
9194
9195        final IPackageInstallObserver2 observer;
9196        // Always refers to PackageManager flags only
9197        final int installFlags;
9198        final String installerPackageName;
9199        final ManifestDigest manifestDigest;
9200        final UserHandle user;
9201        final String abiOverride;
9202
9203        // The list of instruction sets supported by this app. This is currently
9204        // only used during the rmdex() phase to clean up resources. We can get rid of this
9205        // if we move dex files under the common app path.
9206        /* nullable */ String[] instructionSets;
9207
9208        InstallArgs(OriginInfo origin, IPackageInstallObserver2 observer, int installFlags,
9209                String installerPackageName, ManifestDigest manifestDigest, UserHandle user,
9210                String[] instructionSets, String abiOverride) {
9211            this.origin = origin;
9212            this.installFlags = installFlags;
9213            this.observer = observer;
9214            this.installerPackageName = installerPackageName;
9215            this.manifestDigest = manifestDigest;
9216            this.user = user;
9217            this.instructionSets = instructionSets;
9218            this.abiOverride = abiOverride;
9219        }
9220
9221        abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException;
9222        abstract int doPreInstall(int status);
9223
9224        /**
9225         * Rename package into final resting place. All paths on the given
9226         * scanned package should be updated to reflect the rename.
9227         */
9228        abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath);
9229        abstract int doPostInstall(int status, int uid);
9230
9231        /** @see PackageSettingBase#codePathString */
9232        abstract String getCodePath();
9233        /** @see PackageSettingBase#resourcePathString */
9234        abstract String getResourcePath();
9235        abstract String getLegacyNativeLibraryPath();
9236
9237        // Need installer lock especially for dex file removal.
9238        abstract void cleanUpResourcesLI();
9239        abstract boolean doPostDeleteLI(boolean delete);
9240        abstract boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException;
9241
9242        /**
9243         * Called before the source arguments are copied. This is used mostly
9244         * for MoveParams when it needs to read the source file to put it in the
9245         * destination.
9246         */
9247        int doPreCopy() {
9248            return PackageManager.INSTALL_SUCCEEDED;
9249        }
9250
9251        /**
9252         * Called after the source arguments are copied. This is used mostly for
9253         * MoveParams when it needs to read the source file to put it in the
9254         * destination.
9255         *
9256         * @return
9257         */
9258        int doPostCopy(int uid) {
9259            return PackageManager.INSTALL_SUCCEEDED;
9260        }
9261
9262        protected boolean isFwdLocked() {
9263            return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0;
9264        }
9265
9266        protected boolean isExternal() {
9267            return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0;
9268        }
9269
9270        UserHandle getUser() {
9271            return user;
9272        }
9273    }
9274
9275    /**
9276     * Logic to handle installation of non-ASEC applications, including copying
9277     * and renaming logic.
9278     */
9279    class FileInstallArgs extends InstallArgs {
9280        private File codeFile;
9281        private File resourceFile;
9282        private File legacyNativeLibraryPath;
9283
9284        // Example topology:
9285        // /data/app/com.example/base.apk
9286        // /data/app/com.example/split_foo.apk
9287        // /data/app/com.example/lib/arm/libfoo.so
9288        // /data/app/com.example/lib/arm64/libfoo.so
9289        // /data/app/com.example/dalvik/arm/base.apk@classes.dex
9290
9291        /** New install */
9292        FileInstallArgs(InstallParams params) {
9293            super(params.origin, params.observer, params.installFlags,
9294                    params.installerPackageName, params.getManifestDigest(), params.getUser(),
9295                    null /* instruction sets */, params.packageAbiOverride);
9296            if (isFwdLocked()) {
9297                throw new IllegalArgumentException("Forward locking only supported in ASEC");
9298            }
9299        }
9300
9301        /** Existing install */
9302        FileInstallArgs(String codePath, String resourcePath, String legacyNativeLibraryPath,
9303                String[] instructionSets) {
9304            super(OriginInfo.fromNothing(), null, 0, null, null, null, instructionSets, null);
9305            this.codeFile = (codePath != null) ? new File(codePath) : null;
9306            this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null;
9307            this.legacyNativeLibraryPath = (legacyNativeLibraryPath != null) ?
9308                    new File(legacyNativeLibraryPath) : null;
9309        }
9310
9311        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9312            final long sizeBytes = imcs.calculateInstalledSize(origin.file.getAbsolutePath(),
9313                    isFwdLocked(), abiOverride);
9314
9315            final StorageManager storage = StorageManager.from(mContext);
9316            return (sizeBytes <= storage.getStorageBytesUntilLow(Environment.getDataDirectory()));
9317        }
9318
9319        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9320            if (origin.staged) {
9321                Slog.d(TAG, origin.file + " already staged; skipping copy");
9322                codeFile = origin.file;
9323                resourceFile = origin.file;
9324                return PackageManager.INSTALL_SUCCEEDED;
9325            }
9326
9327            try {
9328                final File tempDir = mInstallerService.allocateInternalStageDirLegacy();
9329                codeFile = tempDir;
9330                resourceFile = tempDir;
9331            } catch (IOException e) {
9332                Slog.w(TAG, "Failed to create copy file: " + e);
9333                return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE;
9334            }
9335
9336            final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() {
9337                @Override
9338                public ParcelFileDescriptor open(String name, int mode) throws RemoteException {
9339                    if (!FileUtils.isValidExtFilename(name)) {
9340                        throw new IllegalArgumentException("Invalid filename: " + name);
9341                    }
9342                    try {
9343                        final File file = new File(codeFile, name);
9344                        final FileDescriptor fd = Os.open(file.getAbsolutePath(),
9345                                O_RDWR | O_CREAT, 0644);
9346                        Os.chmod(file.getAbsolutePath(), 0644);
9347                        return new ParcelFileDescriptor(fd);
9348                    } catch (ErrnoException e) {
9349                        throw new RemoteException("Failed to open: " + e.getMessage());
9350                    }
9351                }
9352            };
9353
9354            int ret = PackageManager.INSTALL_SUCCEEDED;
9355            ret = imcs.copyPackage(origin.file.getAbsolutePath(), target);
9356            if (ret != PackageManager.INSTALL_SUCCEEDED) {
9357                Slog.e(TAG, "Failed to copy package");
9358                return ret;
9359            }
9360
9361            final File libraryRoot = new File(codeFile, LIB_DIR_NAME);
9362            NativeLibraryHelper.Handle handle = null;
9363            try {
9364                handle = NativeLibraryHelper.Handle.create(codeFile);
9365                ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot,
9366                        abiOverride);
9367            } catch (IOException e) {
9368                Slog.e(TAG, "Copying native libraries failed", e);
9369                ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR;
9370            } finally {
9371                IoUtils.closeQuietly(handle);
9372            }
9373
9374            return ret;
9375        }
9376
9377        int doPreInstall(int status) {
9378            if (status != PackageManager.INSTALL_SUCCEEDED) {
9379                cleanUp();
9380            }
9381            return status;
9382        }
9383
9384        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9385            if (status != PackageManager.INSTALL_SUCCEEDED) {
9386                cleanUp();
9387                return false;
9388            } else {
9389                final File beforeCodeFile = codeFile;
9390                final File afterCodeFile = getNextCodePath(pkg.packageName);
9391
9392                Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile);
9393                try {
9394                    Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath());
9395                } catch (ErrnoException e) {
9396                    Slog.d(TAG, "Failed to rename", e);
9397                    return false;
9398                }
9399
9400                if (!SELinux.restoreconRecursive(afterCodeFile)) {
9401                    Slog.d(TAG, "Failed to restorecon");
9402                    return false;
9403                }
9404
9405                // Reflect the rename internally
9406                codeFile = afterCodeFile;
9407                resourceFile = afterCodeFile;
9408
9409                // Reflect the rename in scanned details
9410                pkg.codePath = afterCodeFile.getAbsolutePath();
9411                pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9412                        pkg.baseCodePath);
9413                pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9414                        pkg.splitCodePaths);
9415
9416                // Reflect the rename in app info
9417                pkg.applicationInfo.setCodePath(pkg.codePath);
9418                pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9419                pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9420                pkg.applicationInfo.setResourcePath(pkg.codePath);
9421                pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9422                pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9423
9424                return true;
9425            }
9426        }
9427
9428        int doPostInstall(int status, int uid) {
9429            if (status != PackageManager.INSTALL_SUCCEEDED) {
9430                cleanUp();
9431            }
9432            return status;
9433        }
9434
9435        @Override
9436        String getCodePath() {
9437            return (codeFile != null) ? codeFile.getAbsolutePath() : null;
9438        }
9439
9440        @Override
9441        String getResourcePath() {
9442            return (resourceFile != null) ? resourceFile.getAbsolutePath() : null;
9443        }
9444
9445        @Override
9446        String getLegacyNativeLibraryPath() {
9447            return (legacyNativeLibraryPath != null) ? legacyNativeLibraryPath.getAbsolutePath() : null;
9448        }
9449
9450        private boolean cleanUp() {
9451            if (codeFile == null || !codeFile.exists()) {
9452                return false;
9453            }
9454
9455            if (codeFile.isDirectory()) {
9456                FileUtils.deleteContents(codeFile);
9457            }
9458            codeFile.delete();
9459
9460            if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) {
9461                resourceFile.delete();
9462            }
9463
9464            if (legacyNativeLibraryPath != null && !FileUtils.contains(codeFile, legacyNativeLibraryPath)) {
9465                if (!FileUtils.deleteContents(legacyNativeLibraryPath)) {
9466                    Slog.w(TAG, "Couldn't delete native library directory " + legacyNativeLibraryPath);
9467                }
9468                legacyNativeLibraryPath.delete();
9469            }
9470
9471            return true;
9472        }
9473
9474        void cleanUpResourcesLI() {
9475            // Try enumerating all code paths before deleting
9476            List<String> allCodePaths = Collections.EMPTY_LIST;
9477            if (codeFile != null && codeFile.exists()) {
9478                try {
9479                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9480                    allCodePaths = pkg.getAllCodePaths();
9481                } catch (PackageParserException e) {
9482                    // Ignored; we tried our best
9483                }
9484            }
9485
9486            cleanUp();
9487
9488            if (!allCodePaths.isEmpty()) {
9489                if (instructionSets == null) {
9490                    throw new IllegalStateException("instructionSet == null");
9491                }
9492                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9493                for (String codePath : allCodePaths) {
9494                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9495                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9496                        if (retCode < 0) {
9497                            Slog.w(TAG, "Couldn't remove dex file for package: "
9498                                    + " at location " + codePath + ", retcode=" + retCode);
9499                            // we don't consider this to be a failure of the core package deletion
9500                        }
9501                    }
9502                }
9503            }
9504        }
9505
9506        boolean doPostDeleteLI(boolean delete) {
9507            // XXX err, shouldn't we respect the delete flag?
9508            cleanUpResourcesLI();
9509            return true;
9510        }
9511    }
9512
9513    private boolean isAsecExternal(String cid) {
9514        final String asecPath = PackageHelper.getSdFilesystem(cid);
9515        return !asecPath.startsWith(mAsecInternalPath);
9516    }
9517
9518    private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws
9519            PackageManagerException {
9520        if (copyRet < 0) {
9521            if (copyRet != PackageManager.NO_NATIVE_LIBRARIES &&
9522                    copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) {
9523                throw new PackageManagerException(copyRet, message);
9524            }
9525        }
9526    }
9527
9528    /**
9529     * Extract the MountService "container ID" from the full code path of an
9530     * .apk.
9531     */
9532    static String cidFromCodePath(String fullCodePath) {
9533        int eidx = fullCodePath.lastIndexOf("/");
9534        String subStr1 = fullCodePath.substring(0, eidx);
9535        int sidx = subStr1.lastIndexOf("/");
9536        return subStr1.substring(sidx+1, eidx);
9537    }
9538
9539    /**
9540     * Logic to handle installation of ASEC applications, including copying and
9541     * renaming logic.
9542     */
9543    class AsecInstallArgs extends InstallArgs {
9544        static final String RES_FILE_NAME = "pkg.apk";
9545        static final String PUBLIC_RES_FILE_NAME = "res.zip";
9546
9547        String cid;
9548        String packagePath;
9549        String resourcePath;
9550        String legacyNativeLibraryDir;
9551
9552        /** New install */
9553        AsecInstallArgs(InstallParams params) {
9554            super(params.origin, params.observer, params.installFlags,
9555                    params.installerPackageName, params.getManifestDigest(),
9556                    params.getUser(), null /* instruction sets */,
9557                    params.packageAbiOverride);
9558        }
9559
9560        /** Existing install */
9561        AsecInstallArgs(String fullCodePath, String[] instructionSets,
9562                        boolean isExternal, boolean isForwardLocked) {
9563            super(OriginInfo.fromNothing(), null, (isExternal ? INSTALL_EXTERNAL : 0)
9564                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9565                    instructionSets, null);
9566            // Hackily pretend we're still looking at a full code path
9567            if (!fullCodePath.endsWith(RES_FILE_NAME)) {
9568                fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath();
9569            }
9570
9571            // Extract cid from fullCodePath
9572            int eidx = fullCodePath.lastIndexOf("/");
9573            String subStr1 = fullCodePath.substring(0, eidx);
9574            int sidx = subStr1.lastIndexOf("/");
9575            cid = subStr1.substring(sidx+1, eidx);
9576            setMountPath(subStr1);
9577        }
9578
9579        AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) {
9580            super(OriginInfo.fromNothing(), null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0)
9581                    | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null,
9582                    instructionSets, null);
9583            this.cid = cid;
9584            setMountPath(PackageHelper.getSdDir(cid));
9585        }
9586
9587        void createCopyFile() {
9588            cid = mInstallerService.allocateExternalStageCidLegacy();
9589        }
9590
9591        boolean checkFreeStorage(IMediaContainerService imcs) throws RemoteException {
9592            final long sizeBytes = imcs.calculateInstalledSize(packagePath, isFwdLocked(),
9593                    abiOverride);
9594
9595            final File target;
9596            if (isExternal()) {
9597                target = new UserEnvironment(UserHandle.USER_OWNER).getExternalStorageDirectory();
9598            } else {
9599                target = Environment.getDataDirectory();
9600            }
9601
9602            final StorageManager storage = StorageManager.from(mContext);
9603            return (sizeBytes <= storage.getStorageBytesUntilLow(target));
9604        }
9605
9606        int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException {
9607            if (origin.staged) {
9608                Slog.d(TAG, origin.cid + " already staged; skipping copy");
9609                cid = origin.cid;
9610                setMountPath(PackageHelper.getSdDir(cid));
9611                return PackageManager.INSTALL_SUCCEEDED;
9612            }
9613
9614            if (temp) {
9615                createCopyFile();
9616            } else {
9617                /*
9618                 * Pre-emptively destroy the container since it's destroyed if
9619                 * copying fails due to it existing anyway.
9620                 */
9621                PackageHelper.destroySdDir(cid);
9622            }
9623
9624            final String newMountPath = imcs.copyPackageToContainer(
9625                    origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternal(),
9626                    isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */));
9627
9628            if (newMountPath != null) {
9629                setMountPath(newMountPath);
9630                return PackageManager.INSTALL_SUCCEEDED;
9631            } else {
9632                return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9633            }
9634        }
9635
9636        @Override
9637        String getCodePath() {
9638            return packagePath;
9639        }
9640
9641        @Override
9642        String getResourcePath() {
9643            return resourcePath;
9644        }
9645
9646        @Override
9647        String getLegacyNativeLibraryPath() {
9648            return legacyNativeLibraryDir;
9649        }
9650
9651        int doPreInstall(int status) {
9652            if (status != PackageManager.INSTALL_SUCCEEDED) {
9653                // Destroy container
9654                PackageHelper.destroySdDir(cid);
9655            } else {
9656                boolean mounted = PackageHelper.isContainerMounted(cid);
9657                if (!mounted) {
9658                    String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(),
9659                            Process.SYSTEM_UID);
9660                    if (newMountPath != null) {
9661                        setMountPath(newMountPath);
9662                    } else {
9663                        return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9664                    }
9665                }
9666            }
9667            return status;
9668        }
9669
9670        boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) {
9671            String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME);
9672            String newMountPath = null;
9673            if (PackageHelper.isContainerMounted(cid)) {
9674                // Unmount the container
9675                if (!PackageHelper.unMountSdDir(cid)) {
9676                    Slog.i(TAG, "Failed to unmount " + cid + " before renaming");
9677                    return false;
9678                }
9679            }
9680            if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9681                Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId +
9682                        " which might be stale. Will try to clean up.");
9683                // Clean up the stale container and proceed to recreate.
9684                if (!PackageHelper.destroySdDir(newCacheId)) {
9685                    Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId);
9686                    return false;
9687                }
9688                // Successfully cleaned up stale container. Try to rename again.
9689                if (!PackageHelper.renameSdDir(cid, newCacheId)) {
9690                    Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId
9691                            + " inspite of cleaning it up.");
9692                    return false;
9693                }
9694            }
9695            if (!PackageHelper.isContainerMounted(newCacheId)) {
9696                Slog.w(TAG, "Mounting container " + newCacheId);
9697                newMountPath = PackageHelper.mountSdDir(newCacheId,
9698                        getEncryptKey(), Process.SYSTEM_UID);
9699            } else {
9700                newMountPath = PackageHelper.getSdDir(newCacheId);
9701            }
9702            if (newMountPath == null) {
9703                Slog.w(TAG, "Failed to get cache path for  " + newCacheId);
9704                return false;
9705            }
9706            Log.i(TAG, "Succesfully renamed " + cid +
9707                    " to " + newCacheId +
9708                    " at new path: " + newMountPath);
9709            cid = newCacheId;
9710
9711            final File beforeCodeFile = new File(packagePath);
9712            setMountPath(newMountPath);
9713            final File afterCodeFile = new File(packagePath);
9714
9715            // Reflect the rename in scanned details
9716            pkg.codePath = afterCodeFile.getAbsolutePath();
9717            pkg.baseCodePath = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9718                    pkg.baseCodePath);
9719            pkg.splitCodePaths = FileUtils.rewriteAfterRename(beforeCodeFile, afterCodeFile,
9720                    pkg.splitCodePaths);
9721
9722            // Reflect the rename in app info
9723            pkg.applicationInfo.setCodePath(pkg.codePath);
9724            pkg.applicationInfo.setBaseCodePath(pkg.baseCodePath);
9725            pkg.applicationInfo.setSplitCodePaths(pkg.splitCodePaths);
9726            pkg.applicationInfo.setResourcePath(pkg.codePath);
9727            pkg.applicationInfo.setBaseResourcePath(pkg.baseCodePath);
9728            pkg.applicationInfo.setSplitResourcePaths(pkg.splitCodePaths);
9729
9730            return true;
9731        }
9732
9733        private void setMountPath(String mountPath) {
9734            final File mountFile = new File(mountPath);
9735
9736            final File monolithicFile = new File(mountFile, RES_FILE_NAME);
9737            if (monolithicFile.exists()) {
9738                packagePath = monolithicFile.getAbsolutePath();
9739                if (isFwdLocked()) {
9740                    resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath();
9741                } else {
9742                    resourcePath = packagePath;
9743                }
9744            } else {
9745                packagePath = mountFile.getAbsolutePath();
9746                resourcePath = packagePath;
9747            }
9748
9749            legacyNativeLibraryDir = new File(mountFile, LIB_DIR_NAME).getAbsolutePath();
9750        }
9751
9752        int doPostInstall(int status, int uid) {
9753            if (status != PackageManager.INSTALL_SUCCEEDED) {
9754                cleanUp();
9755            } else {
9756                final int groupOwner;
9757                final String protectedFile;
9758                if (isFwdLocked()) {
9759                    groupOwner = UserHandle.getSharedAppGid(uid);
9760                    protectedFile = RES_FILE_NAME;
9761                } else {
9762                    groupOwner = -1;
9763                    protectedFile = null;
9764                }
9765
9766                if (uid < Process.FIRST_APPLICATION_UID
9767                        || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) {
9768                    Slog.e(TAG, "Failed to finalize " + cid);
9769                    PackageHelper.destroySdDir(cid);
9770                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9771                }
9772
9773                boolean mounted = PackageHelper.isContainerMounted(cid);
9774                if (!mounted) {
9775                    PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid());
9776                }
9777            }
9778            return status;
9779        }
9780
9781        private void cleanUp() {
9782            if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp");
9783
9784            // Destroy secure container
9785            PackageHelper.destroySdDir(cid);
9786        }
9787
9788        private List<String> getAllCodePaths() {
9789            final File codeFile = new File(getCodePath());
9790            if (codeFile != null && codeFile.exists()) {
9791                try {
9792                    final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0);
9793                    return pkg.getAllCodePaths();
9794                } catch (PackageParserException e) {
9795                    // Ignored; we tried our best
9796                }
9797            }
9798            return Collections.EMPTY_LIST;
9799        }
9800
9801        void cleanUpResourcesLI() {
9802            // Enumerate all code paths before deleting
9803            cleanUpResourcesLI(getAllCodePaths());
9804        }
9805
9806        private void cleanUpResourcesLI(List<String> allCodePaths) {
9807            cleanUp();
9808
9809            if (!allCodePaths.isEmpty()) {
9810                if (instructionSets == null) {
9811                    throw new IllegalStateException("instructionSet == null");
9812                }
9813                String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets);
9814                for (String codePath : allCodePaths) {
9815                    for (String dexCodeInstructionSet : dexCodeInstructionSets) {
9816                        int retCode = mInstaller.rmdex(codePath, dexCodeInstructionSet);
9817                        if (retCode < 0) {
9818                            Slog.w(TAG, "Couldn't remove dex file for package: "
9819                                    + " at location " + codePath + ", retcode=" + retCode);
9820                            // we don't consider this to be a failure of the core package deletion
9821                        }
9822                    }
9823                }
9824            }
9825        }
9826
9827        boolean matchContainer(String app) {
9828            if (cid.startsWith(app)) {
9829                return true;
9830            }
9831            return false;
9832        }
9833
9834        String getPackageName() {
9835            return getAsecPackageName(cid);
9836        }
9837
9838        boolean doPostDeleteLI(boolean delete) {
9839            if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete);
9840            final List<String> allCodePaths = getAllCodePaths();
9841            boolean mounted = PackageHelper.isContainerMounted(cid);
9842            if (mounted) {
9843                // Unmount first
9844                if (PackageHelper.unMountSdDir(cid)) {
9845                    mounted = false;
9846                }
9847            }
9848            if (!mounted && delete) {
9849                cleanUpResourcesLI(allCodePaths);
9850            }
9851            return !mounted;
9852        }
9853
9854        @Override
9855        int doPreCopy() {
9856            if (isFwdLocked()) {
9857                if (!PackageHelper.fixSdPermissions(cid,
9858                        getPackageUid(DEFAULT_CONTAINER_PACKAGE, 0), RES_FILE_NAME)) {
9859                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9860                }
9861            }
9862
9863            return PackageManager.INSTALL_SUCCEEDED;
9864        }
9865
9866        @Override
9867        int doPostCopy(int uid) {
9868            if (isFwdLocked()) {
9869                if (uid < Process.FIRST_APPLICATION_UID
9870                        || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid),
9871                                RES_FILE_NAME)) {
9872                    Slog.e(TAG, "Failed to finalize " + cid);
9873                    PackageHelper.destroySdDir(cid);
9874                    return PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
9875                }
9876            }
9877
9878            return PackageManager.INSTALL_SUCCEEDED;
9879        }
9880    }
9881
9882    static String getAsecPackageName(String packageCid) {
9883        int idx = packageCid.lastIndexOf("-");
9884        if (idx == -1) {
9885            return packageCid;
9886        }
9887        return packageCid.substring(0, idx);
9888    }
9889
9890    // Utility method used to create code paths based on package name and available index.
9891    private static String getNextCodePath(String oldCodePath, String prefix, String suffix) {
9892        String idxStr = "";
9893        int idx = 1;
9894        // Fall back to default value of idx=1 if prefix is not
9895        // part of oldCodePath
9896        if (oldCodePath != null) {
9897            String subStr = oldCodePath;
9898            // Drop the suffix right away
9899            if (suffix != null && subStr.endsWith(suffix)) {
9900                subStr = subStr.substring(0, subStr.length() - suffix.length());
9901            }
9902            // If oldCodePath already contains prefix find out the
9903            // ending index to either increment or decrement.
9904            int sidx = subStr.lastIndexOf(prefix);
9905            if (sidx != -1) {
9906                subStr = subStr.substring(sidx + prefix.length());
9907                if (subStr != null) {
9908                    if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) {
9909                        subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length());
9910                    }
9911                    try {
9912                        idx = Integer.parseInt(subStr);
9913                        if (idx <= 1) {
9914                            idx++;
9915                        } else {
9916                            idx--;
9917                        }
9918                    } catch(NumberFormatException e) {
9919                    }
9920                }
9921            }
9922        }
9923        idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx);
9924        return prefix + idxStr;
9925    }
9926
9927    private File getNextCodePath(String packageName) {
9928        int suffix = 1;
9929        File result;
9930        do {
9931            result = new File(mAppInstallDir, packageName + "-" + suffix);
9932            suffix++;
9933        } while (result.exists());
9934        return result;
9935    }
9936
9937    // Utility method used to ignore ADD/REMOVE events
9938    // by directory observer.
9939    private static boolean ignoreCodePath(String fullPathStr) {
9940        String apkName = deriveCodePathName(fullPathStr);
9941        int idx = apkName.lastIndexOf(INSTALL_PACKAGE_SUFFIX);
9942        if (idx != -1 && ((idx+1) < apkName.length())) {
9943            // Make sure the package ends with a numeral
9944            String version = apkName.substring(idx+1);
9945            try {
9946                Integer.parseInt(version);
9947                return true;
9948            } catch (NumberFormatException e) {}
9949        }
9950        return false;
9951    }
9952
9953    // Utility method that returns the relative package path with respect
9954    // to the installation directory. Like say for /data/data/com.test-1.apk
9955    // string com.test-1 is returned.
9956    static String deriveCodePathName(String codePath) {
9957        if (codePath == null) {
9958            return null;
9959        }
9960        final File codeFile = new File(codePath);
9961        final String name = codeFile.getName();
9962        if (codeFile.isDirectory()) {
9963            return name;
9964        } else if (name.endsWith(".apk") || name.endsWith(".tmp")) {
9965            final int lastDot = name.lastIndexOf('.');
9966            return name.substring(0, lastDot);
9967        } else {
9968            Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK");
9969            return null;
9970        }
9971    }
9972
9973    class PackageInstalledInfo {
9974        String name;
9975        int uid;
9976        // The set of users that originally had this package installed.
9977        int[] origUsers;
9978        // The set of users that now have this package installed.
9979        int[] newUsers;
9980        PackageParser.Package pkg;
9981        int returnCode;
9982        String returnMsg;
9983        PackageRemovedInfo removedInfo;
9984
9985        public void setError(int code, String msg) {
9986            returnCode = code;
9987            returnMsg = msg;
9988            Slog.w(TAG, msg);
9989        }
9990
9991        public void setError(String msg, PackageParserException e) {
9992            returnCode = e.error;
9993            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
9994            Slog.w(TAG, msg, e);
9995        }
9996
9997        public void setError(String msg, PackageManagerException e) {
9998            returnCode = e.error;
9999            returnMsg = ExceptionUtils.getCompleteMessage(msg, e);
10000            Slog.w(TAG, msg, e);
10001        }
10002
10003        // In some error cases we want to convey more info back to the observer
10004        String origPackage;
10005        String origPermission;
10006    }
10007
10008    /*
10009     * Install a non-existing package.
10010     */
10011    private void installNewPackageLI(PackageParser.Package pkg,
10012            int parseFlags, int scanFlags, UserHandle user,
10013            String installerPackageName, PackageInstalledInfo res) {
10014        // Remember this for later, in case we need to rollback this install
10015        String pkgName = pkg.packageName;
10016
10017        if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg);
10018        boolean dataDirExists = getDataPathForPackage(pkg.packageName, 0).exists();
10019        synchronized(mPackages) {
10020            if (mSettings.mRenamedPackages.containsKey(pkgName)) {
10021                // A package with the same name is already installed, though
10022                // it has been renamed to an older name.  The package we
10023                // are trying to install should be installed as an update to
10024                // the existing one, but that has not been requested, so bail.
10025                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10026                        + " without first uninstalling package running as "
10027                        + mSettings.mRenamedPackages.get(pkgName));
10028                return;
10029            }
10030            if (mPackages.containsKey(pkgName)) {
10031                // Don't allow installation over an existing package with the same name.
10032                res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName
10033                        + " without first uninstalling.");
10034                return;
10035            }
10036        }
10037
10038        try {
10039            PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags, scanFlags,
10040                    System.currentTimeMillis(), user);
10041
10042            updateSettingsLI(newPackage, installerPackageName, null, null, res);
10043            // delete the partially installed application. the data directory will have to be
10044            // restored if it was already existing
10045            if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10046                // remove package from internal structures.  Note that we want deletePackageX to
10047                // delete the package data and cache directories that it created in
10048                // scanPackageLocked, unless those directories existed before we even tried to
10049                // install.
10050                deletePackageLI(pkgName, UserHandle.ALL, false, null, null,
10051                        dataDirExists ? PackageManager.DELETE_KEEP_DATA : 0,
10052                                res.removedInfo, true);
10053            }
10054
10055        } catch (PackageManagerException e) {
10056            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10057        }
10058    }
10059
10060    private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) {
10061        // Upgrade keysets are being used.  Determine if new package has a superset of the
10062        // required keys.
10063        long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets();
10064        KeySetManagerService ksms = mSettings.mKeySetManagerService;
10065        for (int i = 0; i < upgradeKeySets.length; i++) {
10066            Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]);
10067            if (newPkg.mSigningKeys.containsAll(upgradeSet)) {
10068                return true;
10069            }
10070        }
10071        return false;
10072    }
10073
10074    private void replacePackageLI(PackageParser.Package pkg,
10075            int parseFlags, int scanFlags, UserHandle user,
10076            String installerPackageName, PackageInstalledInfo res) {
10077        PackageParser.Package oldPackage;
10078        String pkgName = pkg.packageName;
10079        int[] allUsers;
10080        boolean[] perUserInstalled;
10081
10082        // First find the old package info and check signatures
10083        synchronized(mPackages) {
10084            oldPackage = mPackages.get(pkgName);
10085            if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage);
10086            PackageSetting ps = mSettings.mPackages.get(pkgName);
10087            if (ps == null || !ps.keySetData.isUsingUpgradeKeySets() || ps.sharedUser != null) {
10088                // default to original signature matching
10089                if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures)
10090                    != PackageManager.SIGNATURE_MATCH) {
10091                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10092                            "New package has a different signature: " + pkgName);
10093                    return;
10094                }
10095            } else {
10096                if(!checkUpgradeKeySetLP(ps, pkg)) {
10097                    res.setError(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES,
10098                            "New package not signed by keys specified by upgrade-keysets: "
10099                            + pkgName);
10100                    return;
10101                }
10102            }
10103
10104            // In case of rollback, remember per-user/profile install state
10105            allUsers = sUserManager.getUserIds();
10106            perUserInstalled = new boolean[allUsers.length];
10107            for (int i = 0; i < allUsers.length; i++) {
10108                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10109            }
10110        }
10111
10112        boolean sysPkg = (isSystemApp(oldPackage));
10113        if (sysPkg) {
10114            replaceSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10115                    user, allUsers, perUserInstalled, installerPackageName, res);
10116        } else {
10117            replaceNonSystemPackageLI(oldPackage, pkg, parseFlags, scanFlags,
10118                    user, allUsers, perUserInstalled, installerPackageName, res);
10119        }
10120    }
10121
10122    private void replaceNonSystemPackageLI(PackageParser.Package deletedPackage,
10123            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10124            int[] allUsers, boolean[] perUserInstalled,
10125            String installerPackageName, PackageInstalledInfo res) {
10126        String pkgName = deletedPackage.packageName;
10127        boolean deletedPkg = true;
10128        boolean updatedSettings = false;
10129
10130        if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old="
10131                + deletedPackage);
10132        long origUpdateTime;
10133        if (pkg.mExtras != null) {
10134            origUpdateTime = ((PackageSetting)pkg.mExtras).lastUpdateTime;
10135        } else {
10136            origUpdateTime = 0;
10137        }
10138
10139        // First delete the existing package while retaining the data directory
10140        if (!deletePackageLI(pkgName, null, true, null, null, PackageManager.DELETE_KEEP_DATA,
10141                res.removedInfo, true)) {
10142            // If the existing package wasn't successfully deleted
10143            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI");
10144            deletedPkg = false;
10145        } else {
10146            // Successfully deleted the old package; proceed with replace.
10147
10148            // If deleted package lived in a container, give users a chance to
10149            // relinquish resources before killing.
10150            if (isForwardLocked(deletedPackage) || isExternal(deletedPackage)) {
10151                if (DEBUG_INSTALL) {
10152                    Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE");
10153                }
10154                final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid };
10155                final ArrayList<String> pkgList = new ArrayList<String>(1);
10156                pkgList.add(deletedPackage.applicationInfo.packageName);
10157                sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null);
10158            }
10159
10160            deleteCodeCacheDirsLI(pkgName);
10161            try {
10162                final PackageParser.Package newPackage = scanPackageLI(pkg, parseFlags,
10163                        scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user);
10164                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10165                updatedSettings = true;
10166            } catch (PackageManagerException e) {
10167                res.setError("Package couldn't be installed in " + pkg.codePath, e);
10168            }
10169        }
10170
10171        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10172            // remove package from internal structures.  Note that we want deletePackageX to
10173            // delete the package data and cache directories that it created in
10174            // scanPackageLocked, unless those directories existed before we even tried to
10175            // install.
10176            if(updatedSettings) {
10177                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName);
10178                deletePackageLI(
10179                        pkgName, null, true, allUsers, perUserInstalled,
10180                        PackageManager.DELETE_KEEP_DATA,
10181                                res.removedInfo, true);
10182            }
10183            // Since we failed to install the new package we need to restore the old
10184            // package that we deleted.
10185            if (deletedPkg) {
10186                if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage);
10187                File restoreFile = new File(deletedPackage.codePath);
10188                // Parse old package
10189                boolean oldOnSd = isExternal(deletedPackage);
10190                int oldParseFlags  = mDefParseFlags | PackageParser.PARSE_CHATTY |
10191                        (isForwardLocked(deletedPackage) ? PackageParser.PARSE_FORWARD_LOCK : 0) |
10192                        (oldOnSd ? PackageParser.PARSE_ON_SDCARD : 0);
10193                int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME;
10194                try {
10195                    scanPackageLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, null);
10196                } catch (PackageManagerException e) {
10197                    Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: "
10198                            + e.getMessage());
10199                    return;
10200                }
10201                // Restore of old package succeeded. Update permissions.
10202                // writer
10203                synchronized (mPackages) {
10204                    updatePermissionsLPw(deletedPackage.packageName, deletedPackage,
10205                            UPDATE_PERMISSIONS_ALL);
10206                    // can downgrade to reader
10207                    mSettings.writeLPr();
10208                }
10209                Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade");
10210            }
10211        }
10212    }
10213
10214    private void replaceSystemPackageLI(PackageParser.Package deletedPackage,
10215            PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user,
10216            int[] allUsers, boolean[] perUserInstalled,
10217            String installerPackageName, PackageInstalledInfo res) {
10218        if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg
10219                + ", old=" + deletedPackage);
10220        boolean disabledSystem = false;
10221        boolean updatedSettings = false;
10222        parseFlags |= PackageParser.PARSE_IS_SYSTEM;
10223        if ((deletedPackage.applicationInfo.flags&ApplicationInfo.FLAG_PRIVILEGED) != 0) {
10224            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10225        }
10226        String packageName = deletedPackage.packageName;
10227        if (packageName == null) {
10228            res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10229                    "Attempt to delete null packageName.");
10230            return;
10231        }
10232        PackageParser.Package oldPkg;
10233        PackageSetting oldPkgSetting;
10234        // reader
10235        synchronized (mPackages) {
10236            oldPkg = mPackages.get(packageName);
10237            oldPkgSetting = mSettings.mPackages.get(packageName);
10238            if((oldPkg == null) || (oldPkg.applicationInfo == null) ||
10239                    (oldPkgSetting == null)) {
10240                res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE,
10241                        "Couldn't find package:" + packageName + " information");
10242                return;
10243            }
10244        }
10245
10246        killApplication(packageName, oldPkg.applicationInfo.uid, "replace sys pkg");
10247
10248        res.removedInfo.uid = oldPkg.applicationInfo.uid;
10249        res.removedInfo.removedPackage = packageName;
10250        // Remove existing system package
10251        removePackageLI(oldPkgSetting, true);
10252        // writer
10253        synchronized (mPackages) {
10254            disabledSystem = mSettings.disableSystemPackageLPw(packageName);
10255            if (!disabledSystem && deletedPackage != null) {
10256                // We didn't need to disable the .apk as a current system package,
10257                // which means we are replacing another update that is already
10258                // installed.  We need to make sure to delete the older one's .apk.
10259                res.removedInfo.args = createInstallArgsForExisting(0,
10260                        deletedPackage.applicationInfo.getCodePath(),
10261                        deletedPackage.applicationInfo.getResourcePath(),
10262                        deletedPackage.applicationInfo.nativeLibraryRootDir,
10263                        getAppDexInstructionSets(deletedPackage.applicationInfo));
10264            } else {
10265                res.removedInfo.args = null;
10266            }
10267        }
10268
10269        // Successfully disabled the old package. Now proceed with re-installation
10270        deleteCodeCacheDirsLI(packageName);
10271
10272        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10273        pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP;
10274
10275        PackageParser.Package newPackage = null;
10276        try {
10277            newPackage = scanPackageLI(pkg, parseFlags, scanFlags, 0, user);
10278            if (newPackage.mExtras != null) {
10279                final PackageSetting newPkgSetting = (PackageSetting) newPackage.mExtras;
10280                newPkgSetting.firstInstallTime = oldPkgSetting.firstInstallTime;
10281                newPkgSetting.lastUpdateTime = System.currentTimeMillis();
10282
10283                // is the update attempting to change shared user? that isn't going to work...
10284                if (oldPkgSetting.sharedUser != newPkgSetting.sharedUser) {
10285                    res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE,
10286                            "Forbidding shared user change from " + oldPkgSetting.sharedUser
10287                            + " to " + newPkgSetting.sharedUser);
10288                    updatedSettings = true;
10289                }
10290            }
10291
10292            if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) {
10293                updateSettingsLI(newPackage, installerPackageName, allUsers, perUserInstalled, res);
10294                updatedSettings = true;
10295            }
10296
10297        } catch (PackageManagerException e) {
10298            res.setError("Package couldn't be installed in " + pkg.codePath, e);
10299        }
10300
10301        if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) {
10302            // Re installation failed. Restore old information
10303            // Remove new pkg information
10304            if (newPackage != null) {
10305                removeInstalledPackageLI(newPackage, true);
10306            }
10307            // Add back the old system package
10308            try {
10309                scanPackageLI(oldPkg, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user);
10310            } catch (PackageManagerException e) {
10311                Slog.e(TAG, "Failed to restore original package: " + e.getMessage());
10312            }
10313            // Restore the old system information in Settings
10314            synchronized (mPackages) {
10315                if (disabledSystem) {
10316                    mSettings.enableSystemPackageLPw(packageName);
10317                }
10318                if (updatedSettings) {
10319                    mSettings.setInstallerPackageName(packageName,
10320                            oldPkgSetting.installerPackageName);
10321                }
10322                mSettings.writeLPr();
10323            }
10324        }
10325    }
10326
10327    private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName,
10328            int[] allUsers, boolean[] perUserInstalled,
10329            PackageInstalledInfo res) {
10330        String pkgName = newPackage.packageName;
10331        synchronized (mPackages) {
10332            //write settings. the installStatus will be incomplete at this stage.
10333            //note that the new package setting would have already been
10334            //added to mPackages. It hasn't been persisted yet.
10335            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE);
10336            mSettings.writeLPr();
10337        }
10338
10339        if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath);
10340
10341        synchronized (mPackages) {
10342            updatePermissionsLPw(newPackage.packageName, newPackage,
10343                    UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0
10344                            ? UPDATE_PERMISSIONS_ALL : 0));
10345            // For system-bundled packages, we assume that installing an upgraded version
10346            // of the package implies that the user actually wants to run that new code,
10347            // so we enable the package.
10348            if (isSystemApp(newPackage)) {
10349                // NB: implicit assumption that system package upgrades apply to all users
10350                if (DEBUG_INSTALL) {
10351                    Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName);
10352                }
10353                PackageSetting ps = mSettings.mPackages.get(pkgName);
10354                if (ps != null) {
10355                    if (res.origUsers != null) {
10356                        for (int userHandle : res.origUsers) {
10357                            ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT,
10358                                    userHandle, installerPackageName);
10359                        }
10360                    }
10361                    // Also convey the prior install/uninstall state
10362                    if (allUsers != null && perUserInstalled != null) {
10363                        for (int i = 0; i < allUsers.length; i++) {
10364                            if (DEBUG_INSTALL) {
10365                                Slog.d(TAG, "    user " + allUsers[i]
10366                                        + " => " + perUserInstalled[i]);
10367                            }
10368                            ps.setInstalled(perUserInstalled[i], allUsers[i]);
10369                        }
10370                        // these install state changes will be persisted in the
10371                        // upcoming call to mSettings.writeLPr().
10372                    }
10373                }
10374            }
10375            res.name = pkgName;
10376            res.uid = newPackage.applicationInfo.uid;
10377            res.pkg = newPackage;
10378            mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE);
10379            mSettings.setInstallerPackageName(pkgName, installerPackageName);
10380            res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10381            //to update install status
10382            mSettings.writeLPr();
10383        }
10384    }
10385
10386    private void installPackageLI(InstallArgs args, PackageInstalledInfo res) {
10387        final int installFlags = args.installFlags;
10388        String installerPackageName = args.installerPackageName;
10389        File tmpPackageFile = new File(args.getCodePath());
10390        boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0);
10391        boolean onSd = ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0);
10392        boolean replace = false;
10393        final int scanFlags = SCAN_NEW_INSTALL | SCAN_FORCE_DEX | SCAN_UPDATE_SIGNATURE;
10394        // Result object to be returned
10395        res.returnCode = PackageManager.INSTALL_SUCCEEDED;
10396
10397        if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile);
10398        // Retrieve PackageSettings and parse package
10399        final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY
10400                | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0)
10401                | (onSd ? PackageParser.PARSE_ON_SDCARD : 0);
10402        PackageParser pp = new PackageParser();
10403        pp.setSeparateProcesses(mSeparateProcesses);
10404        pp.setDisplayMetrics(mMetrics);
10405
10406        final PackageParser.Package pkg;
10407        try {
10408            pkg = pp.parsePackage(tmpPackageFile, parseFlags);
10409        } catch (PackageParserException e) {
10410            res.setError("Failed parse during installPackageLI", e);
10411            return;
10412        }
10413
10414        // Mark that we have an install time CPU ABI override.
10415        pkg.cpuAbiOverride = args.abiOverride;
10416
10417        String pkgName = res.name = pkg.packageName;
10418        if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) {
10419            if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) {
10420                res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI");
10421                return;
10422            }
10423        }
10424
10425        try {
10426            pp.collectCertificates(pkg, parseFlags);
10427            pp.collectManifestDigest(pkg);
10428        } catch (PackageParserException e) {
10429            res.setError("Failed collect during installPackageLI", e);
10430            return;
10431        }
10432
10433        /* If the installer passed in a manifest digest, compare it now. */
10434        if (args.manifestDigest != null) {
10435            if (DEBUG_INSTALL) {
10436                final String parsedManifest = pkg.manifestDigest == null ? "null"
10437                        : pkg.manifestDigest.toString();
10438                Slog.d(TAG, "Comparing manifests: " + args.manifestDigest.toString() + " vs. "
10439                        + parsedManifest);
10440            }
10441
10442            if (!args.manifestDigest.equals(pkg.manifestDigest)) {
10443                res.setError(INSTALL_FAILED_PACKAGE_CHANGED, "Manifest digest changed");
10444                return;
10445            }
10446        } else if (DEBUG_INSTALL) {
10447            final String parsedManifest = pkg.manifestDigest == null
10448                    ? "null" : pkg.manifestDigest.toString();
10449            Slog.d(TAG, "manifestDigest was not present, but parser got: " + parsedManifest);
10450        }
10451
10452        // Get rid of all references to package scan path via parser.
10453        pp = null;
10454        String oldCodePath = null;
10455        boolean systemApp = false;
10456        synchronized (mPackages) {
10457            // Check whether the newly-scanned package wants to define an already-defined perm
10458            int N = pkg.permissions.size();
10459            for (int i = N-1; i >= 0; i--) {
10460                PackageParser.Permission perm = pkg.permissions.get(i);
10461                BasePermission bp = mSettings.mPermissions.get(perm.info.name);
10462                if (bp != null) {
10463                    // If the defining package is signed with our cert, it's okay.  This
10464                    // also includes the "updating the same package" case, of course.
10465                    // "updating same package" could also involve key-rotation.
10466                    final boolean sigsOk;
10467                    if (!bp.sourcePackage.equals(pkg.packageName)
10468                            || !(bp.packageSetting instanceof PackageSetting)
10469                            || !bp.packageSetting.keySetData.isUsingUpgradeKeySets()
10470                            || ((PackageSetting) bp.packageSetting).sharedUser != null) {
10471                        sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures,
10472                                pkg.mSignatures) == PackageManager.SIGNATURE_MATCH;
10473                    } else {
10474                        sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg);
10475                    }
10476                    if (!sigsOk) {
10477                        // If the owning package is the system itself, we log but allow
10478                        // install to proceed; we fail the install on all other permission
10479                        // redefinitions.
10480                        if (!bp.sourcePackage.equals("android")) {
10481                            res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package "
10482                                    + pkg.packageName + " attempting to redeclare permission "
10483                                    + perm.info.name + " already owned by " + bp.sourcePackage);
10484                            res.origPermission = perm.info.name;
10485                            res.origPackage = bp.sourcePackage;
10486                            return;
10487                        } else {
10488                            Slog.w(TAG, "Package " + pkg.packageName
10489                                    + " attempting to redeclare system permission "
10490                                    + perm.info.name + "; ignoring new declaration");
10491                            pkg.permissions.remove(i);
10492                        }
10493                    }
10494                }
10495            }
10496
10497            // Check if installing already existing package
10498            if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) {
10499                String oldName = mSettings.mRenamedPackages.get(pkgName);
10500                if (pkg.mOriginalPackages != null
10501                        && pkg.mOriginalPackages.contains(oldName)
10502                        && mPackages.containsKey(oldName)) {
10503                    // This package is derived from an original package,
10504                    // and this device has been updating from that original
10505                    // name.  We must continue using the original name, so
10506                    // rename the new package here.
10507                    pkg.setPackageName(oldName);
10508                    pkgName = pkg.packageName;
10509                    replace = true;
10510                    if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName="
10511                            + oldName + " pkgName=" + pkgName);
10512                } else if (mPackages.containsKey(pkgName)) {
10513                    // This package, under its official name, already exists
10514                    // on the device; we should replace it.
10515                    replace = true;
10516                    if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName);
10517                }
10518            }
10519            PackageSetting ps = mSettings.mPackages.get(pkgName);
10520            if (ps != null) {
10521                if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps);
10522                oldCodePath = mSettings.mPackages.get(pkgName).codePathString;
10523                if (ps.pkg != null && ps.pkg.applicationInfo != null) {
10524                    systemApp = (ps.pkg.applicationInfo.flags &
10525                            ApplicationInfo.FLAG_SYSTEM) != 0;
10526                }
10527                res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10528            }
10529        }
10530
10531        if (systemApp && onSd) {
10532            // Disable updates to system apps on sdcard
10533            res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION,
10534                    "Cannot install updates to system apps on sdcard");
10535            return;
10536        }
10537
10538        if (!args.doRename(res.returnCode, pkg, oldCodePath)) {
10539            res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename");
10540            return;
10541        }
10542
10543        if (replace) {
10544            replacePackageLI(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user,
10545                    installerPackageName, res);
10546        } else {
10547            installNewPackageLI(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES,
10548                    args.user, installerPackageName, res);
10549        }
10550        synchronized (mPackages) {
10551            final PackageSetting ps = mSettings.mPackages.get(pkgName);
10552            if (ps != null) {
10553                res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
10554            }
10555        }
10556    }
10557
10558    private static boolean isForwardLocked(PackageParser.Package pkg) {
10559        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10560    }
10561
10562    private static boolean isForwardLocked(ApplicationInfo info) {
10563        return (info.flags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10564    }
10565
10566    private boolean isForwardLocked(PackageSetting ps) {
10567        return (ps.pkgFlags & ApplicationInfo.FLAG_FORWARD_LOCK) != 0;
10568    }
10569
10570    private static boolean isMultiArch(PackageSetting ps) {
10571        return (ps.pkgFlags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10572    }
10573
10574    private static boolean isMultiArch(ApplicationInfo info) {
10575        return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0;
10576    }
10577
10578    private static boolean isExternal(PackageParser.Package pkg) {
10579        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10580    }
10581
10582    private static boolean isExternal(PackageSetting ps) {
10583        return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10584    }
10585
10586    private static boolean isExternal(ApplicationInfo info) {
10587        return (info.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0;
10588    }
10589
10590    private static boolean isSystemApp(PackageParser.Package pkg) {
10591        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10592    }
10593
10594    private static boolean isPrivilegedApp(PackageParser.Package pkg) {
10595        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_PRIVILEGED) != 0;
10596    }
10597
10598    private static boolean isSystemApp(ApplicationInfo info) {
10599        return (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
10600    }
10601
10602    private static boolean isSystemApp(PackageSetting ps) {
10603        return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0;
10604    }
10605
10606    private static boolean isUpdatedSystemApp(PackageSetting ps) {
10607        return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10608    }
10609
10610    private static boolean isUpdatedSystemApp(PackageParser.Package pkg) {
10611        return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10612    }
10613
10614    private static boolean isUpdatedSystemApp(ApplicationInfo info) {
10615        return (info.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0;
10616    }
10617
10618    private int packageFlagsToInstallFlags(PackageSetting ps) {
10619        int installFlags = 0;
10620        if (isExternal(ps)) {
10621            installFlags |= PackageManager.INSTALL_EXTERNAL;
10622        }
10623        if (isForwardLocked(ps)) {
10624            installFlags |= PackageManager.INSTALL_FORWARD_LOCK;
10625        }
10626        return installFlags;
10627    }
10628
10629    private void deleteTempPackageFiles() {
10630        final FilenameFilter filter = new FilenameFilter() {
10631            public boolean accept(File dir, String name) {
10632                return name.startsWith("vmdl") && name.endsWith(".tmp");
10633            }
10634        };
10635        for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) {
10636            file.delete();
10637        }
10638    }
10639
10640    @Override
10641    public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId,
10642            int flags) {
10643        deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId,
10644                flags);
10645    }
10646
10647    @Override
10648    public void deletePackage(final String packageName,
10649            final IPackageDeleteObserver2 observer, final int userId, final int flags) {
10650        mContext.enforceCallingOrSelfPermission(
10651                android.Manifest.permission.DELETE_PACKAGES, null);
10652        final int uid = Binder.getCallingUid();
10653        if (UserHandle.getUserId(uid) != userId) {
10654            mContext.enforceCallingPermission(
10655                    android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
10656                    "deletePackage for user " + userId);
10657        }
10658        if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) {
10659            try {
10660                observer.onPackageDeleted(packageName,
10661                        PackageManager.DELETE_FAILED_USER_RESTRICTED, null);
10662            } catch (RemoteException re) {
10663            }
10664            return;
10665        }
10666
10667        boolean uninstallBlocked = false;
10668        if ((flags & PackageManager.DELETE_ALL_USERS) != 0) {
10669            int[] users = sUserManager.getUserIds();
10670            for (int i = 0; i < users.length; ++i) {
10671                if (getBlockUninstallForUser(packageName, users[i])) {
10672                    uninstallBlocked = true;
10673                    break;
10674                }
10675            }
10676        } else {
10677            uninstallBlocked = getBlockUninstallForUser(packageName, userId);
10678        }
10679        if (uninstallBlocked) {
10680            try {
10681                observer.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_OWNER_BLOCKED,
10682                        null);
10683            } catch (RemoteException re) {
10684            }
10685            return;
10686        }
10687
10688        if (DEBUG_REMOVE) {
10689            Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId);
10690        }
10691        // Queue up an async operation since the package deletion may take a little while.
10692        mHandler.post(new Runnable() {
10693            public void run() {
10694                mHandler.removeCallbacks(this);
10695                final int returnCode = deletePackageX(packageName, userId, flags);
10696                if (observer != null) {
10697                    try {
10698                        observer.onPackageDeleted(packageName, returnCode, null);
10699                    } catch (RemoteException e) {
10700                        Log.i(TAG, "Observer no longer exists.");
10701                    } //end catch
10702                } //end if
10703            } //end run
10704        });
10705    }
10706
10707    private boolean isPackageDeviceAdmin(String packageName, int userId) {
10708        IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface(
10709                ServiceManager.getService(Context.DEVICE_POLICY_SERVICE));
10710        try {
10711            if (dpm != null) {
10712                if (dpm.isDeviceOwner(packageName)) {
10713                    return true;
10714                }
10715                int[] users;
10716                if (userId == UserHandle.USER_ALL) {
10717                    users = sUserManager.getUserIds();
10718                } else {
10719                    users = new int[]{userId};
10720                }
10721                for (int i = 0; i < users.length; ++i) {
10722                    if (dpm.packageHasActiveAdmins(packageName, users[i])) {
10723                        return true;
10724                    }
10725                }
10726            }
10727        } catch (RemoteException e) {
10728        }
10729        return false;
10730    }
10731
10732    /**
10733     *  This method is an internal method that could be get invoked either
10734     *  to delete an installed package or to clean up a failed installation.
10735     *  After deleting an installed package, a broadcast is sent to notify any
10736     *  listeners that the package has been installed. For cleaning up a failed
10737     *  installation, the broadcast is not necessary since the package's
10738     *  installation wouldn't have sent the initial broadcast either
10739     *  The key steps in deleting a package are
10740     *  deleting the package information in internal structures like mPackages,
10741     *  deleting the packages base directories through installd
10742     *  updating mSettings to reflect current status
10743     *  persisting settings for later use
10744     *  sending a broadcast if necessary
10745     */
10746    private int deletePackageX(String packageName, int userId, int flags) {
10747        final PackageRemovedInfo info = new PackageRemovedInfo();
10748        final boolean res;
10749
10750        final UserHandle removeForUser = (flags & PackageManager.DELETE_ALL_USERS) != 0
10751                ? UserHandle.ALL : new UserHandle(userId);
10752
10753        if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) {
10754            Slog.w(TAG, "Not removing package " + packageName + ": has active device admin");
10755            return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER;
10756        }
10757
10758        boolean removedForAllUsers = false;
10759        boolean systemUpdate = false;
10760
10761        // for the uninstall-updates case and restricted profiles, remember the per-
10762        // userhandle installed state
10763        int[] allUsers;
10764        boolean[] perUserInstalled;
10765        synchronized (mPackages) {
10766            PackageSetting ps = mSettings.mPackages.get(packageName);
10767            allUsers = sUserManager.getUserIds();
10768            perUserInstalled = new boolean[allUsers.length];
10769            for (int i = 0; i < allUsers.length; i++) {
10770                perUserInstalled[i] = ps != null ? ps.getInstalled(allUsers[i]) : false;
10771            }
10772        }
10773
10774        synchronized (mInstallLock) {
10775            if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId);
10776            res = deletePackageLI(packageName, removeForUser,
10777                    true, allUsers, perUserInstalled,
10778                    flags | REMOVE_CHATTY, info, true);
10779            systemUpdate = info.isRemovedPackageSystemUpdate;
10780            if (res && !systemUpdate && mPackages.get(packageName) == null) {
10781                removedForAllUsers = true;
10782            }
10783            if (DEBUG_REMOVE) Slog.d(TAG, "delete res: systemUpdate=" + systemUpdate
10784                    + " removedForAllUsers=" + removedForAllUsers);
10785        }
10786
10787        if (res) {
10788            info.sendBroadcast(true, systemUpdate, removedForAllUsers);
10789
10790            // If the removed package was a system update, the old system package
10791            // was re-enabled; we need to broadcast this information
10792            if (systemUpdate) {
10793                Bundle extras = new Bundle(1);
10794                extras.putInt(Intent.EXTRA_UID, info.removedAppId >= 0
10795                        ? info.removedAppId : info.uid);
10796                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10797
10798                sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName,
10799                        extras, null, null, null);
10800                sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName,
10801                        extras, null, null, null);
10802                sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null,
10803                        null, packageName, null, null);
10804            }
10805        }
10806        // Force a gc here.
10807        Runtime.getRuntime().gc();
10808        // Delete the resources here after sending the broadcast to let
10809        // other processes clean up before deleting resources.
10810        if (info.args != null) {
10811            synchronized (mInstallLock) {
10812                info.args.doPostDeleteLI(true);
10813            }
10814        }
10815
10816        return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR;
10817    }
10818
10819    static class PackageRemovedInfo {
10820        String removedPackage;
10821        int uid = -1;
10822        int removedAppId = -1;
10823        int[] removedUsers = null;
10824        boolean isRemovedPackageSystemUpdate = false;
10825        // Clean up resources deleted packages.
10826        InstallArgs args = null;
10827
10828        void sendBroadcast(boolean fullRemove, boolean replacing, boolean removedForAllUsers) {
10829            Bundle extras = new Bundle(1);
10830            extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid);
10831            extras.putBoolean(Intent.EXTRA_DATA_REMOVED, fullRemove);
10832            if (replacing) {
10833                extras.putBoolean(Intent.EXTRA_REPLACING, true);
10834            }
10835            extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers);
10836            if (removedPackage != null) {
10837                sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage,
10838                        extras, null, null, removedUsers);
10839                if (fullRemove && !replacing) {
10840                    sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, removedPackage,
10841                            extras, null, null, removedUsers);
10842                }
10843            }
10844            if (removedAppId >= 0) {
10845                sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, null, null,
10846                        removedUsers);
10847            }
10848        }
10849    }
10850
10851    /*
10852     * This method deletes the package from internal data structures. If the DONT_DELETE_DATA
10853     * flag is not set, the data directory is removed as well.
10854     * make sure this flag is set for partially installed apps. If not its meaningless to
10855     * delete a partially installed application.
10856     */
10857    private void removePackageDataLI(PackageSetting ps,
10858            int[] allUserHandles, boolean[] perUserInstalled,
10859            PackageRemovedInfo outInfo, int flags, boolean writeSettings) {
10860        String packageName = ps.name;
10861        if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps);
10862        removePackageLI(ps, (flags&REMOVE_CHATTY) != 0);
10863        // Retrieve object to delete permissions for shared user later on
10864        final PackageSetting deletedPs;
10865        // reader
10866        synchronized (mPackages) {
10867            deletedPs = mSettings.mPackages.get(packageName);
10868            if (outInfo != null) {
10869                outInfo.removedPackage = packageName;
10870                outInfo.removedUsers = deletedPs != null
10871                        ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true)
10872                        : null;
10873            }
10874        }
10875        if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10876            removeDataDirsLI(packageName);
10877            schedulePackageCleaning(packageName, UserHandle.USER_ALL, true);
10878        }
10879        // writer
10880        synchronized (mPackages) {
10881            if (deletedPs != null) {
10882                if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) {
10883                    if (outInfo != null) {
10884                        mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName);
10885                        outInfo.removedAppId = mSettings.removePackageLPw(packageName);
10886                    }
10887                    if (deletedPs != null) {
10888                        updatePermissionsLPw(deletedPs.name, null, 0);
10889                        if (deletedPs.sharedUser != null) {
10890                            // remove permissions associated with package
10891                            mSettings.updateSharedUserPermsLPw(deletedPs, mGlobalGids);
10892                        }
10893                    }
10894                    clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL);
10895                }
10896                // make sure to preserve per-user disabled state if this removal was just
10897                // a downgrade of a system app to the factory package
10898                if (allUserHandles != null && perUserInstalled != null) {
10899                    if (DEBUG_REMOVE) {
10900                        Slog.d(TAG, "Propagating install state across downgrade");
10901                    }
10902                    for (int i = 0; i < allUserHandles.length; i++) {
10903                        if (DEBUG_REMOVE) {
10904                            Slog.d(TAG, "    user " + allUserHandles[i]
10905                                    + " => " + perUserInstalled[i]);
10906                        }
10907                        ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
10908                    }
10909                }
10910            }
10911            // can downgrade to reader
10912            if (writeSettings) {
10913                // Save settings now
10914                mSettings.writeLPr();
10915            }
10916        }
10917        if (outInfo != null) {
10918            // A user ID was deleted here. Go through all users and remove it
10919            // from KeyStore.
10920            removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId);
10921        }
10922    }
10923
10924    static boolean locationIsPrivileged(File path) {
10925        try {
10926            final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app")
10927                    .getCanonicalPath();
10928            return path.getCanonicalPath().startsWith(privilegedAppDir);
10929        } catch (IOException e) {
10930            Slog.e(TAG, "Unable to access code path " + path);
10931        }
10932        return false;
10933    }
10934
10935    /*
10936     * Tries to delete system package.
10937     */
10938    private boolean deleteSystemPackageLI(PackageSetting newPs,
10939            int[] allUserHandles, boolean[] perUserInstalled,
10940            int flags, PackageRemovedInfo outInfo, boolean writeSettings) {
10941        final boolean applyUserRestrictions
10942                = (allUserHandles != null) && (perUserInstalled != null);
10943        PackageSetting disabledPs = null;
10944        // Confirm if the system package has been updated
10945        // An updated system app can be deleted. This will also have to restore
10946        // the system pkg from system partition
10947        // reader
10948        synchronized (mPackages) {
10949            disabledPs = mSettings.getDisabledSystemPkgLPr(newPs.name);
10950        }
10951        if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + newPs
10952                + " disabledPs=" + disabledPs);
10953        if (disabledPs == null) {
10954            Slog.w(TAG, "Attempt to delete unknown system package "+ newPs.name);
10955            return false;
10956        } else if (DEBUG_REMOVE) {
10957            Slog.d(TAG, "Deleting system pkg from data partition");
10958        }
10959        if (DEBUG_REMOVE) {
10960            if (applyUserRestrictions) {
10961                Slog.d(TAG, "Remembering install states:");
10962                for (int i = 0; i < allUserHandles.length; i++) {
10963                    Slog.d(TAG, "   u=" + allUserHandles[i] + " inst=" + perUserInstalled[i]);
10964                }
10965            }
10966        }
10967        // Delete the updated package
10968        outInfo.isRemovedPackageSystemUpdate = true;
10969        if (disabledPs.versionCode < newPs.versionCode) {
10970            // Delete data for downgrades
10971            flags &= ~PackageManager.DELETE_KEEP_DATA;
10972        } else {
10973            // Preserve data by setting flag
10974            flags |= PackageManager.DELETE_KEEP_DATA;
10975        }
10976        boolean ret = deleteInstalledPackageLI(newPs, true, flags,
10977                allUserHandles, perUserInstalled, outInfo, writeSettings);
10978        if (!ret) {
10979            return false;
10980        }
10981        // writer
10982        synchronized (mPackages) {
10983            // Reinstate the old system package
10984            mSettings.enableSystemPackageLPw(newPs.name);
10985            // Remove any native libraries from the upgraded package.
10986            NativeLibraryHelper.removeNativeBinariesLI(newPs.legacyNativeLibraryPathString);
10987        }
10988        // Install the system package
10989        if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs);
10990        int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM;
10991        if (locationIsPrivileged(disabledPs.codePath)) {
10992            parseFlags |= PackageParser.PARSE_IS_PRIVILEGED;
10993        }
10994
10995        final PackageParser.Package newPkg;
10996        try {
10997            newPkg = scanPackageLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null);
10998        } catch (PackageManagerException e) {
10999            Slog.w(TAG, "Failed to restore system package:" + newPs.name + ": " + e.getMessage());
11000            return false;
11001        }
11002
11003        // writer
11004        synchronized (mPackages) {
11005            PackageSetting ps = mSettings.mPackages.get(newPkg.packageName);
11006            updatePermissionsLPw(newPkg.packageName, newPkg,
11007                    UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG);
11008            if (applyUserRestrictions) {
11009                if (DEBUG_REMOVE) {
11010                    Slog.d(TAG, "Propagating install state across reinstall");
11011                }
11012                for (int i = 0; i < allUserHandles.length; i++) {
11013                    if (DEBUG_REMOVE) {
11014                        Slog.d(TAG, "    user " + allUserHandles[i]
11015                                + " => " + perUserInstalled[i]);
11016                    }
11017                    ps.setInstalled(perUserInstalled[i], allUserHandles[i]);
11018                }
11019                // Regardless of writeSettings we need to ensure that this restriction
11020                // state propagation is persisted
11021                mSettings.writeAllUsersPackageRestrictionsLPr();
11022            }
11023            // can downgrade to reader here
11024            if (writeSettings) {
11025                mSettings.writeLPr();
11026            }
11027        }
11028        return true;
11029    }
11030
11031    private boolean deleteInstalledPackageLI(PackageSetting ps,
11032            boolean deleteCodeAndResources, int flags,
11033            int[] allUserHandles, boolean[] perUserInstalled,
11034            PackageRemovedInfo outInfo, boolean writeSettings) {
11035        if (outInfo != null) {
11036            outInfo.uid = ps.appId;
11037        }
11038
11039        // Delete package data from internal structures and also remove data if flag is set
11040        removePackageDataLI(ps, allUserHandles, perUserInstalled, outInfo, flags, writeSettings);
11041
11042        // Delete application code and resources
11043        if (deleteCodeAndResources && (outInfo != null)) {
11044            outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps),
11045                    ps.codePathString, ps.resourcePathString, ps.legacyNativeLibraryPathString,
11046                    getAppDexInstructionSets(ps));
11047            if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args);
11048        }
11049        return true;
11050    }
11051
11052    @Override
11053    public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall,
11054            int userId) {
11055        mContext.enforceCallingOrSelfPermission(
11056                android.Manifest.permission.DELETE_PACKAGES, null);
11057        synchronized (mPackages) {
11058            PackageSetting ps = mSettings.mPackages.get(packageName);
11059            if (ps == null) {
11060                Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName);
11061                return false;
11062            }
11063            if (!ps.getInstalled(userId)) {
11064                // Can't block uninstall for an app that is not installed or enabled.
11065                Log.i(TAG, "Package not installed in set block uninstall " + packageName);
11066                return false;
11067            }
11068            ps.setBlockUninstall(blockUninstall, userId);
11069            mSettings.writePackageRestrictionsLPr(userId);
11070        }
11071        return true;
11072    }
11073
11074    @Override
11075    public boolean getBlockUninstallForUser(String packageName, int userId) {
11076        synchronized (mPackages) {
11077            PackageSetting ps = mSettings.mPackages.get(packageName);
11078            if (ps == null) {
11079                Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName);
11080                return false;
11081            }
11082            return ps.getBlockUninstall(userId);
11083        }
11084    }
11085
11086    /*
11087     * This method handles package deletion in general
11088     */
11089    private boolean deletePackageLI(String packageName, UserHandle user,
11090            boolean deleteCodeAndResources, int[] allUserHandles, boolean[] perUserInstalled,
11091            int flags, PackageRemovedInfo outInfo,
11092            boolean writeSettings) {
11093        if (packageName == null) {
11094            Slog.w(TAG, "Attempt to delete null packageName.");
11095            return false;
11096        }
11097        if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user);
11098        PackageSetting ps;
11099        boolean dataOnly = false;
11100        int removeUser = -1;
11101        int appId = -1;
11102        synchronized (mPackages) {
11103            ps = mSettings.mPackages.get(packageName);
11104            if (ps == null) {
11105                Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11106                return false;
11107            }
11108            if ((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null
11109                    && user.getIdentifier() != UserHandle.USER_ALL) {
11110                // The caller is asking that the package only be deleted for a single
11111                // user.  To do this, we just mark its uninstalled state and delete
11112                // its data.  If this is a system app, we only allow this to happen if
11113                // they have set the special DELETE_SYSTEM_APP which requests different
11114                // semantics than normal for uninstalling system apps.
11115                if (DEBUG_REMOVE) Slog.d(TAG, "Only deleting for single user");
11116                ps.setUserState(user.getIdentifier(),
11117                        COMPONENT_ENABLED_STATE_DEFAULT,
11118                        false, //installed
11119                        true,  //stopped
11120                        true,  //notLaunched
11121                        false, //hidden
11122                        null, null, null,
11123                        false // blockUninstall
11124                        );
11125                if (!isSystemApp(ps)) {
11126                    if (ps.isAnyInstalled(sUserManager.getUserIds())) {
11127                        // Other user still have this package installed, so all
11128                        // we need to do is clear this user's data and save that
11129                        // it is uninstalled.
11130                        if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users");
11131                        removeUser = user.getIdentifier();
11132                        appId = ps.appId;
11133                        mSettings.writePackageRestrictionsLPr(removeUser);
11134                    } else {
11135                        // We need to set it back to 'installed' so the uninstall
11136                        // broadcasts will be sent correctly.
11137                        if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete");
11138                        ps.setInstalled(true, user.getIdentifier());
11139                    }
11140                } else {
11141                    // This is a system app, so we assume that the
11142                    // other users still have this package installed, so all
11143                    // we need to do is clear this user's data and save that
11144                    // it is uninstalled.
11145                    if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app");
11146                    removeUser = user.getIdentifier();
11147                    appId = ps.appId;
11148                    mSettings.writePackageRestrictionsLPr(removeUser);
11149                }
11150            }
11151        }
11152
11153        if (removeUser >= 0) {
11154            // From above, we determined that we are deleting this only
11155            // for a single user.  Continue the work here.
11156            if (DEBUG_REMOVE) Slog.d(TAG, "Updating install state for user: " + removeUser);
11157            if (outInfo != null) {
11158                outInfo.removedPackage = packageName;
11159                outInfo.removedAppId = appId;
11160                outInfo.removedUsers = new int[] {removeUser};
11161            }
11162            mInstaller.clearUserData(packageName, removeUser);
11163            removeKeystoreDataIfNeeded(removeUser, appId);
11164            schedulePackageCleaning(packageName, removeUser, false);
11165            return true;
11166        }
11167
11168        if (dataOnly) {
11169            // Delete application data first
11170            if (DEBUG_REMOVE) Slog.d(TAG, "Removing package data only");
11171            removePackageDataLI(ps, null, null, outInfo, flags, writeSettings);
11172            return true;
11173        }
11174
11175        boolean ret = false;
11176        if (isSystemApp(ps)) {
11177            if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package:" + ps.name);
11178            // When an updated system application is deleted we delete the existing resources as well and
11179            // fall back to existing code in system partition
11180            ret = deleteSystemPackageLI(ps, allUserHandles, perUserInstalled,
11181                    flags, outInfo, writeSettings);
11182        } else {
11183            if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package:" + ps.name);
11184            // Kill application pre-emptively especially for apps on sd.
11185            killApplication(packageName, ps.appId, "uninstall pkg");
11186            ret = deleteInstalledPackageLI(ps, deleteCodeAndResources, flags,
11187                    allUserHandles, perUserInstalled,
11188                    outInfo, writeSettings);
11189        }
11190
11191        return ret;
11192    }
11193
11194    private final class ClearStorageConnection implements ServiceConnection {
11195        IMediaContainerService mContainerService;
11196
11197        @Override
11198        public void onServiceConnected(ComponentName name, IBinder service) {
11199            synchronized (this) {
11200                mContainerService = IMediaContainerService.Stub.asInterface(service);
11201                notifyAll();
11202            }
11203        }
11204
11205        @Override
11206        public void onServiceDisconnected(ComponentName name) {
11207        }
11208    }
11209
11210    private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) {
11211        final boolean mounted;
11212        if (Environment.isExternalStorageEmulated()) {
11213            mounted = true;
11214        } else {
11215            final String status = Environment.getExternalStorageState();
11216
11217            mounted = status.equals(Environment.MEDIA_MOUNTED)
11218                    || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY);
11219        }
11220
11221        if (!mounted) {
11222            return;
11223        }
11224
11225        final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT);
11226        int[] users;
11227        if (userId == UserHandle.USER_ALL) {
11228            users = sUserManager.getUserIds();
11229        } else {
11230            users = new int[] { userId };
11231        }
11232        final ClearStorageConnection conn = new ClearStorageConnection();
11233        if (mContext.bindServiceAsUser(
11234                containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.OWNER)) {
11235            try {
11236                for (int curUser : users) {
11237                    long timeout = SystemClock.uptimeMillis() + 5000;
11238                    synchronized (conn) {
11239                        long now = SystemClock.uptimeMillis();
11240                        while (conn.mContainerService == null && now < timeout) {
11241                            try {
11242                                conn.wait(timeout - now);
11243                            } catch (InterruptedException e) {
11244                            }
11245                        }
11246                    }
11247                    if (conn.mContainerService == null) {
11248                        return;
11249                    }
11250
11251                    final UserEnvironment userEnv = new UserEnvironment(curUser);
11252                    clearDirectory(conn.mContainerService,
11253                            userEnv.buildExternalStorageAppCacheDirs(packageName));
11254                    if (allData) {
11255                        clearDirectory(conn.mContainerService,
11256                                userEnv.buildExternalStorageAppDataDirs(packageName));
11257                        clearDirectory(conn.mContainerService,
11258                                userEnv.buildExternalStorageAppMediaDirs(packageName));
11259                    }
11260                }
11261            } finally {
11262                mContext.unbindService(conn);
11263            }
11264        }
11265    }
11266
11267    @Override
11268    public void clearApplicationUserData(final String packageName,
11269            final IPackageDataObserver observer, final int userId) {
11270        mContext.enforceCallingOrSelfPermission(
11271                android.Manifest.permission.CLEAR_APP_USER_DATA, null);
11272        enforceCrossUserPermission(Binder.getCallingUid(), userId, true, false, "clear application data");
11273        // Queue up an async operation since the package deletion may take a little while.
11274        mHandler.post(new Runnable() {
11275            public void run() {
11276                mHandler.removeCallbacks(this);
11277                final boolean succeeded;
11278                synchronized (mInstallLock) {
11279                    succeeded = clearApplicationUserDataLI(packageName, userId);
11280                }
11281                clearExternalStorageDataSync(packageName, userId, true);
11282                if (succeeded) {
11283                    // invoke DeviceStorageMonitor's update method to clear any notifications
11284                    DeviceStorageMonitorInternal
11285                            dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
11286                    if (dsm != null) {
11287                        dsm.checkMemory();
11288                    }
11289                }
11290                if(observer != null) {
11291                    try {
11292                        observer.onRemoveCompleted(packageName, succeeded);
11293                    } catch (RemoteException e) {
11294                        Log.i(TAG, "Observer no longer exists.");
11295                    }
11296                } //end if observer
11297            } //end run
11298        });
11299    }
11300
11301    private boolean clearApplicationUserDataLI(String packageName, int userId) {
11302        if (packageName == null) {
11303            Slog.w(TAG, "Attempt to delete null packageName.");
11304            return false;
11305        }
11306
11307        // Try finding details about the requested package
11308        PackageParser.Package pkg;
11309        synchronized (mPackages) {
11310            pkg = mPackages.get(packageName);
11311            if (pkg == null) {
11312                final PackageSetting ps = mSettings.mPackages.get(packageName);
11313                if (ps != null) {
11314                    pkg = ps.pkg;
11315                }
11316            }
11317        }
11318
11319        if (pkg == null) {
11320            Slog.w(TAG, "Package named '" + packageName + "' doesn't exist.");
11321        }
11322
11323        // Always delete data directories for package, even if we found no other
11324        // record of app. This helps users recover from UID mismatches without
11325        // resorting to a full data wipe.
11326        int retCode = mInstaller.clearUserData(packageName, userId);
11327        if (retCode < 0) {
11328            Slog.w(TAG, "Couldn't remove cache files for package: " + packageName);
11329            return false;
11330        }
11331
11332        if (pkg == null) {
11333            return false;
11334        }
11335
11336        if (pkg != null && pkg.applicationInfo != null) {
11337            final int appId = pkg.applicationInfo.uid;
11338            removeKeystoreDataIfNeeded(userId, appId);
11339        }
11340
11341        // Create a native library symlink only if we have native libraries
11342        // and if the native libraries are 32 bit libraries. We do not provide
11343        // this symlink for 64 bit libraries.
11344        if (pkg != null && pkg.applicationInfo.primaryCpuAbi != null &&
11345                !VMRuntime.is64BitAbi(pkg.applicationInfo.primaryCpuAbi)) {
11346            final String nativeLibPath = pkg.applicationInfo.nativeLibraryDir;
11347            if (mInstaller.linkNativeLibraryDirectory(pkg.packageName, nativeLibPath, userId) < 0) {
11348                Slog.w(TAG, "Failed linking native library dir");
11349                return false;
11350            }
11351        }
11352
11353        return true;
11354    }
11355
11356    /**
11357     * Remove entries from the keystore daemon. Will only remove it if the
11358     * {@code appId} is valid.
11359     */
11360    private static void removeKeystoreDataIfNeeded(int userId, int appId) {
11361        if (appId < 0) {
11362            return;
11363        }
11364
11365        final KeyStore keyStore = KeyStore.getInstance();
11366        if (keyStore != null) {
11367            if (userId == UserHandle.USER_ALL) {
11368                for (final int individual : sUserManager.getUserIds()) {
11369                    keyStore.clearUid(UserHandle.getUid(individual, appId));
11370                }
11371            } else {
11372                keyStore.clearUid(UserHandle.getUid(userId, appId));
11373            }
11374        } else {
11375            Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId);
11376        }
11377    }
11378
11379    @Override
11380    public void deleteApplicationCacheFiles(final String packageName,
11381            final IPackageDataObserver observer) {
11382        mContext.enforceCallingOrSelfPermission(
11383                android.Manifest.permission.DELETE_CACHE_FILES, null);
11384        // Queue up an async operation since the package deletion may take a little while.
11385        final int userId = UserHandle.getCallingUserId();
11386        mHandler.post(new Runnable() {
11387            public void run() {
11388                mHandler.removeCallbacks(this);
11389                final boolean succeded;
11390                synchronized (mInstallLock) {
11391                    succeded = deleteApplicationCacheFilesLI(packageName, userId);
11392                }
11393                clearExternalStorageDataSync(packageName, userId, false);
11394                if(observer != null) {
11395                    try {
11396                        observer.onRemoveCompleted(packageName, succeded);
11397                    } catch (RemoteException e) {
11398                        Log.i(TAG, "Observer no longer exists.");
11399                    }
11400                } //end if observer
11401            } //end run
11402        });
11403    }
11404
11405    private boolean deleteApplicationCacheFilesLI(String packageName, int userId) {
11406        if (packageName == null) {
11407            Slog.w(TAG, "Attempt to delete null packageName.");
11408            return false;
11409        }
11410        PackageParser.Package p;
11411        synchronized (mPackages) {
11412            p = mPackages.get(packageName);
11413        }
11414        if (p == null) {
11415            Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11416            return false;
11417        }
11418        final ApplicationInfo applicationInfo = p.applicationInfo;
11419        if (applicationInfo == null) {
11420            Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11421            return false;
11422        }
11423        int retCode = mInstaller.deleteCacheFiles(packageName, userId);
11424        if (retCode < 0) {
11425            Slog.w(TAG, "Couldn't remove cache files for package: "
11426                       + packageName + " u" + userId);
11427            return false;
11428        }
11429        return true;
11430    }
11431
11432    @Override
11433    public void getPackageSizeInfo(final String packageName, int userHandle,
11434            final IPackageStatsObserver observer) {
11435        mContext.enforceCallingOrSelfPermission(
11436                android.Manifest.permission.GET_PACKAGE_SIZE, null);
11437        if (packageName == null) {
11438            throw new IllegalArgumentException("Attempt to get size of null packageName");
11439        }
11440
11441        PackageStats stats = new PackageStats(packageName, userHandle);
11442
11443        /*
11444         * Queue up an async operation since the package measurement may take a
11445         * little while.
11446         */
11447        Message msg = mHandler.obtainMessage(INIT_COPY);
11448        msg.obj = new MeasureParams(stats, observer);
11449        mHandler.sendMessage(msg);
11450    }
11451
11452    private boolean getPackageSizeInfoLI(String packageName, int userHandle,
11453            PackageStats pStats) {
11454        if (packageName == null) {
11455            Slog.w(TAG, "Attempt to get size of null packageName.");
11456            return false;
11457        }
11458        PackageParser.Package p;
11459        boolean dataOnly = false;
11460        String libDirRoot = null;
11461        String asecPath = null;
11462        PackageSetting ps = null;
11463        synchronized (mPackages) {
11464            p = mPackages.get(packageName);
11465            ps = mSettings.mPackages.get(packageName);
11466            if(p == null) {
11467                dataOnly = true;
11468                if((ps == null) || (ps.pkg == null)) {
11469                    Slog.w(TAG, "Package named '" + packageName +"' doesn't exist.");
11470                    return false;
11471                }
11472                p = ps.pkg;
11473            }
11474            if (ps != null) {
11475                libDirRoot = ps.legacyNativeLibraryPathString;
11476            }
11477            if (p != null && (isExternal(p) || isForwardLocked(p))) {
11478                String secureContainerId = cidFromCodePath(p.applicationInfo.getBaseCodePath());
11479                if (secureContainerId != null) {
11480                    asecPath = PackageHelper.getSdFilesystem(secureContainerId);
11481                }
11482            }
11483        }
11484        String publicSrcDir = null;
11485        if(!dataOnly) {
11486            final ApplicationInfo applicationInfo = p.applicationInfo;
11487            if (applicationInfo == null) {
11488                Slog.w(TAG, "Package " + packageName + " has no applicationInfo.");
11489                return false;
11490            }
11491            if (isForwardLocked(p)) {
11492                publicSrcDir = applicationInfo.getBaseResourcePath();
11493            }
11494        }
11495        // TODO: extend to measure size of split APKs
11496        // TODO(multiArch): Extend getSizeInfo to look at the full subdirectory tree,
11497        // not just the first level.
11498        // TODO(multiArch): Extend getSizeInfo to look at *all* instruction sets, not
11499        // just the primary.
11500        String[] dexCodeInstructionSets = getDexCodeInstructionSets(getAppDexInstructionSets(ps));
11501        int res = mInstaller.getSizeInfo(packageName, userHandle, p.baseCodePath, libDirRoot,
11502                publicSrcDir, asecPath, dexCodeInstructionSets, pStats);
11503        if (res < 0) {
11504            return false;
11505        }
11506
11507        // Fix-up for forward-locked applications in ASEC containers.
11508        if (!isExternal(p)) {
11509            pStats.codeSize += pStats.externalCodeSize;
11510            pStats.externalCodeSize = 0L;
11511        }
11512
11513        return true;
11514    }
11515
11516
11517    @Override
11518    public void addPackageToPreferred(String packageName) {
11519        Slog.w(TAG, "addPackageToPreferred: this is now a no-op");
11520    }
11521
11522    @Override
11523    public void removePackageFromPreferred(String packageName) {
11524        Slog.w(TAG, "removePackageFromPreferred: this is now a no-op");
11525    }
11526
11527    @Override
11528    public List<PackageInfo> getPreferredPackages(int flags) {
11529        return new ArrayList<PackageInfo>();
11530    }
11531
11532    private int getUidTargetSdkVersionLockedLPr(int uid) {
11533        Object obj = mSettings.getUserIdLPr(uid);
11534        if (obj instanceof SharedUserSetting) {
11535            final SharedUserSetting sus = (SharedUserSetting) obj;
11536            int vers = Build.VERSION_CODES.CUR_DEVELOPMENT;
11537            final Iterator<PackageSetting> it = sus.packages.iterator();
11538            while (it.hasNext()) {
11539                final PackageSetting ps = it.next();
11540                if (ps.pkg != null) {
11541                    int v = ps.pkg.applicationInfo.targetSdkVersion;
11542                    if (v < vers) vers = v;
11543                }
11544            }
11545            return vers;
11546        } else if (obj instanceof PackageSetting) {
11547            final PackageSetting ps = (PackageSetting) obj;
11548            if (ps.pkg != null) {
11549                return ps.pkg.applicationInfo.targetSdkVersion;
11550            }
11551        }
11552        return Build.VERSION_CODES.CUR_DEVELOPMENT;
11553    }
11554
11555    @Override
11556    public void addPreferredActivity(IntentFilter filter, int match,
11557            ComponentName[] set, ComponentName activity, int userId) {
11558        addPreferredActivityInternal(filter, match, set, activity, true, userId,
11559                "Adding preferred");
11560    }
11561
11562    private void addPreferredActivityInternal(IntentFilter filter, int match,
11563            ComponentName[] set, ComponentName activity, boolean always, int userId,
11564            String opname) {
11565        // writer
11566        int callingUid = Binder.getCallingUid();
11567        enforceCrossUserPermission(callingUid, userId, true, false, "add preferred activity");
11568        if (filter.countActions() == 0) {
11569            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11570            return;
11571        }
11572        synchronized (mPackages) {
11573            if (mContext.checkCallingOrSelfPermission(
11574                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11575                    != PackageManager.PERMISSION_GRANTED) {
11576                if (getUidTargetSdkVersionLockedLPr(callingUid)
11577                        < Build.VERSION_CODES.FROYO) {
11578                    Slog.w(TAG, "Ignoring addPreferredActivity() from uid "
11579                            + callingUid);
11580                    return;
11581                }
11582                mContext.enforceCallingOrSelfPermission(
11583                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11584            }
11585
11586            PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId);
11587            Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user "
11588                    + userId + ":");
11589            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11590            pir.addFilter(new PreferredActivity(filter, match, set, activity, always));
11591            mSettings.writePackageRestrictionsLPr(userId);
11592        }
11593    }
11594
11595    @Override
11596    public void replacePreferredActivity(IntentFilter filter, int match,
11597            ComponentName[] set, ComponentName activity, int userId) {
11598        if (filter.countActions() != 1) {
11599            throw new IllegalArgumentException(
11600                    "replacePreferredActivity expects filter to have only 1 action.");
11601        }
11602        if (filter.countDataAuthorities() != 0
11603                || filter.countDataPaths() != 0
11604                || filter.countDataSchemes() > 1
11605                || filter.countDataTypes() != 0) {
11606            throw new IllegalArgumentException(
11607                    "replacePreferredActivity expects filter to have no data authorities, " +
11608                    "paths, or types; and at most one scheme.");
11609        }
11610
11611        final int callingUid = Binder.getCallingUid();
11612        enforceCrossUserPermission(callingUid, userId, true, false, "replace preferred activity");
11613        synchronized (mPackages) {
11614            if (mContext.checkCallingOrSelfPermission(
11615                    android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11616                    != PackageManager.PERMISSION_GRANTED) {
11617                if (getUidTargetSdkVersionLockedLPr(callingUid)
11618                        < Build.VERSION_CODES.FROYO) {
11619                    Slog.w(TAG, "Ignoring replacePreferredActivity() from uid "
11620                            + Binder.getCallingUid());
11621                    return;
11622                }
11623                mContext.enforceCallingOrSelfPermission(
11624                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11625            }
11626
11627            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11628            if (pir != null) {
11629                // Get all of the existing entries that exactly match this filter.
11630                ArrayList<PreferredActivity> existing = pir.findFilters(filter);
11631                if (existing != null && existing.size() == 1) {
11632                    PreferredActivity cur = existing.get(0);
11633                    if (DEBUG_PREFERRED) {
11634                        Slog.i(TAG, "Checking replace of preferred:");
11635                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11636                        if (!cur.mPref.mAlways) {
11637                            Slog.i(TAG, "  -- CUR; not mAlways!");
11638                        } else {
11639                            Slog.i(TAG, "  -- CUR: mMatch=" + cur.mPref.mMatch);
11640                            Slog.i(TAG, "  -- CUR: mSet="
11641                                    + Arrays.toString(cur.mPref.mSetComponents));
11642                            Slog.i(TAG, "  -- CUR: mComponent=" + cur.mPref.mShortComponent);
11643                            Slog.i(TAG, "  -- NEW: mMatch="
11644                                    + (match&IntentFilter.MATCH_CATEGORY_MASK));
11645                            Slog.i(TAG, "  -- CUR: mSet=" + Arrays.toString(set));
11646                            Slog.i(TAG, "  -- CUR: mComponent=" + activity.flattenToShortString());
11647                        }
11648                    }
11649                    if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity)
11650                            && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK)
11651                            && cur.mPref.sameSet(set)) {
11652                        // Setting the preferred activity to what it happens to be already
11653                        if (DEBUG_PREFERRED) {
11654                            Slog.i(TAG, "Replacing with same preferred activity "
11655                                    + cur.mPref.mShortComponent + " for user "
11656                                    + userId + ":");
11657                            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11658                        }
11659                        return;
11660                    }
11661                }
11662
11663                if (existing != null) {
11664                    if (DEBUG_PREFERRED) {
11665                        Slog.i(TAG, existing.size() + " existing preferred matches for:");
11666                        filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11667                    }
11668                    for (int i = 0; i < existing.size(); i++) {
11669                        PreferredActivity pa = existing.get(i);
11670                        if (DEBUG_PREFERRED) {
11671                            Slog.i(TAG, "Removing existing preferred activity "
11672                                    + pa.mPref.mComponent + ":");
11673                            pa.dump(new LogPrinter(Log.INFO, TAG), "  ");
11674                        }
11675                        pir.removeFilter(pa);
11676                    }
11677                }
11678            }
11679            addPreferredActivityInternal(filter, match, set, activity, true, userId,
11680                    "Replacing preferred");
11681        }
11682    }
11683
11684    @Override
11685    public void clearPackagePreferredActivities(String packageName) {
11686        final int uid = Binder.getCallingUid();
11687        // writer
11688        synchronized (mPackages) {
11689            PackageParser.Package pkg = mPackages.get(packageName);
11690            if (pkg == null || pkg.applicationInfo.uid != uid) {
11691                if (mContext.checkCallingOrSelfPermission(
11692                        android.Manifest.permission.SET_PREFERRED_APPLICATIONS)
11693                        != PackageManager.PERMISSION_GRANTED) {
11694                    if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid())
11695                            < Build.VERSION_CODES.FROYO) {
11696                        Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid "
11697                                + Binder.getCallingUid());
11698                        return;
11699                    }
11700                    mContext.enforceCallingOrSelfPermission(
11701                            android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11702                }
11703            }
11704
11705            int user = UserHandle.getCallingUserId();
11706            if (clearPackagePreferredActivitiesLPw(packageName, user)) {
11707                mSettings.writePackageRestrictionsLPr(user);
11708                scheduleWriteSettingsLocked();
11709            }
11710        }
11711    }
11712
11713    /** This method takes a specific user id as well as UserHandle.USER_ALL. */
11714    boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) {
11715        ArrayList<PreferredActivity> removed = null;
11716        boolean changed = false;
11717        for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
11718            final int thisUserId = mSettings.mPreferredActivities.keyAt(i);
11719            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
11720            if (userId != UserHandle.USER_ALL && userId != thisUserId) {
11721                continue;
11722            }
11723            Iterator<PreferredActivity> it = pir.filterIterator();
11724            while (it.hasNext()) {
11725                PreferredActivity pa = it.next();
11726                // Mark entry for removal only if it matches the package name
11727                // and the entry is of type "always".
11728                if (packageName == null ||
11729                        (pa.mPref.mComponent.getPackageName().equals(packageName)
11730                                && pa.mPref.mAlways)) {
11731                    if (removed == null) {
11732                        removed = new ArrayList<PreferredActivity>();
11733                    }
11734                    removed.add(pa);
11735                }
11736            }
11737            if (removed != null) {
11738                for (int j=0; j<removed.size(); j++) {
11739                    PreferredActivity pa = removed.get(j);
11740                    pir.removeFilter(pa);
11741                }
11742                changed = true;
11743            }
11744        }
11745        return changed;
11746    }
11747
11748    @Override
11749    public void resetPreferredActivities(int userId) {
11750        /* TODO: Actually use userId. Why is it being passed in? */
11751        mContext.enforceCallingOrSelfPermission(
11752                android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null);
11753        // writer
11754        synchronized (mPackages) {
11755            int user = UserHandle.getCallingUserId();
11756            clearPackagePreferredActivitiesLPw(null, user);
11757            mSettings.readDefaultPreferredAppsLPw(this, user);
11758            mSettings.writePackageRestrictionsLPr(user);
11759            scheduleWriteSettingsLocked();
11760        }
11761    }
11762
11763    @Override
11764    public int getPreferredActivities(List<IntentFilter> outFilters,
11765            List<ComponentName> outActivities, String packageName) {
11766
11767        int num = 0;
11768        final int userId = UserHandle.getCallingUserId();
11769        // reader
11770        synchronized (mPackages) {
11771            PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId);
11772            if (pir != null) {
11773                final Iterator<PreferredActivity> it = pir.filterIterator();
11774                while (it.hasNext()) {
11775                    final PreferredActivity pa = it.next();
11776                    if (packageName == null
11777                            || (pa.mPref.mComponent.getPackageName().equals(packageName)
11778                                    && pa.mPref.mAlways)) {
11779                        if (outFilters != null) {
11780                            outFilters.add(new IntentFilter(pa));
11781                        }
11782                        if (outActivities != null) {
11783                            outActivities.add(pa.mPref.mComponent);
11784                        }
11785                    }
11786                }
11787            }
11788        }
11789
11790        return num;
11791    }
11792
11793    @Override
11794    public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity,
11795            int userId) {
11796        int callingUid = Binder.getCallingUid();
11797        if (callingUid != Process.SYSTEM_UID) {
11798            throw new SecurityException(
11799                    "addPersistentPreferredActivity can only be run by the system");
11800        }
11801        if (filter.countActions() == 0) {
11802            Slog.w(TAG, "Cannot set a preferred activity with no filter actions");
11803            return;
11804        }
11805        synchronized (mPackages) {
11806            Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId +
11807                    " :");
11808            filter.dump(new LogPrinter(Log.INFO, TAG), "  ");
11809            mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter(
11810                    new PersistentPreferredActivity(filter, activity));
11811            mSettings.writePackageRestrictionsLPr(userId);
11812        }
11813    }
11814
11815    @Override
11816    public void clearPackagePersistentPreferredActivities(String packageName, int userId) {
11817        int callingUid = Binder.getCallingUid();
11818        if (callingUid != Process.SYSTEM_UID) {
11819            throw new SecurityException(
11820                    "clearPackagePersistentPreferredActivities can only be run by the system");
11821        }
11822        ArrayList<PersistentPreferredActivity> removed = null;
11823        boolean changed = false;
11824        synchronized (mPackages) {
11825            for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) {
11826                final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i);
11827                PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities
11828                        .valueAt(i);
11829                if (userId != thisUserId) {
11830                    continue;
11831                }
11832                Iterator<PersistentPreferredActivity> it = ppir.filterIterator();
11833                while (it.hasNext()) {
11834                    PersistentPreferredActivity ppa = it.next();
11835                    // Mark entry for removal only if it matches the package name.
11836                    if (ppa.mComponent.getPackageName().equals(packageName)) {
11837                        if (removed == null) {
11838                            removed = new ArrayList<PersistentPreferredActivity>();
11839                        }
11840                        removed.add(ppa);
11841                    }
11842                }
11843                if (removed != null) {
11844                    for (int j=0; j<removed.size(); j++) {
11845                        PersistentPreferredActivity ppa = removed.get(j);
11846                        ppir.removeFilter(ppa);
11847                    }
11848                    changed = true;
11849                }
11850            }
11851
11852            if (changed) {
11853                mSettings.writePackageRestrictionsLPr(userId);
11854            }
11855        }
11856    }
11857
11858    @Override
11859    public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage,
11860            int ownerUserId, int sourceUserId, int targetUserId, int flags) {
11861        mContext.enforceCallingOrSelfPermission(
11862                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11863        int callingUid = Binder.getCallingUid();
11864        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11865        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11866        if (intentFilter.countActions() == 0) {
11867            Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions");
11868            return;
11869        }
11870        synchronized (mPackages) {
11871            CrossProfileIntentFilter filter = new CrossProfileIntentFilter(intentFilter,
11872                    ownerPackage, UserHandle.getUserId(callingUid), targetUserId, flags);
11873            mSettings.editCrossProfileIntentResolverLPw(sourceUserId).addFilter(filter);
11874            mSettings.writePackageRestrictionsLPr(sourceUserId);
11875        }
11876    }
11877
11878    @Override
11879    public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage,
11880            int ownerUserId) {
11881        mContext.enforceCallingOrSelfPermission(
11882                        android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null);
11883        int callingUid = Binder.getCallingUid();
11884        enforceOwnerRights(ownerPackage, ownerUserId, callingUid);
11885        enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId);
11886        int callingUserId = UserHandle.getUserId(callingUid);
11887        synchronized (mPackages) {
11888            CrossProfileIntentResolver resolver =
11889                    mSettings.editCrossProfileIntentResolverLPw(sourceUserId);
11890            HashSet<CrossProfileIntentFilter> set =
11891                    new HashSet<CrossProfileIntentFilter>(resolver.filterSet());
11892            for (CrossProfileIntentFilter filter : set) {
11893                if (filter.getOwnerPackage().equals(ownerPackage)
11894                        && filter.getOwnerUserId() == callingUserId) {
11895                    resolver.removeFilter(filter);
11896                }
11897            }
11898            mSettings.writePackageRestrictionsLPr(sourceUserId);
11899        }
11900    }
11901
11902    // Enforcing that callingUid is owning pkg on userId
11903    private void enforceOwnerRights(String pkg, int userId, int callingUid) {
11904        // The system owns everything.
11905        if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) {
11906            return;
11907        }
11908        int callingUserId = UserHandle.getUserId(callingUid);
11909        if (callingUserId != userId) {
11910            throw new SecurityException("calling uid " + callingUid
11911                    + " pretends to own " + pkg + " on user " + userId + " but belongs to user "
11912                    + callingUserId);
11913        }
11914        PackageInfo pi = getPackageInfo(pkg, 0, callingUserId);
11915        if (pi == null) {
11916            throw new IllegalArgumentException("Unknown package " + pkg + " on user "
11917                    + callingUserId);
11918        }
11919        if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) {
11920            throw new SecurityException("Calling uid " + callingUid
11921                    + " does not own package " + pkg);
11922        }
11923    }
11924
11925    @Override
11926    public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) {
11927        Intent intent = new Intent(Intent.ACTION_MAIN);
11928        intent.addCategory(Intent.CATEGORY_HOME);
11929
11930        final int callingUserId = UserHandle.getCallingUserId();
11931        List<ResolveInfo> list = queryIntentActivities(intent, null,
11932                PackageManager.GET_META_DATA, callingUserId);
11933        ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0,
11934                true, false, false, callingUserId);
11935
11936        allHomeCandidates.clear();
11937        if (list != null) {
11938            for (ResolveInfo ri : list) {
11939                allHomeCandidates.add(ri);
11940            }
11941        }
11942        return (preferred == null || preferred.activityInfo == null)
11943                ? null
11944                : new ComponentName(preferred.activityInfo.packageName,
11945                        preferred.activityInfo.name);
11946    }
11947
11948    @Override
11949    public void setApplicationEnabledSetting(String appPackageName,
11950            int newState, int flags, int userId, String callingPackage) {
11951        if (!sUserManager.exists(userId)) return;
11952        if (callingPackage == null) {
11953            callingPackage = Integer.toString(Binder.getCallingUid());
11954        }
11955        setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage);
11956    }
11957
11958    @Override
11959    public void setComponentEnabledSetting(ComponentName componentName,
11960            int newState, int flags, int userId) {
11961        if (!sUserManager.exists(userId)) return;
11962        setEnabledSetting(componentName.getPackageName(),
11963                componentName.getClassName(), newState, flags, userId, null);
11964    }
11965
11966    private void setEnabledSetting(final String packageName, String className, int newState,
11967            final int flags, int userId, String callingPackage) {
11968        if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT
11969              || newState == COMPONENT_ENABLED_STATE_ENABLED
11970              || newState == COMPONENT_ENABLED_STATE_DISABLED
11971              || newState == COMPONENT_ENABLED_STATE_DISABLED_USER
11972              || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) {
11973            throw new IllegalArgumentException("Invalid new component state: "
11974                    + newState);
11975        }
11976        PackageSetting pkgSetting;
11977        final int uid = Binder.getCallingUid();
11978        final int permission = mContext.checkCallingOrSelfPermission(
11979                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
11980        enforceCrossUserPermission(uid, userId, false, true, "set enabled");
11981        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
11982        boolean sendNow = false;
11983        boolean isApp = (className == null);
11984        String componentName = isApp ? packageName : className;
11985        int packageUid = -1;
11986        ArrayList<String> components;
11987
11988        // writer
11989        synchronized (mPackages) {
11990            pkgSetting = mSettings.mPackages.get(packageName);
11991            if (pkgSetting == null) {
11992                if (className == null) {
11993                    throw new IllegalArgumentException(
11994                            "Unknown package: " + packageName);
11995                }
11996                throw new IllegalArgumentException(
11997                        "Unknown component: " + packageName
11998                        + "/" + className);
11999            }
12000            // Allow root and verify that userId is not being specified by a different user
12001            if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) {
12002                throw new SecurityException(
12003                        "Permission Denial: attempt to change component state from pid="
12004                        + Binder.getCallingPid()
12005                        + ", uid=" + uid + ", package uid=" + pkgSetting.appId);
12006            }
12007            if (className == null) {
12008                // We're dealing with an application/package level state change
12009                if (pkgSetting.getEnabled(userId) == newState) {
12010                    // Nothing to do
12011                    return;
12012                }
12013                if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
12014                    || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
12015                    // Don't care about who enables an app.
12016                    callingPackage = null;
12017                }
12018                pkgSetting.setEnabled(newState, userId, callingPackage);
12019                // pkgSetting.pkg.mSetEnabled = newState;
12020            } else {
12021                // We're dealing with a component level state change
12022                // First, verify that this is a valid class name.
12023                PackageParser.Package pkg = pkgSetting.pkg;
12024                if (pkg == null || !pkg.hasComponentClassName(className)) {
12025                    if (pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.JELLY_BEAN) {
12026                        throw new IllegalArgumentException("Component class " + className
12027                                + " does not exist in " + packageName);
12028                    } else {
12029                        Slog.w(TAG, "Failed setComponentEnabledSetting: component class "
12030                                + className + " does not exist in " + packageName);
12031                    }
12032                }
12033                switch (newState) {
12034                case COMPONENT_ENABLED_STATE_ENABLED:
12035                    if (!pkgSetting.enableComponentLPw(className, userId)) {
12036                        return;
12037                    }
12038                    break;
12039                case COMPONENT_ENABLED_STATE_DISABLED:
12040                    if (!pkgSetting.disableComponentLPw(className, userId)) {
12041                        return;
12042                    }
12043                    break;
12044                case COMPONENT_ENABLED_STATE_DEFAULT:
12045                    if (!pkgSetting.restoreComponentLPw(className, userId)) {
12046                        return;
12047                    }
12048                    break;
12049                default:
12050                    Slog.e(TAG, "Invalid new component state: " + newState);
12051                    return;
12052                }
12053            }
12054            mSettings.writePackageRestrictionsLPr(userId);
12055            components = mPendingBroadcasts.get(userId, packageName);
12056            final boolean newPackage = components == null;
12057            if (newPackage) {
12058                components = new ArrayList<String>();
12059            }
12060            if (!components.contains(componentName)) {
12061                components.add(componentName);
12062            }
12063            if ((flags&PackageManager.DONT_KILL_APP) == 0) {
12064                sendNow = true;
12065                // Purge entry from pending broadcast list if another one exists already
12066                // since we are sending one right away.
12067                mPendingBroadcasts.remove(userId, packageName);
12068            } else {
12069                if (newPackage) {
12070                    mPendingBroadcasts.put(userId, packageName, components);
12071                }
12072                if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) {
12073                    // Schedule a message
12074                    mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY);
12075                }
12076            }
12077        }
12078
12079        long callingId = Binder.clearCallingIdentity();
12080        try {
12081            if (sendNow) {
12082                packageUid = UserHandle.getUid(userId, pkgSetting.appId);
12083                sendPackageChangedBroadcast(packageName,
12084                        (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid);
12085            }
12086        } finally {
12087            Binder.restoreCallingIdentity(callingId);
12088        }
12089    }
12090
12091    private void sendPackageChangedBroadcast(String packageName,
12092            boolean killFlag, ArrayList<String> componentNames, int packageUid) {
12093        if (DEBUG_INSTALL)
12094            Log.v(TAG, "Sending package changed: package=" + packageName + " components="
12095                    + componentNames);
12096        Bundle extras = new Bundle(4);
12097        extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0));
12098        String nameList[] = new String[componentNames.size()];
12099        componentNames.toArray(nameList);
12100        extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList);
12101        extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag);
12102        extras.putInt(Intent.EXTRA_UID, packageUid);
12103        sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED,  packageName, extras, null, null,
12104                new int[] {UserHandle.getUserId(packageUid)});
12105    }
12106
12107    @Override
12108    public void setPackageStoppedState(String packageName, boolean stopped, int userId) {
12109        if (!sUserManager.exists(userId)) return;
12110        final int uid = Binder.getCallingUid();
12111        final int permission = mContext.checkCallingOrSelfPermission(
12112                android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE);
12113        final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED);
12114        enforceCrossUserPermission(uid, userId, true, true, "stop package");
12115        // writer
12116        synchronized (mPackages) {
12117            if (mSettings.setPackageStoppedStateLPw(packageName, stopped, allowedByPermission,
12118                    uid, userId)) {
12119                scheduleWritePackageRestrictionsLocked(userId);
12120            }
12121        }
12122    }
12123
12124    @Override
12125    public String getInstallerPackageName(String packageName) {
12126        // reader
12127        synchronized (mPackages) {
12128            return mSettings.getInstallerPackageNameLPr(packageName);
12129        }
12130    }
12131
12132    @Override
12133    public int getApplicationEnabledSetting(String packageName, int userId) {
12134        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12135        int uid = Binder.getCallingUid();
12136        enforceCrossUserPermission(uid, userId, false, false, "get enabled");
12137        // reader
12138        synchronized (mPackages) {
12139            return mSettings.getApplicationEnabledSettingLPr(packageName, userId);
12140        }
12141    }
12142
12143    @Override
12144    public int getComponentEnabledSetting(ComponentName componentName, int userId) {
12145        if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED;
12146        int uid = Binder.getCallingUid();
12147        enforceCrossUserPermission(uid, userId, false, false, "get component enabled");
12148        // reader
12149        synchronized (mPackages) {
12150            return mSettings.getComponentEnabledSettingLPr(componentName, userId);
12151        }
12152    }
12153
12154    @Override
12155    public void enterSafeMode() {
12156        enforceSystemOrRoot("Only the system can request entering safe mode");
12157
12158        if (!mSystemReady) {
12159            mSafeMode = true;
12160        }
12161    }
12162
12163    @Override
12164    public void systemReady() {
12165        mSystemReady = true;
12166
12167        // Read the compatibilty setting when the system is ready.
12168        boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(
12169                mContext.getContentResolver(),
12170                android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
12171        PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
12172        if (DEBUG_SETTINGS) {
12173            Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
12174        }
12175
12176        synchronized (mPackages) {
12177            // Verify that all of the preferred activity components actually
12178            // exist.  It is possible for applications to be updated and at
12179            // that point remove a previously declared activity component that
12180            // had been set as a preferred activity.  We try to clean this up
12181            // the next time we encounter that preferred activity, but it is
12182            // possible for the user flow to never be able to return to that
12183            // situation so here we do a sanity check to make sure we haven't
12184            // left any junk around.
12185            ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
12186            for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12187                PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12188                removed.clear();
12189                for (PreferredActivity pa : pir.filterSet()) {
12190                    if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
12191                        removed.add(pa);
12192                    }
12193                }
12194                if (removed.size() > 0) {
12195                    for (int r=0; r<removed.size(); r++) {
12196                        PreferredActivity pa = removed.get(r);
12197                        Slog.w(TAG, "Removing dangling preferred activity: "
12198                                + pa.mPref.mComponent);
12199                        pir.removeFilter(pa);
12200                    }
12201                    mSettings.writePackageRestrictionsLPr(
12202                            mSettings.mPreferredActivities.keyAt(i));
12203                }
12204            }
12205        }
12206        sUserManager.systemReady();
12207
12208        // Kick off any messages waiting for system ready
12209        if (mPostSystemReadyMessages != null) {
12210            for (Message msg : mPostSystemReadyMessages) {
12211                msg.sendToTarget();
12212            }
12213            mPostSystemReadyMessages = null;
12214        }
12215    }
12216
12217    @Override
12218    public boolean isSafeMode() {
12219        return mSafeMode;
12220    }
12221
12222    @Override
12223    public boolean hasSystemUidErrors() {
12224        return mHasSystemUidErrors;
12225    }
12226
12227    static String arrayToString(int[] array) {
12228        StringBuffer buf = new StringBuffer(128);
12229        buf.append('[');
12230        if (array != null) {
12231            for (int i=0; i<array.length; i++) {
12232                if (i > 0) buf.append(", ");
12233                buf.append(array[i]);
12234            }
12235        }
12236        buf.append(']');
12237        return buf.toString();
12238    }
12239
12240    static class DumpState {
12241        public static final int DUMP_LIBS = 1 << 0;
12242        public static final int DUMP_FEATURES = 1 << 1;
12243        public static final int DUMP_RESOLVERS = 1 << 2;
12244        public static final int DUMP_PERMISSIONS = 1 << 3;
12245        public static final int DUMP_PACKAGES = 1 << 4;
12246        public static final int DUMP_SHARED_USERS = 1 << 5;
12247        public static final int DUMP_MESSAGES = 1 << 6;
12248        public static final int DUMP_PROVIDERS = 1 << 7;
12249        public static final int DUMP_VERIFIERS = 1 << 8;
12250        public static final int DUMP_PREFERRED = 1 << 9;
12251        public static final int DUMP_PREFERRED_XML = 1 << 10;
12252        public static final int DUMP_KEYSETS = 1 << 11;
12253        public static final int DUMP_VERSION = 1 << 12;
12254        public static final int DUMP_INSTALLS = 1 << 13;
12255
12256        public static final int OPTION_SHOW_FILTERS = 1 << 0;
12257
12258        private int mTypes;
12259
12260        private int mOptions;
12261
12262        private boolean mTitlePrinted;
12263
12264        private SharedUserSetting mSharedUser;
12265
12266        public boolean isDumping(int type) {
12267            if (mTypes == 0 && type != DUMP_PREFERRED_XML) {
12268                return true;
12269            }
12270
12271            return (mTypes & type) != 0;
12272        }
12273
12274        public void setDump(int type) {
12275            mTypes |= type;
12276        }
12277
12278        public boolean isOptionEnabled(int option) {
12279            return (mOptions & option) != 0;
12280        }
12281
12282        public void setOptionEnabled(int option) {
12283            mOptions |= option;
12284        }
12285
12286        public boolean onTitlePrinted() {
12287            final boolean printed = mTitlePrinted;
12288            mTitlePrinted = true;
12289            return printed;
12290        }
12291
12292        public boolean getTitlePrinted() {
12293            return mTitlePrinted;
12294        }
12295
12296        public void setTitlePrinted(boolean enabled) {
12297            mTitlePrinted = enabled;
12298        }
12299
12300        public SharedUserSetting getSharedUser() {
12301            return mSharedUser;
12302        }
12303
12304        public void setSharedUser(SharedUserSetting user) {
12305            mSharedUser = user;
12306        }
12307    }
12308
12309    @Override
12310    protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
12311        if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP)
12312                != PackageManager.PERMISSION_GRANTED) {
12313            pw.println("Permission Denial: can't dump ActivityManager from from pid="
12314                    + Binder.getCallingPid()
12315                    + ", uid=" + Binder.getCallingUid()
12316                    + " without permission "
12317                    + android.Manifest.permission.DUMP);
12318            return;
12319        }
12320
12321        DumpState dumpState = new DumpState();
12322        boolean fullPreferred = false;
12323        boolean checkin = false;
12324
12325        String packageName = null;
12326
12327        int opti = 0;
12328        while (opti < args.length) {
12329            String opt = args[opti];
12330            if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') {
12331                break;
12332            }
12333            opti++;
12334
12335            if ("-a".equals(opt)) {
12336                // Right now we only know how to print all.
12337            } else if ("-h".equals(opt)) {
12338                pw.println("Package manager dump options:");
12339                pw.println("  [-h] [-f] [--checkin] [cmd] ...");
12340                pw.println("    --checkin: dump for a checkin");
12341                pw.println("    -f: print details of intent filters");
12342                pw.println("    -h: print this help");
12343                pw.println("  cmd may be one of:");
12344                pw.println("    l[ibraries]: list known shared libraries");
12345                pw.println("    f[ibraries]: list device features");
12346                pw.println("    k[eysets]: print known keysets");
12347                pw.println("    r[esolvers]: dump intent resolvers");
12348                pw.println("    perm[issions]: dump permissions");
12349                pw.println("    pref[erred]: print preferred package settings");
12350                pw.println("    preferred-xml [--full]: print preferred package settings as xml");
12351                pw.println("    prov[iders]: dump content providers");
12352                pw.println("    p[ackages]: dump installed packages");
12353                pw.println("    s[hared-users]: dump shared user IDs");
12354                pw.println("    m[essages]: print collected runtime messages");
12355                pw.println("    v[erifiers]: print package verifier info");
12356                pw.println("    version: print database version info");
12357                pw.println("    write: write current settings now");
12358                pw.println("    <package.name>: info about given package");
12359                pw.println("    installs: details about install sessions");
12360                return;
12361            } else if ("--checkin".equals(opt)) {
12362                checkin = true;
12363            } else if ("-f".equals(opt)) {
12364                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12365            } else {
12366                pw.println("Unknown argument: " + opt + "; use -h for help");
12367            }
12368        }
12369
12370        // Is the caller requesting to dump a particular piece of data?
12371        if (opti < args.length) {
12372            String cmd = args[opti];
12373            opti++;
12374            // Is this a package name?
12375            if ("android".equals(cmd) || cmd.contains(".")) {
12376                packageName = cmd;
12377                // When dumping a single package, we always dump all of its
12378                // filter information since the amount of data will be reasonable.
12379                dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS);
12380            } else if ("l".equals(cmd) || "libraries".equals(cmd)) {
12381                dumpState.setDump(DumpState.DUMP_LIBS);
12382            } else if ("f".equals(cmd) || "features".equals(cmd)) {
12383                dumpState.setDump(DumpState.DUMP_FEATURES);
12384            } else if ("r".equals(cmd) || "resolvers".equals(cmd)) {
12385                dumpState.setDump(DumpState.DUMP_RESOLVERS);
12386            } else if ("perm".equals(cmd) || "permissions".equals(cmd)) {
12387                dumpState.setDump(DumpState.DUMP_PERMISSIONS);
12388            } else if ("pref".equals(cmd) || "preferred".equals(cmd)) {
12389                dumpState.setDump(DumpState.DUMP_PREFERRED);
12390            } else if ("preferred-xml".equals(cmd)) {
12391                dumpState.setDump(DumpState.DUMP_PREFERRED_XML);
12392                if (opti < args.length && "--full".equals(args[opti])) {
12393                    fullPreferred = true;
12394                    opti++;
12395                }
12396            } else if ("p".equals(cmd) || "packages".equals(cmd)) {
12397                dumpState.setDump(DumpState.DUMP_PACKAGES);
12398            } else if ("s".equals(cmd) || "shared-users".equals(cmd)) {
12399                dumpState.setDump(DumpState.DUMP_SHARED_USERS);
12400            } else if ("prov".equals(cmd) || "providers".equals(cmd)) {
12401                dumpState.setDump(DumpState.DUMP_PROVIDERS);
12402            } else if ("m".equals(cmd) || "messages".equals(cmd)) {
12403                dumpState.setDump(DumpState.DUMP_MESSAGES);
12404            } else if ("v".equals(cmd) || "verifiers".equals(cmd)) {
12405                dumpState.setDump(DumpState.DUMP_VERIFIERS);
12406            } else if ("version".equals(cmd)) {
12407                dumpState.setDump(DumpState.DUMP_VERSION);
12408            } else if ("k".equals(cmd) || "keysets".equals(cmd)) {
12409                dumpState.setDump(DumpState.DUMP_KEYSETS);
12410            } else if ("installs".equals(cmd)) {
12411                dumpState.setDump(DumpState.DUMP_INSTALLS);
12412            } else if ("write".equals(cmd)) {
12413                synchronized (mPackages) {
12414                    mSettings.writeLPr();
12415                    pw.println("Settings written.");
12416                    return;
12417                }
12418            }
12419        }
12420
12421        if (checkin) {
12422            pw.println("vers,1");
12423        }
12424
12425        // reader
12426        synchronized (mPackages) {
12427            if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) {
12428                if (!checkin) {
12429                    if (dumpState.onTitlePrinted())
12430                        pw.println();
12431                    pw.println("Database versions:");
12432                    pw.print("  SDK Version:");
12433                    pw.print(" internal=");
12434                    pw.print(mSettings.mInternalSdkPlatform);
12435                    pw.print(" external=");
12436                    pw.println(mSettings.mExternalSdkPlatform);
12437                    pw.print("  DB Version:");
12438                    pw.print(" internal=");
12439                    pw.print(mSettings.mInternalDatabaseVersion);
12440                    pw.print(" external=");
12441                    pw.println(mSettings.mExternalDatabaseVersion);
12442                }
12443            }
12444
12445            if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) {
12446                if (!checkin) {
12447                    if (dumpState.onTitlePrinted())
12448                        pw.println();
12449                    pw.println("Verifiers:");
12450                    pw.print("  Required: ");
12451                    pw.print(mRequiredVerifierPackage);
12452                    pw.print(" (uid=");
12453                    pw.print(getPackageUid(mRequiredVerifierPackage, 0));
12454                    pw.println(")");
12455                } else if (mRequiredVerifierPackage != null) {
12456                    pw.print("vrfy,"); pw.print(mRequiredVerifierPackage);
12457                    pw.print(","); pw.println(getPackageUid(mRequiredVerifierPackage, 0));
12458                }
12459            }
12460
12461            if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) {
12462                boolean printedHeader = false;
12463                final Iterator<String> it = mSharedLibraries.keySet().iterator();
12464                while (it.hasNext()) {
12465                    String name = it.next();
12466                    SharedLibraryEntry ent = mSharedLibraries.get(name);
12467                    if (!checkin) {
12468                        if (!printedHeader) {
12469                            if (dumpState.onTitlePrinted())
12470                                pw.println();
12471                            pw.println("Libraries:");
12472                            printedHeader = true;
12473                        }
12474                        pw.print("  ");
12475                    } else {
12476                        pw.print("lib,");
12477                    }
12478                    pw.print(name);
12479                    if (!checkin) {
12480                        pw.print(" -> ");
12481                    }
12482                    if (ent.path != null) {
12483                        if (!checkin) {
12484                            pw.print("(jar) ");
12485                            pw.print(ent.path);
12486                        } else {
12487                            pw.print(",jar,");
12488                            pw.print(ent.path);
12489                        }
12490                    } else {
12491                        if (!checkin) {
12492                            pw.print("(apk) ");
12493                            pw.print(ent.apk);
12494                        } else {
12495                            pw.print(",apk,");
12496                            pw.print(ent.apk);
12497                        }
12498                    }
12499                    pw.println();
12500                }
12501            }
12502
12503            if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) {
12504                if (dumpState.onTitlePrinted())
12505                    pw.println();
12506                if (!checkin) {
12507                    pw.println("Features:");
12508                }
12509                Iterator<String> it = mAvailableFeatures.keySet().iterator();
12510                while (it.hasNext()) {
12511                    String name = it.next();
12512                    if (!checkin) {
12513                        pw.print("  ");
12514                    } else {
12515                        pw.print("feat,");
12516                    }
12517                    pw.println(name);
12518                }
12519            }
12520
12521            if (!checkin && dumpState.isDumping(DumpState.DUMP_RESOLVERS)) {
12522                if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:"
12523                        : "Activity Resolver Table:", "  ", packageName,
12524                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12525                    dumpState.setTitlePrinted(true);
12526                }
12527                if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:"
12528                        : "Receiver Resolver Table:", "  ", packageName,
12529                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12530                    dumpState.setTitlePrinted(true);
12531                }
12532                if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:"
12533                        : "Service Resolver Table:", "  ", packageName,
12534                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12535                    dumpState.setTitlePrinted(true);
12536                }
12537                if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:"
12538                        : "Provider Resolver Table:", "  ", packageName,
12539                        dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS))) {
12540                    dumpState.setTitlePrinted(true);
12541                }
12542            }
12543
12544            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) {
12545                for (int i=0; i<mSettings.mPreferredActivities.size(); i++) {
12546                    PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
12547                    int user = mSettings.mPreferredActivities.keyAt(i);
12548                    if (pir.dump(pw,
12549                            dumpState.getTitlePrinted()
12550                                ? "\nPreferred Activities User " + user + ":"
12551                                : "Preferred Activities User " + user + ":", "  ",
12552                            packageName, true)) {
12553                        dumpState.setTitlePrinted(true);
12554                    }
12555                }
12556            }
12557
12558            if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) {
12559                pw.flush();
12560                FileOutputStream fout = new FileOutputStream(fd);
12561                BufferedOutputStream str = new BufferedOutputStream(fout);
12562                XmlSerializer serializer = new FastXmlSerializer();
12563                try {
12564                    serializer.setOutput(str, "utf-8");
12565                    serializer.startDocument(null, true);
12566                    serializer.setFeature(
12567                            "http://xmlpull.org/v1/doc/features.html#indent-output", true);
12568                    mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred);
12569                    serializer.endDocument();
12570                    serializer.flush();
12571                } catch (IllegalArgumentException e) {
12572                    pw.println("Failed writing: " + e);
12573                } catch (IllegalStateException e) {
12574                    pw.println("Failed writing: " + e);
12575                } catch (IOException e) {
12576                    pw.println("Failed writing: " + e);
12577                }
12578            }
12579
12580            if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) {
12581                mSettings.dumpPermissionsLPr(pw, packageName, dumpState);
12582                if (packageName == null) {
12583                    for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) {
12584                        if (iperm == 0) {
12585                            if (dumpState.onTitlePrinted())
12586                                pw.println();
12587                            pw.println("AppOp Permissions:");
12588                        }
12589                        pw.print("  AppOp Permission ");
12590                        pw.print(mAppOpPermissionPackages.keyAt(iperm));
12591                        pw.println(":");
12592                        ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm);
12593                        for (int ipkg=0; ipkg<pkgs.size(); ipkg++) {
12594                            pw.print("    "); pw.println(pkgs.valueAt(ipkg));
12595                        }
12596                    }
12597                }
12598            }
12599
12600            if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) {
12601                boolean printedSomething = false;
12602                for (PackageParser.Provider p : mProviders.mProviders.values()) {
12603                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12604                        continue;
12605                    }
12606                    if (!printedSomething) {
12607                        if (dumpState.onTitlePrinted())
12608                            pw.println();
12609                        pw.println("Registered ContentProviders:");
12610                        printedSomething = true;
12611                    }
12612                    pw.print("  "); p.printComponentShortName(pw); pw.println(":");
12613                    pw.print("    "); pw.println(p.toString());
12614                }
12615                printedSomething = false;
12616                for (Map.Entry<String, PackageParser.Provider> entry :
12617                        mProvidersByAuthority.entrySet()) {
12618                    PackageParser.Provider p = entry.getValue();
12619                    if (packageName != null && !packageName.equals(p.info.packageName)) {
12620                        continue;
12621                    }
12622                    if (!printedSomething) {
12623                        if (dumpState.onTitlePrinted())
12624                            pw.println();
12625                        pw.println("ContentProvider Authorities:");
12626                        printedSomething = true;
12627                    }
12628                    pw.print("  ["); pw.print(entry.getKey()); pw.println("]:");
12629                    pw.print("    "); pw.println(p.toString());
12630                    if (p.info != null && p.info.applicationInfo != null) {
12631                        final String appInfo = p.info.applicationInfo.toString();
12632                        pw.print("      applicationInfo="); pw.println(appInfo);
12633                    }
12634                }
12635            }
12636
12637            if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) {
12638                mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState);
12639            }
12640
12641            if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) {
12642                mSettings.dumpPackagesLPr(pw, packageName, dumpState, checkin);
12643            }
12644
12645            if (!checkin && dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) {
12646                mSettings.dumpSharedUsersLPr(pw, packageName, dumpState);
12647            }
12648
12649            if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) {
12650                // XXX should handle packageName != null by dumping only install data that
12651                // the given package is involved with.
12652                if (dumpState.onTitlePrinted()) pw.println();
12653                mInstallerService.dump(new IndentingPrintWriter(pw, "  ", 120));
12654            }
12655
12656            if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) {
12657                if (dumpState.onTitlePrinted()) pw.println();
12658                mSettings.dumpReadMessagesLPr(pw, dumpState);
12659
12660                pw.println();
12661                pw.println("Package warning messages:");
12662                final File fname = getSettingsProblemFile();
12663                FileInputStream in = null;
12664                try {
12665                    in = new FileInputStream(fname);
12666                    final int avail = in.available();
12667                    final byte[] data = new byte[avail];
12668                    in.read(data);
12669                    pw.print(new String(data));
12670                } catch (FileNotFoundException e) {
12671                } catch (IOException e) {
12672                } finally {
12673                    if (in != null) {
12674                        try {
12675                            in.close();
12676                        } catch (IOException e) {
12677                        }
12678                    }
12679                }
12680            }
12681
12682            if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) {
12683                BufferedReader in = null;
12684                String line = null;
12685                try {
12686                    in = new BufferedReader(new FileReader(getSettingsProblemFile()));
12687                    while ((line = in.readLine()) != null) {
12688                        pw.print("msg,");
12689                        pw.println(line);
12690                    }
12691                } catch (IOException ignored) {
12692                } finally {
12693                    IoUtils.closeQuietly(in);
12694                }
12695            }
12696        }
12697    }
12698
12699    // ------- apps on sdcard specific code -------
12700    static final boolean DEBUG_SD_INSTALL = false;
12701
12702    private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD";
12703
12704    private static final String SD_ENCRYPTION_ALGORITHM = "AES";
12705
12706    private boolean mMediaMounted = false;
12707
12708    static String getEncryptKey() {
12709        try {
12710            String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString(
12711                    SD_ENCRYPTION_KEYSTORE_NAME);
12712            if (sdEncKey == null) {
12713                sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128,
12714                        SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME);
12715                if (sdEncKey == null) {
12716                    Slog.e(TAG, "Failed to create encryption keys");
12717                    return null;
12718                }
12719            }
12720            return sdEncKey;
12721        } catch (NoSuchAlgorithmException nsae) {
12722            Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae);
12723            return null;
12724        } catch (IOException ioe) {
12725            Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe);
12726            return null;
12727        }
12728    }
12729
12730    /*
12731     * Update media status on PackageManager.
12732     */
12733    @Override
12734    public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) {
12735        int callingUid = Binder.getCallingUid();
12736        if (callingUid != 0 && callingUid != Process.SYSTEM_UID) {
12737            throw new SecurityException("Media status can only be updated by the system");
12738        }
12739        // reader; this apparently protects mMediaMounted, but should probably
12740        // be a different lock in that case.
12741        synchronized (mPackages) {
12742            Log.i(TAG, "Updating external media status from "
12743                    + (mMediaMounted ? "mounted" : "unmounted") + " to "
12744                    + (mediaStatus ? "mounted" : "unmounted"));
12745            if (DEBUG_SD_INSTALL)
12746                Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus
12747                        + ", mMediaMounted=" + mMediaMounted);
12748            if (mediaStatus == mMediaMounted) {
12749                final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1
12750                        : 0, -1);
12751                mHandler.sendMessage(msg);
12752                return;
12753            }
12754            mMediaMounted = mediaStatus;
12755        }
12756        // Queue up an async operation since the package installation may take a
12757        // little while.
12758        mHandler.post(new Runnable() {
12759            public void run() {
12760                updateExternalMediaStatusInner(mediaStatus, reportStatus, true);
12761            }
12762        });
12763    }
12764
12765    /**
12766     * Called by MountService when the initial ASECs to scan are available.
12767     * Should block until all the ASEC containers are finished being scanned.
12768     */
12769    public void scanAvailableAsecs() {
12770        updateExternalMediaStatusInner(true, false, false);
12771        if (mShouldRestoreconData) {
12772            SELinuxMMAC.setRestoreconDone();
12773            mShouldRestoreconData = false;
12774        }
12775    }
12776
12777    /*
12778     * Collect information of applications on external media, map them against
12779     * existing containers and update information based on current mount status.
12780     * Please note that we always have to report status if reportStatus has been
12781     * set to true especially when unloading packages.
12782     */
12783    private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus,
12784            boolean externalStorage) {
12785        ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>();
12786        int[] uidArr = EmptyArray.INT;
12787
12788        final String[] list = PackageHelper.getSecureContainerList();
12789        if (ArrayUtils.isEmpty(list)) {
12790            Log.i(TAG, "No secure containers found");
12791        } else {
12792            // Process list of secure containers and categorize them
12793            // as active or stale based on their package internal state.
12794
12795            // reader
12796            synchronized (mPackages) {
12797                for (String cid : list) {
12798                    // Leave stages untouched for now; installer service owns them
12799                    if (PackageInstallerService.isStageName(cid)) continue;
12800
12801                    if (DEBUG_SD_INSTALL)
12802                        Log.i(TAG, "Processing container " + cid);
12803                    String pkgName = getAsecPackageName(cid);
12804                    if (pkgName == null) {
12805                        Slog.i(TAG, "Found stale container " + cid + " with no package name");
12806                        continue;
12807                    }
12808                    if (DEBUG_SD_INSTALL)
12809                        Log.i(TAG, "Looking for pkg : " + pkgName);
12810
12811                    final PackageSetting ps = mSettings.mPackages.get(pkgName);
12812                    if (ps == null) {
12813                        Slog.i(TAG, "Found stale container " + cid + " with no matching settings");
12814                        continue;
12815                    }
12816
12817                    /*
12818                     * Skip packages that are not external if we're unmounting
12819                     * external storage.
12820                     */
12821                    if (externalStorage && !isMounted && !isExternal(ps)) {
12822                        continue;
12823                    }
12824
12825                    final AsecInstallArgs args = new AsecInstallArgs(cid,
12826                            getAppDexInstructionSets(ps), isForwardLocked(ps));
12827                    // The package status is changed only if the code path
12828                    // matches between settings and the container id.
12829                    if (ps.codePathString != null
12830                            && ps.codePathString.startsWith(args.getCodePath())) {
12831                        if (DEBUG_SD_INSTALL) {
12832                            Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName
12833                                    + " at code path: " + ps.codePathString);
12834                        }
12835
12836                        // We do have a valid package installed on sdcard
12837                        processCids.put(args, ps.codePathString);
12838                        final int uid = ps.appId;
12839                        if (uid != -1) {
12840                            uidArr = ArrayUtils.appendInt(uidArr, uid);
12841                        }
12842                    } else {
12843                        Slog.i(TAG, "Found stale container " + cid + ": expected codePath="
12844                                + ps.codePathString);
12845                    }
12846                }
12847            }
12848
12849            Arrays.sort(uidArr);
12850        }
12851
12852        // Process packages with valid entries.
12853        if (isMounted) {
12854            if (DEBUG_SD_INSTALL)
12855                Log.i(TAG, "Loading packages");
12856            loadMediaPackages(processCids, uidArr);
12857            startCleaningPackages();
12858            mInstallerService.onSecureContainersAvailable();
12859        } else {
12860            if (DEBUG_SD_INSTALL)
12861                Log.i(TAG, "Unloading packages");
12862            unloadMediaPackages(processCids, uidArr, reportStatus);
12863        }
12864    }
12865
12866    private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing,
12867            ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) {
12868        int size = pkgList.size();
12869        if (size > 0) {
12870            // Send broadcasts here
12871            Bundle extras = new Bundle();
12872            extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList
12873                    .toArray(new String[size]));
12874            if (uidArr != null) {
12875                extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr);
12876            }
12877            if (replacing) {
12878                extras.putBoolean(Intent.EXTRA_REPLACING, replacing);
12879            }
12880            String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE
12881                    : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE;
12882            sendPackageBroadcast(action, null, extras, null, finishedReceiver, null);
12883        }
12884    }
12885
12886   /*
12887     * Look at potentially valid container ids from processCids If package
12888     * information doesn't match the one on record or package scanning fails,
12889     * the cid is added to list of removeCids. We currently don't delete stale
12890     * containers.
12891     */
12892    private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr) {
12893        ArrayList<String> pkgList = new ArrayList<String>();
12894        Set<AsecInstallArgs> keys = processCids.keySet();
12895
12896        for (AsecInstallArgs args : keys) {
12897            String codePath = processCids.get(args);
12898            if (DEBUG_SD_INSTALL)
12899                Log.i(TAG, "Loading container : " + args.cid);
12900            int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR;
12901            try {
12902                // Make sure there are no container errors first.
12903                if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) {
12904                    Slog.e(TAG, "Failed to mount cid : " + args.cid
12905                            + " when installing from sdcard");
12906                    continue;
12907                }
12908                // Check code path here.
12909                if (codePath == null || !codePath.startsWith(args.getCodePath())) {
12910                    Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath()
12911                            + " does not match one in settings " + codePath);
12912                    continue;
12913                }
12914                // Parse package
12915                int parseFlags = mDefParseFlags;
12916                if (args.isExternal()) {
12917                    parseFlags |= PackageParser.PARSE_ON_SDCARD;
12918                }
12919                if (args.isFwdLocked()) {
12920                    parseFlags |= PackageParser.PARSE_FORWARD_LOCK;
12921                }
12922
12923                synchronized (mInstallLock) {
12924                    PackageParser.Package pkg = null;
12925                    try {
12926                        pkg = scanPackageLI(new File(codePath), parseFlags, 0, 0, null);
12927                    } catch (PackageManagerException e) {
12928                        Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage());
12929                    }
12930                    // Scan the package
12931                    if (pkg != null) {
12932                        /*
12933                         * TODO why is the lock being held? doPostInstall is
12934                         * called in other places without the lock. This needs
12935                         * to be straightened out.
12936                         */
12937                        // writer
12938                        synchronized (mPackages) {
12939                            retCode = PackageManager.INSTALL_SUCCEEDED;
12940                            pkgList.add(pkg.packageName);
12941                            // Post process args
12942                            args.doPostInstall(PackageManager.INSTALL_SUCCEEDED,
12943                                    pkg.applicationInfo.uid);
12944                        }
12945                    } else {
12946                        Slog.i(TAG, "Failed to install pkg from  " + codePath + " from sdcard");
12947                    }
12948                }
12949
12950            } finally {
12951                if (retCode != PackageManager.INSTALL_SUCCEEDED) {
12952                    Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode);
12953                }
12954            }
12955        }
12956        // writer
12957        synchronized (mPackages) {
12958            // If the platform SDK has changed since the last time we booted,
12959            // we need to re-grant app permission to catch any new ones that
12960            // appear. This is really a hack, and means that apps can in some
12961            // cases get permissions that the user didn't initially explicitly
12962            // allow... it would be nice to have some better way to handle
12963            // this situation.
12964            final boolean regrantPermissions = mSettings.mExternalSdkPlatform != mSdkVersion;
12965            if (regrantPermissions)
12966                Slog.i(TAG, "Platform changed from " + mSettings.mExternalSdkPlatform + " to "
12967                        + mSdkVersion + "; regranting permissions for external storage");
12968            mSettings.mExternalSdkPlatform = mSdkVersion;
12969
12970            // Make sure group IDs have been assigned, and any permission
12971            // changes in other apps are accounted for
12972            updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL
12973                    | (regrantPermissions
12974                            ? (UPDATE_PERMISSIONS_REPLACE_PKG|UPDATE_PERMISSIONS_REPLACE_ALL)
12975                            : 0));
12976
12977            mSettings.updateExternalDatabaseVersion();
12978
12979            // can downgrade to reader
12980            // Persist settings
12981            mSettings.writeLPr();
12982        }
12983        // Send a broadcast to let everyone know we are done processing
12984        if (pkgList.size() > 0) {
12985            sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null);
12986        }
12987    }
12988
12989   /*
12990     * Utility method to unload a list of specified containers
12991     */
12992    private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) {
12993        // Just unmount all valid containers.
12994        for (AsecInstallArgs arg : cidArgs) {
12995            synchronized (mInstallLock) {
12996                arg.doPostDeleteLI(false);
12997           }
12998       }
12999   }
13000
13001    /*
13002     * Unload packages mounted on external media. This involves deleting package
13003     * data from internal structures, sending broadcasts about diabled packages,
13004     * gc'ing to free up references, unmounting all secure containers
13005     * corresponding to packages on external media, and posting a
13006     * UPDATED_MEDIA_STATUS message if status has been requested. Please note
13007     * that we always have to post this message if status has been requested no
13008     * matter what.
13009     */
13010    private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[],
13011            final boolean reportStatus) {
13012        if (DEBUG_SD_INSTALL)
13013            Log.i(TAG, "unloading media packages");
13014        ArrayList<String> pkgList = new ArrayList<String>();
13015        ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>();
13016        final Set<AsecInstallArgs> keys = processCids.keySet();
13017        for (AsecInstallArgs args : keys) {
13018            String pkgName = args.getPackageName();
13019            if (DEBUG_SD_INSTALL)
13020                Log.i(TAG, "Trying to unload pkg : " + pkgName);
13021            // Delete package internally
13022            PackageRemovedInfo outInfo = new PackageRemovedInfo();
13023            synchronized (mInstallLock) {
13024                boolean res = deletePackageLI(pkgName, null, false, null, null,
13025                        PackageManager.DELETE_KEEP_DATA, outInfo, false);
13026                if (res) {
13027                    pkgList.add(pkgName);
13028                } else {
13029                    Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName);
13030                    failedList.add(args);
13031                }
13032            }
13033        }
13034
13035        // reader
13036        synchronized (mPackages) {
13037            // We didn't update the settings after removing each package;
13038            // write them now for all packages.
13039            mSettings.writeLPr();
13040        }
13041
13042        // We have to absolutely send UPDATED_MEDIA_STATUS only
13043        // after confirming that all the receivers processed the ordered
13044        // broadcast when packages get disabled, force a gc to clean things up.
13045        // and unload all the containers.
13046        if (pkgList.size() > 0) {
13047            sendResourcesChangedBroadcast(false, false, pkgList, uidArr,
13048                    new IIntentReceiver.Stub() {
13049                public void performReceive(Intent intent, int resultCode, String data,
13050                        Bundle extras, boolean ordered, boolean sticky,
13051                        int sendingUser) throws RemoteException {
13052                    Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS,
13053                            reportStatus ? 1 : 0, 1, keys);
13054                    mHandler.sendMessage(msg);
13055                }
13056            });
13057        } else {
13058            Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1,
13059                    keys);
13060            mHandler.sendMessage(msg);
13061        }
13062    }
13063
13064    /** Binder call */
13065    @Override
13066    public void movePackage(final String packageName, final IPackageMoveObserver observer,
13067            final int flags) {
13068        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null);
13069        UserHandle user = new UserHandle(UserHandle.getCallingUserId());
13070        int returnCode = PackageManager.MOVE_SUCCEEDED;
13071        int currInstallFlags = 0;
13072        int newInstallFlags = 0;
13073
13074        File codeFile = null;
13075        String installerPackageName = null;
13076        String packageAbiOverride = null;
13077
13078        // reader
13079        synchronized (mPackages) {
13080            final PackageParser.Package pkg = mPackages.get(packageName);
13081            final PackageSetting ps = mSettings.mPackages.get(packageName);
13082            if (pkg == null || ps == null) {
13083                returnCode = PackageManager.MOVE_FAILED_DOESNT_EXIST;
13084            } else {
13085                // Disable moving fwd locked apps and system packages
13086                if (pkg.applicationInfo != null && isSystemApp(pkg)) {
13087                    Slog.w(TAG, "Cannot move system application");
13088                    returnCode = PackageManager.MOVE_FAILED_SYSTEM_PACKAGE;
13089                } else if (pkg.mOperationPending) {
13090                    Slog.w(TAG, "Attempt to move package which has pending operations");
13091                    returnCode = PackageManager.MOVE_FAILED_OPERATION_PENDING;
13092                } else {
13093                    // Find install location first
13094                    if ((flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13095                            && (flags & PackageManager.MOVE_INTERNAL) != 0) {
13096                        Slog.w(TAG, "Ambigous flags specified for move location.");
13097                        returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13098                    } else {
13099                        newInstallFlags = (flags & PackageManager.MOVE_EXTERNAL_MEDIA) != 0
13100                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13101                        currInstallFlags = isExternal(pkg)
13102                                ? PackageManager.INSTALL_EXTERNAL : PackageManager.INSTALL_INTERNAL;
13103
13104                        if (newInstallFlags == currInstallFlags) {
13105                            Slog.w(TAG, "No move required. Trying to move to same location");
13106                            returnCode = PackageManager.MOVE_FAILED_INVALID_LOCATION;
13107                        } else {
13108                            if (isForwardLocked(pkg)) {
13109                                currInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13110                                newInstallFlags |= PackageManager.INSTALL_FORWARD_LOCK;
13111                            }
13112                        }
13113                    }
13114                    if (returnCode == PackageManager.MOVE_SUCCEEDED) {
13115                        pkg.mOperationPending = true;
13116                    }
13117                }
13118
13119                codeFile = new File(pkg.codePath);
13120                installerPackageName = ps.installerPackageName;
13121                packageAbiOverride = ps.cpuAbiOverrideString;
13122            }
13123        }
13124
13125        if (returnCode != PackageManager.MOVE_SUCCEEDED) {
13126            try {
13127                observer.packageMoved(packageName, returnCode);
13128            } catch (RemoteException ignored) {
13129            }
13130            return;
13131        }
13132
13133        final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {
13134            @Override
13135            public void onUserActionRequired(Intent intent) throws RemoteException {
13136                throw new IllegalStateException();
13137            }
13138
13139            @Override
13140            public void onPackageInstalled(String basePackageName, int returnCode, String msg,
13141                    Bundle extras) throws RemoteException {
13142                Slog.d(TAG, "Install result for move: "
13143                        + PackageManager.installStatusToString(returnCode, msg));
13144
13145                // We usually have a new package now after the install, but if
13146                // we failed we need to clear the pending flag on the original
13147                // package object.
13148                synchronized (mPackages) {
13149                    final PackageParser.Package pkg = mPackages.get(packageName);
13150                    if (pkg != null) {
13151                        pkg.mOperationPending = false;
13152                    }
13153                }
13154
13155                final int status = PackageManager.installStatusToPublicStatus(returnCode);
13156                switch (status) {
13157                    case PackageInstaller.STATUS_SUCCESS:
13158                        observer.packageMoved(packageName, PackageManager.MOVE_SUCCEEDED);
13159                        break;
13160                    case PackageInstaller.STATUS_FAILURE_STORAGE:
13161                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
13162                        break;
13163                    default:
13164                        observer.packageMoved(packageName, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
13165                        break;
13166                }
13167            }
13168        };
13169
13170        // Treat a move like reinstalling an existing app, which ensures that we
13171        // process everythign uniformly, like unpacking native libraries.
13172        newInstallFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
13173
13174        final Message msg = mHandler.obtainMessage(INIT_COPY);
13175        final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
13176        msg.obj = new InstallParams(origin, installObserver, newInstallFlags,
13177                installerPackageName, null, user, packageAbiOverride);
13178        mHandler.sendMessage(msg);
13179    }
13180
13181    @Override
13182    public boolean setInstallLocation(int loc) {
13183        mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS,
13184                null);
13185        if (getInstallLocation() == loc) {
13186            return true;
13187        }
13188        if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL
13189                || loc == PackageHelper.APP_INSTALL_EXTERNAL) {
13190            android.provider.Settings.Global.putInt(mContext.getContentResolver(),
13191                    android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc);
13192            return true;
13193        }
13194        return false;
13195   }
13196
13197    @Override
13198    public int getInstallLocation() {
13199        return android.provider.Settings.Global.getInt(mContext.getContentResolver(),
13200                android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION,
13201                PackageHelper.APP_INSTALL_AUTO);
13202    }
13203
13204    /** Called by UserManagerService */
13205    void cleanUpUserLILPw(UserManagerService userManager, int userHandle) {
13206        mDirtyUsers.remove(userHandle);
13207        mSettings.removeUserLPw(userHandle);
13208        mPendingBroadcasts.remove(userHandle);
13209        if (mInstaller != null) {
13210            // Technically, we shouldn't be doing this with the package lock
13211            // held.  However, this is very rare, and there is already so much
13212            // other disk I/O going on, that we'll let it slide for now.
13213            mInstaller.removeUserDataDirs(userHandle);
13214        }
13215        mUserNeedsBadging.delete(userHandle);
13216        removeUnusedPackagesLILPw(userManager, userHandle);
13217    }
13218
13219    /**
13220     * We're removing userHandle and would like to remove any downloaded packages
13221     * that are no longer in use by any other user.
13222     * @param userHandle the user being removed
13223     */
13224    private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) {
13225        final boolean DEBUG_CLEAN_APKS = false;
13226        int [] users = userManager.getUserIdsLPr();
13227        Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator();
13228        while (psit.hasNext()) {
13229            PackageSetting ps = psit.next();
13230            if (ps.pkg == null) {
13231                continue;
13232            }
13233            final String packageName = ps.pkg.packageName;
13234            // Skip over if system app
13235            if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) {
13236                continue;
13237            }
13238            if (DEBUG_CLEAN_APKS) {
13239                Slog.i(TAG, "Checking package " + packageName);
13240            }
13241            boolean keep = false;
13242            for (int i = 0; i < users.length; i++) {
13243                if (users[i] != userHandle && ps.getInstalled(users[i])) {
13244                    keep = true;
13245                    if (DEBUG_CLEAN_APKS) {
13246                        Slog.i(TAG, "  Keeping package " + packageName + " for user "
13247                                + users[i]);
13248                    }
13249                    break;
13250                }
13251            }
13252            if (!keep) {
13253                if (DEBUG_CLEAN_APKS) {
13254                    Slog.i(TAG, "  Removing package " + packageName);
13255                }
13256                mHandler.post(new Runnable() {
13257                    public void run() {
13258                        deletePackageX(packageName, userHandle, 0);
13259                    } //end run
13260                });
13261            }
13262        }
13263    }
13264
13265    /** Called by UserManagerService */
13266    void createNewUserLILPw(int userHandle, File path) {
13267        if (mInstaller != null) {
13268            mInstaller.createUserConfig(userHandle);
13269            mSettings.createNewUserLILPw(this, mInstaller, userHandle, path);
13270        }
13271    }
13272
13273    @Override
13274    public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException {
13275        mContext.enforceCallingOrSelfPermission(
13276                android.Manifest.permission.PACKAGE_VERIFICATION_AGENT,
13277                "Only package verification agents can read the verifier device identity");
13278
13279        synchronized (mPackages) {
13280            return mSettings.getVerifierDeviceIdentityLPw();
13281        }
13282    }
13283
13284    @Override
13285    public void setPermissionEnforced(String permission, boolean enforced) {
13286        mContext.enforceCallingOrSelfPermission(GRANT_REVOKE_PERMISSIONS, null);
13287        if (READ_EXTERNAL_STORAGE.equals(permission)) {
13288            synchronized (mPackages) {
13289                if (mSettings.mReadExternalStorageEnforced == null
13290                        || mSettings.mReadExternalStorageEnforced != enforced) {
13291                    mSettings.mReadExternalStorageEnforced = enforced;
13292                    mSettings.writeLPr();
13293                }
13294            }
13295            // kill any non-foreground processes so we restart them and
13296            // grant/revoke the GID.
13297            final IActivityManager am = ActivityManagerNative.getDefault();
13298            if (am != null) {
13299                final long token = Binder.clearCallingIdentity();
13300                try {
13301                    am.killProcessesBelowForeground("setPermissionEnforcement");
13302                } catch (RemoteException e) {
13303                } finally {
13304                    Binder.restoreCallingIdentity(token);
13305                }
13306            }
13307        } else {
13308            throw new IllegalArgumentException("No selective enforcement for " + permission);
13309        }
13310    }
13311
13312    @Override
13313    @Deprecated
13314    public boolean isPermissionEnforced(String permission) {
13315        return true;
13316    }
13317
13318    @Override
13319    public boolean isStorageLow() {
13320        final long token = Binder.clearCallingIdentity();
13321        try {
13322            final DeviceStorageMonitorInternal
13323                    dsm = LocalServices.getService(DeviceStorageMonitorInternal.class);
13324            if (dsm != null) {
13325                return dsm.isMemoryLow();
13326            } else {
13327                return false;
13328            }
13329        } finally {
13330            Binder.restoreCallingIdentity(token);
13331        }
13332    }
13333
13334    @Override
13335    public IPackageInstaller getPackageInstaller() {
13336        return mInstallerService;
13337    }
13338
13339    private boolean userNeedsBadging(int userId) {
13340        int index = mUserNeedsBadging.indexOfKey(userId);
13341        if (index < 0) {
13342            final UserInfo userInfo;
13343            final long token = Binder.clearCallingIdentity();
13344            try {
13345                userInfo = sUserManager.getUserInfo(userId);
13346            } finally {
13347                Binder.restoreCallingIdentity(token);
13348            }
13349            final boolean b;
13350            if (userInfo != null && userInfo.isManagedProfile()) {
13351                b = true;
13352            } else {
13353                b = false;
13354            }
13355            mUserNeedsBadging.put(userId, b);
13356            return b;
13357        }
13358        return mUserNeedsBadging.valueAt(index);
13359    }
13360
13361    @Override
13362    public KeySet getKeySetByAlias(String packageName, String alias) {
13363        if (packageName == null || alias == null) {
13364            return null;
13365        }
13366        synchronized(mPackages) {
13367            final PackageParser.Package pkg = mPackages.get(packageName);
13368            if (pkg == null) {
13369                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13370                throw new IllegalArgumentException("Unknown package: " + packageName);
13371            }
13372            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13373            return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias));
13374        }
13375    }
13376
13377    @Override
13378    public KeySet getSigningKeySet(String packageName) {
13379        if (packageName == null) {
13380            return null;
13381        }
13382        synchronized(mPackages) {
13383            final PackageParser.Package pkg = mPackages.get(packageName);
13384            if (pkg == null) {
13385                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13386                throw new IllegalArgumentException("Unknown package: " + packageName);
13387            }
13388            if (pkg.applicationInfo.uid != Binder.getCallingUid()
13389                    && Process.SYSTEM_UID != Binder.getCallingUid()) {
13390                throw new SecurityException("May not access signing KeySet of other apps.");
13391            }
13392            KeySetManagerService ksms = mSettings.mKeySetManagerService;
13393            return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName));
13394        }
13395    }
13396
13397    @Override
13398    public boolean isPackageSignedByKeySet(String packageName, KeySet ks) {
13399        if (packageName == null || ks == null) {
13400            return false;
13401        }
13402        synchronized(mPackages) {
13403            final PackageParser.Package pkg = mPackages.get(packageName);
13404            if (pkg == null) {
13405                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13406                throw new IllegalArgumentException("Unknown package: " + packageName);
13407            }
13408            IBinder ksh = ks.getToken();
13409            if (ksh instanceof KeySetHandle) {
13410                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13411                return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh);
13412            }
13413            return false;
13414        }
13415    }
13416
13417    @Override
13418    public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) {
13419        if (packageName == null || ks == null) {
13420            return false;
13421        }
13422        synchronized(mPackages) {
13423            final PackageParser.Package pkg = mPackages.get(packageName);
13424            if (pkg == null) {
13425                Slog.w(TAG, "KeySet requested for unknown package:" + packageName);
13426                throw new IllegalArgumentException("Unknown package: " + packageName);
13427            }
13428            IBinder ksh = ks.getToken();
13429            if (ksh instanceof KeySetHandle) {
13430                KeySetManagerService ksms = mSettings.mKeySetManagerService;
13431                return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh);
13432            }
13433            return false;
13434        }
13435    }
13436}
13437